A or(A a, A b) {
return a != null ? a : b;
}
// PersistableThrowable doesn't hold GC-disturbing class references in backtrace
static volatile PersistableThrowable lastException_lastException;
static PersistableThrowable lastException() {
return lastException_lastException;
}
static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }
static String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url))) return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=");
}
static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static void rotateStringBuffer(StringBuffer buf, int max) { try {
if (buf == null) return;
synchronized(buf) {
if (buf.length() <= max) return;
try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) { throw rethrow(__e); } }
static void rotateStringBuilder(StringBuilder buf, int max) { try {
if (buf == null) return;
synchronized(buf) {
if (buf.length() <= max) return;
try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) { throw rethrow(__e); } }
static void _onJavaXSet() {}
static boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static boolean swic(String a, String b, Matches m) {
if (!swic(a, b)) return false;
m.m = new String[] {substring(a, l(b))};
return true;
}
static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static boolean containsNewLines(String s) {
return containsNewLine(s);
}
static String jlabel_textAsHTML_center(String text) {
return ""
+ replace(htmlencode2(text), "\n", "
")
+ "
";
}
static Object callOpt_withVarargs(Object o, String method, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me == null) {
// TODO: varargs
return null;
}
if ((me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
return null;
}
} catch (Exception __e) { throw rethrow(__e); } }
static JButton jbutton(String text, Runnable action) {
return newButton(text, action);
}
static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
// button without action
static JButton jbutton(String text) {
return newButton(text, null);
}
/*static JButton jbutton(BufferedImage img, O action) {
ret setButtonImage(img, jbutton("", action));
}*/
static JButton jbutton(Action action) {
return swingNu(JButton.class, action);
}
static int isAndroid_flag;
static boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static Boolean isHeadless_cache;
static boolean isHeadless() {
if (isHeadless_cache != null) return isHeadless_cache;
if (isAndroid()) return isHeadless_cache = true;
if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true;
// Also check if AWT actually works.
// If DISPLAY variable is set but no X server up, this will notice.
try {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) { return isHeadless_cache = true; }
}
static List> _threadInfo_makers = synchroList();
static Object _threadInfo() {
if (empty(_threadInfo_makers)) return null;
HashMap map = new HashMap();
pcallFAll(_threadInfo_makers, map);
return map;
}
static Runnable asRunnable(Object o) {
return toRunnable(o);
}
static void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static String shortenClassName(String name) {
if (name == null) return null;
int i = lastIndexOf(name, "$");
if (i < 0) i = lastIndexOf(name, ".");
return i < 0 ? name : substring(name, i+1);
}
static Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static void newPing() {
var tl = newPing_actionTL();
Runnable action = tl == null ? null : tl.get();
{ if (action != null) action.run(); }
}
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
if (o instanceof ThreadLocal) // TODO: remove this
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static boolean isTrue(Boolean b) {
return b != null && b.booleanValue();
}
static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static Throwable _storeException_value;
static void _storeException(Throwable e) {
_storeException_value = e;
}
static Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static Map syncHashMap() {
return synchroHashMap();
}
static int iround(double d) {
return (int) Math.round(d);
}
static int iround(Number n) {
return iround(toDouble(n));
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0) throw fail("0 is not a snippet ID");
return id;
}
static boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static File loadImageAsFile(String snippetIDOrURL) { try {
if (isURL(snippetIDOrURL))
throw fail("not implemented");
if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
String snippetID = "" + parseSnippetID(snippetIDOrURL);
File file = imageSnippetCacheFile(snippetID);
if (fileSize(file) > 0) return file;
String imageURL = snippetImageURL_noHttps(snippetID);
System.err.println("Loading image: " + imageURL);
byte[] data = loadBinaryPage(imageURL);
saveBinaryFile(file, data);
return file;
} catch (Exception __e) { throw rethrow(__e); } }
// If you change this, also change DiskSnippetCache_fileToLibID
static File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
// Data files are immutable, use centralized cache
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = DiskSnippetCache_file(snippetID);
return file.exists() ? file : null;
}
public static File DiskSnippetCache_getLibrary(String snippetID) { try {
return DiskSnippetCache_getLibrary(psI(snippetID));
} catch (Exception __e) { throw rethrow(__e); } }
public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(DiskSnippetCache_file(snippetID), data);
}
static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL(dataSnippetLink(snippetID));
print("Loading library: " + hideCredentials(url));
try {
data = loadBinaryPage(url.openConnection());
} catch (RuntimeException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID));
print("Loading library: " + hideCredentials(url));
data = loadBinaryPage(url.openConnection());
}
print("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
static long fileSize(String path) { return getFileSize(path); }
static long fileSize(File f) { return getFileSize(f); }
static File loadDataSnippetToFile(String snippetID) { try {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
return loadDataSnippetToFile_noResourceLoader(snippetID);
} catch (Exception __e) { throw rethrow(__e); } }
static File loadDataSnippetToFile_noResourceLoader(String snippetID) { try {
snippetID = fsI(snippetID);
File f = DiskSnippetCache_file(parseSnippetID(snippetID));
List urlsTried = new ArrayList();
List errors = new ArrayList();
try {
URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
print("Loading library: " + hideCredentials(url));
try {
loadBinaryPageToFile(openConnection(url), f);
if (fileSize(f) == 0) throw fail();
} catch (Throwable e) {
errors.add(e);
url = addAndReturn(urlsTried, new URL(tb_mainServer() + "/blobs/" + psI(snippetID)));
print(e);
print("Trying other server: " + hideCredentials(url));
loadBinaryPageToFile(openConnection(url), f);
print("Got bytes: " + fileSize(f));
}
// TODO: check if we hit the "LOADING" message
if (fileSize(f) == 0) throw fail();
System.err.println("Bytes loaded: " + fileSize(f));
} catch (Throwable e) {
//printStackTrace(e);
errors.add(e);
throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
}
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] isGIF_magic = bytesFromHex("47494638"); // Actual signature is longer, but we're lazy
static boolean isGIF(byte[] data) {
return byteArrayStartsWith(data, isGIF_magic);
}
static boolean isGIF(File f) {
return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
}
static void setVar(IVar v, A value) {
if (v != null) v.set(value);
}
static IVF1 setVar(IVar v) {
return a -> { if (v != null) v.set(a); };
}
static boolean loadBufferedImage_useImageCache = true;
static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try {
ping();
if (snippetIDOrURLOrFile == null) return null;
if (isURL(snippetIDOrURLOrFile))
return imageIO_readURL(snippetIDOrURLOrFile);
if (isSnippetID(snippetIDOrURLOrFile)) {
String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return loadBufferedImage(rl.loadLibrary(snippetID));
File dir = imageSnippetsCacheDir();
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
try {
return ImageIO.read(file);
} catch (Throwable e) {
e.printStackTrace();
// fall back to loading from sourceforge
}
}
String imageURL = snippetImageURL_http(snippetID);
print("Loading image: " + imageURL);
BufferedImage image = imageIO_readURL(imageURL);
if (loadBufferedImage_useImageCache) {
File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
ImageIO.write(image, "png", tempFile);
tempFile.renameTo(new File(dir, snippetID + ".png"));
//Log.info("Cached image.");
}
//Log.info("Loaded image.");
return image;
} else
return loadBufferedImage(new File(snippetIDOrURLOrFile));
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage loadBufferedImage(File file) {
return loadBufferedImageFile(file);
}
static A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
static String javaTok_substringN(String s, int i, int j) {
if (i == j) return "";
if (j == i+1 && s.charAt(i) == ' ') return " ";
return s.substring(i, j);
}
static String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
static boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static boolean regionMatches(String a, int offsetA, String b, int offsetB, int len) {
return a != null && b != null && a.regionMatches(offsetA, b, offsetB, len);
}
static boolean regionMatches(String a, int offsetA, String b) {
return regionMatches(a, offsetA, b, 0, l(b));
}
static List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j-i
&& s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static Map synchronizedMRUCache(int maxSize) {
return synchroMap(new MRUCache(maxSize));
}
static String[] codeTokensAsStringArray(List tok) {
int n = max(0, (l(tok)-1)/2);
String[] out = new String[n];
for (int i = 0; i < n; i++)
out[i] = tok.get(i*2+1);
return out;
}
static int jfind(String s, String in) {
return jfind(javaTok(s), in);
}
static int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, null);
}
static int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static int jfind(List tok, String in, ITokCondition condition) { return jfind(tok, 1, in, condition); }
static int jfind(List tok, int startIndex, String in, ITokCondition condition) {
return jfind(tok, startIndex, in, (Object) condition);
}
static int jfind(List tok, int startIdx, String in, Object condition) {
//LS tokin = jfind_preprocess(javaTok(in));
return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
}
// assumes you preprocessed tokin
static int jfind(List tok, List tokin) {
return jfind(tok, 1, tokin);
}
static int jfind(List tok, int startIdx, List tokin) {
return jfind(tok, startIdx, tokin, null);
}
static int jfind(List tok, int startIdx, String[] tokinC, Object condition) {
return findCodeTokens(tok, startIdx, false, tokinC, condition);
}
static int jfind(List tok, int startIdx, List tokin, Object condition) {
return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
}
static List jfind_preprocess(List tok) {
for (String type : litlist("quoted", "id", "int"))
replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
return tok;
}
static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
// supports the usual quotings (", variable length double brackets) except ' quoting
static boolean isQuoted(String s) {
if (isNormalQuoted(s)) return true; // use the exact version
return isMultilineQuoted(s);
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
static boolean eqic(Symbol a, Symbol b) {
return eq(a, b);
}
static boolean eqic(Symbol a, String b) {
return eqic(asString(a), b);
}
static boolean eqic(char a, char b) {
if (a == b) return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2) return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static boolean checkTokCondition(Object condition, List tok, int i) {
if (condition instanceof TokCondition)
return ((TokCondition) condition).get(tok, i);
return checkCondition(condition, tok, i);
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Iterable it, Object a) {
if (it != null)
for (Object o : it)
if (eq(a, o))
return true;
return false;
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static boolean contains(Rect r, Pt p) { return rectContains(r, p); }
static void replaceCollection(Collection dest, Collection src) {
if (dest == src) return;
dest.clear();
if (src != null) dest.addAll(src);
}
static String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
static String joinSubList(List l, int i) {
return join(subList(l, i));
}
static void replaceListPart(List l, int i, int j, List l2) {
replaceSublist(l, i, j, l2);
}
static ThreadLocal assertVerbose_value = new ThreadLocal();
static void assertVerbose(boolean b) {
assertVerbose_value.set(b);
}
static boolean assertVerbose() { return isTrue(assertVerbose_value.get()); }
static A assertEqualsVerbose(Object x, A y) {
assertEqualsVerbose((String) null, x, y);
return y;
}
// x = expected, y = actual
static A assertEqualsVerbose(String msg, Object x, A y) {
if (!eq(x, y)) {
throw fail((nempty(msg) ? msg + ": " : "") + "expected: "+ x + ", got: " + y);
} else
print("OK" + (empty(msg) ? "" : " " + msg) + ": " + /*sfu*/(x));
return y;
}
static A liftLast(List l) {
if (empty(l)) return null;
int i = l(l)-1;
A a = l.get(i);
l.remove(i);
return a;
}
static List liftLast(int n, List l) {
int i = l(l)-n;
List part = cloneSubList(l, i);
removeSubList(l, i);
return part;
}
static Class actualMC() {
return or((Class) realMC(), mc());
}
static boolean isAnonymousClassName(String s) {
for (int i = 0; i < l(s); i++)
if (s.charAt(i) == '$' && Character.isDigit(s.charAt(i+1)))
return true;
return false;
}
static boolean isBoxedType(Class type) {
return type == Boolean.class
|| type == Integer.class
|| type == Long.class
|| type == Float.class
|| type == Short.class
|| type == Character.class
|| type == Byte.class
|| type == Double.class;
}
static boolean isArrayType(Class type) {
return type != null && type.isArray();
}
static boolean hasThisDollarFields(Object o) {
Matches m = new Matches();
for (var f : allFieldObjects_dontMakeAccessible(o))
if (startsWith(f.getName(), "this$", m) && isInteger(m.rest()))
return true;
return false;
}
static boolean hasSingleArgumentConstructor(Class c) {
if (c != null)
for (Constructor m : c.getDeclaredConstructors())
if (l(m.getParameterTypes()) == 1)
return true;
return false;
}
static Constructor getDefaultConstructor(Class c) {
if (c != null)
for (Constructor m : c.getDeclaredConstructors())
if (empty(m.getParameterTypes()))
return m;
return null;
}
static boolean addToCollection(Collection c, A a) {
return c != null && c.add(a);
}
static boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x)) return true; return false;
}
static boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m)) return true; return false;
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static int strL(String s) {
return s == null ? 0 : s.length();
}
static int listL(Collection l) {
return l == null ? 0 : l.size();
}
static byte[] boolArrayToBytes(boolean[] a) {
byte[] b = new byte[(l(a)+7)/8];
for (int i = 0; i < l(a); i++)
if (a[i])
b[i/8] |= 1 << (i & 7);
return b;
}
static int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
static List> mapPairB(final Object f, Iterable> l) {
return map(l, new F1, Pair>() { public Pair get(Pair p) { try {
return p == null ? null : pair(p.a, (C) callF(f, p.b));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "p == null ? null : pair(p.a, (C) callF(f, p.b))"; }});
}
static List> mapPairB(final F1 f, Iterable> l) {
return mapPairB((Object) f, l);
}
static List> mapPairB(final IF1 f, Iterable> l) {
return mapPairB((Object) f, l);
}
static List> mapPairB(Iterable> l, IF1 f) {
return mapPairB((Object) f, l);
}
static Pair mapPairB(IF1 f, Pair p) {
return pairMapB(f, p);
}
static Pair mapPairB(Pair p, IF1 f) {
return pairMapB(f, p);
}
static Map mapToKey(Iterable l, IF1 f) {
return mapToKeys(l, f);
}
static Map mapToKey(IF1 f, Iterable l) {
return mapToKeys(f, l);
}
static Map> getFieldOrder_cache = weakMap();
static List getFieldOrder(Object o) {
return getFieldOrder(_getClass(o));
}
static List getFieldOrder(Class c) {
if (c == null) return null;
return getOrCreate(getFieldOrder_cache, c,
() -> splitAtSpace(toStringOpt(getOpt(c, "_fieldOrder"))));
}
static void addAll(Collection c, Iterable b) {
if (c != null && b != null) for (A a : b) c.add(a);
}
static boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static boolean addAll(Collection c, B... b) {
return c != null && b != null && c.addAll(Arrays.asList(b));
}
static Map addAll(Map a, Map extends A,? extends B> b) {
if (a != null && b != null) a.putAll(b);
return a;
}
static boolean isDigit(char c) {
return Character.isDigit(c);
}
static List immutableEmptyList() {
return Collections.emptyList();
}
static int[] emptyIntArray_a = new int[0];
static int[] emptyIntArray() { return emptyIntArray_a; }
static char[] emptyCharArray = new char[0];
static char[] emptyCharArray() { return emptyCharArray; }
static double[] emptyDoubleArray = new double[0];
static double[] emptyDoubleArray() { return emptyDoubleArray; }
static short[] emptyShortArray = new short[0];
static short[] emptyShortArray() { return emptyShortArray; }
static Map immutableEmptyMap() {
return Collections.emptyMap();
}
static Object[] emptyObjectArray_a = new Object[0];
static Object[] emptyObjectArray() { return emptyObjectArray_a; }
static Symbol emptySymbol_value;
static Symbol emptySymbol() {
if (emptySymbol_value == null) emptySymbol_value = symbol("");
return emptySymbol_value;
}
static File programDir_mine; // set this to relocate program's data
static File programDir() {
return programDir(getProgramID());
}
static File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
if (me) {
String c = caseID();
if (nempty(c)) dir = newFile(dir, c);
}
return dir;
}
static File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static Class getMainClass() {
return mc();
}
static Class getMainClass(Object o) { try {
if (o == null) return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30")) return (Class) o;
ClassLoader cl = (o instanceof Class ? (Class) o : o.getClass()).getClassLoader();
if (cl == null) return null;
String name = mainClassNameForClassLoader(cl);
return loadClassFromClassLoader_orNull(cl, name);
} catch (Exception __e) { throw rethrow(__e); } }
static String actualUserHome_value;
static String actualUserHome() {
if (actualUserHome_value == null) {
if (isAndroid())
actualUserHome_value = "/storage/emulated/0/";
else
actualUserHome_value = System.getProperty("user.home");
}
return actualUserHome_value;
}
static File actualUserHome(String sub) {
return newFile(new File(actualUserHome()), sub);
}
static File userDir() {
return new File(userHome());
}
static File userDir(String path) {
return new File(userHome(), path);
}
static byte[] toUtf8(String s) { try {
return s.getBytes(utf8charset());
} catch (Exception __e) { throw rethrow(__e); } }
static boolean md5OfFile_verbose = false;
static String md5OfFile(String path) {
return md5OfFile(newFile(path));
}
static String md5OfFile(File f) { try {
if (!f.exists()) return "-";
if (md5OfFile_verbose)
print("Getting MD5 of " + f);
MessageDigest md5 = MessageDigest.getInstance("MD5");
FileInputStream in = new FileInputStream(f); try {
byte buf[] = new byte[65536];
int l;
while (true) {
l = in.read(buf);
if (l <= 0) break;
md5.update(buf, 0, l);
}
return bytesToHex(md5.digest());
} finally { _close(in); }} catch (Exception __e) { throw rethrow(__e); } }
static List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
static List newSubListOrSame(List l, int startIndex, int endIndex) {
if (l == null) return null;
int n = l(l);
startIndex = max(0, startIndex);
endIndex = min(n, endIndex);
if (startIndex >= endIndex) return ll();
if (startIndex == 0 && endIndex == n) return l;
return cloneList(l.subList(startIndex, endIndex));
}
static int[] takeFirstOfIntArray(int[] b, int n) {
return subIntArray(b, 0, n);
}
static int[] takeFirstOfIntArray(int n, int[] b) {
return takeFirstOfIntArray(b, n);
}
static short[] takeFirstOfShortArray(short[] b, int n) {
return subShortArray(b, 0, n);
}
static short[] takeFirstOfShortArray(int n, short[] b) {
return takeFirstOfShortArray(b, n);
}
static byte[] takeFirstOfByteArray(byte[] b, int n) {
return subByteArray(b, 0, n);
}
static byte[] takeFirstOfByteArray(int n, byte[] b) {
return takeFirstOfByteArray(b, n);
}
static double[] takeFirstOfDoubleArray(double[] b, int n) {
return subDoubleArray(b, 0, n);
}
static double[] takeFirstOfDoubleArray(int n, double[] b) {
return takeFirstOfDoubleArray(b, n);
}
static String dropLeadingDots(String s) {
int i = 0;
while (charAt(s, i) == '.') ++i;
return dropFirst(s, i);
}
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static Map vm_generalWeakSubMap(Object name) {
synchronized(vm_generalMap()) {
Map map = (Map) (vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = newWeakMap());
return map;
}
}
static Map emptyMap() {
return new HashMap();
}
static void copyStream(InputStream in, OutputStream out) { try {
byte[] buf = new byte[65536];
while (true) {
int n = in.read(buf);
if (n <= 0) return;
out.write(buf, 0, n);
}
} catch (Exception __e) { throw rethrow(__e); } }
//static final Map> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init);
static class getOpt_Map extends WeakHashMap {
getOpt_Map() {
if (getOpt_special == null) getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
//print("getOpt clear");
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
//static final Map> getOpt_cache = _registerWeakMap(synchroMap(new getOpt_Map));
static HashMap getOpt_special; // just a marker
/*static void getOpt_special_init(Map map) {
map.put(Class.class, getOpt_special);
map.put(S.class, getOpt_special);
}*/
static Map getOpt_getFieldMap(Object o) {
Class c = _getClass(o);
HashMap map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
return map;
}
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Map map = getOpt_getFieldMap(o);
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
/*if (o instanceof S)
ret getOpt(getBot((S) o), field);*/
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
if (o instanceof DynamicObject)
return syncMapGet2(((DynamicObject) o).fieldValues, field);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
if (!reflection_classesNotToScan().contains(c.getName())) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
makeAccessible(f);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
}
if (getOpt_cache != null) getOpt_cache.put(c, map);
return map;
}
static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static String hostNameFromURL(String url) { try {
return empty(url) ? null : new URL(url).getHost();
} catch (Exception __e) { throw rethrow(__e); } }
static boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la-lb, b, 0, lb);
}
static boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b)) return false;
if (m != null)
m.m = new String[] { substring(a, 0, l(a)-l(b)) };
return true;
}
static boolean containsNewLine(String s) {
return contains(s, '\n'); // screw \r, nobody needs it
}
static List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++)
if (eq(l.get(i), a))
l.set(i, b);
return l;
}
static List replace(A a, A b, List l) {
return replace(l, a, b);
}
// replace all occurrences of a in s with b
static String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
static String htmlencode2(String s) {
return htmlencode_noQuotes(s);
}
static boolean newButton_autoToolTip = true;
// action can be Runnable or a function name
static JButton newButton(final String text, final Object action) {
return swing(new F0() { public JButton get() { try {
String text2 = dropPrefix("[disabled] ", text);
JButton btn = basicJButton(text2);
if (l(text2) < l(text)) btn.setEnabled(false);
if (newButton_autoToolTip) {
btn.setToolTipText(btn.getText());
//onChangeAndNow(btn, r { btn.setToolTipText(btn.getText()) });
}
// submitButtonOnEnter(btn); // test this first
if (action != null)
btn.addActionListener(actionListener(action, btn));
return btn;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "S text2 = dropPrefix(\"[disabled] \", text);\r\n JButton btn = basicJButton(te..."; }});
}
static void pcallFAll(Collection l, Object... args) {
if (l != null) for (Object f : cloneList(l)) pcallF(f, args);
}
static void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static Runnable toRunnable(final Object o) {
if (o instanceof Runnable) return (Runnable) o;
if (o instanceof String) throw fail("callF_legacy");
return new Runnable() { public void run() { try { callF(o) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; }};
}
static List> _threadInheritInfo_retrievers = synchroList();
static void _threadInheritInfo(Object info) {
if (info == null) return;
pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
static int lastIndexOf(String a, String b) {
return a == null || b == null ? -1 : a.lastIndexOf(b);
}
static int lastIndexOf(String a, char b) {
return a == null ? -1 : a.lastIndexOf(b);
}
// starts searching from i-1
static int lastIndexOf(List l, int i, A a) {
if (l == null) return -1;
for (i = min(l(l), i)-1; i >= 0; i--)
if (eq(l.get(i), a))
return i;
return -1;
}
static int lastIndexOf(List l, A a) {
if (l == null) return -1;
for (int i = l(l)-1; i >= 0; i--)
if (eq(l.get(i), a))
return i;
return -1;
}
static List _registerWeakMap_preList;
static A _registerWeakMap(A map) {
if (javax() == null) {
// We're in class init
if (_registerWeakMap_preList == null) _registerWeakMap_preList = synchroList();
_registerWeakMap_preList.add(map);
return map;
}
try {
call(javax(), "_registerWeakMap", map);
} catch (Throwable e) {
printException(e);
print("Upgrade JavaX!!");
}
return map;
}
static void _onLoad_registerWeakMap() {
assertNotNull(javax());
if (_registerWeakMap_preList == null) return;
for (Object o : _registerWeakMap_preList)
_registerWeakMap(o);
_registerWeakMap_preList = null;
}
static x30_pkg.x30_util.BetterThreadLocal newPing_actionTL;
static x30_pkg.x30_util.BetterThreadLocal newPing_actionTL() {
if (newPing_actionTL == null)
newPing_actionTL = vm_generalMap_getOrCreate("newPing_actionTL",
() -> {
Runnable value = (Runnable) (callF_gen(vm_generalMap_get("newPing_valueForNewThread")));
var tl = new x30_pkg.x30_util.BetterThreadLocal();
tl.set(value);
return tl;
});
return newPing_actionTL;
}
static volatile boolean licensed_yes = true;
static boolean licensed() {
if (!licensed_yes) return false;
ping_okInCleanUp();
return true;
}
static void licensed_off() {
licensed_yes = false;
}
static Set synchronizedSet() {
return synchroHashSet();
}
static Set synchronizedSet(Set set) {
return Collections.synchronizedSet(set);
}
static Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
static double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o instanceof String)
return parseDouble((String) o);
if (o == null) return 0.0;
throw fail(o);
}
static A proxy(Class intrface, final Object target) {
if (target == null) return null;
if (isInstance(intrface, target)) return (A) target;
return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(),
new Class[] { intrface },
new proxy_InvocationHandler(target));
}
static A proxy(Object target, Class intrface) {
return proxy(intrface, target);
}
static String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
static boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static File imageSnippetCacheFile(String snippetID) {
File dir = imageSnippetsCacheDir();
if (!loadBufferedImage_useImageCache) return null;
return new File(dir, parseSnippetID(snippetID) + ".png");
}
static String snippetImageURL_noHttps(String snippetID) {
return snippetImageURL_noHttps(snippetID, "png");
}
static String snippetImageURL_noHttps(String snippetID, String contentType) {
return snippetImageURL(snippetID, contentType)
.replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/")
.replace("https://botcompany.de/", "http://botcompany.de/");
}
static ThreadLocal