l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
static List newSubList(List l, int startIndex, int endIndex) {
return cloneList(subList(l, startIndex, endIndex));
}
static List newSubList(List l, int startIndex) {
return cloneList(subList(l, startIndex));
}
static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static List subList(List l, int startIndex, int endIndex) {
if (l == null) return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex >= endIndex) return ll();
if (startIndex == 0 && endIndex == n) return l;
return l.subList(startIndex, endIndex);
}
static boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static boolean containsNewLines(String s) {
return containsNewLine(s);
}
static String jlabel_textAsHTML_center(String text) {
return ""
+ replace(htmlencode(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 Object call_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.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
{ if (!(isStaticMethod(m))) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} 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);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) { throw rethrow(__e); } }
static Rect pointsRect(int x1, int y1, int x2, int y2) {
return new Rect(x1, y1, x2-x1, y2-y1);
}
static boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
static BufferedImage imageIO_readURL(String url) { try {
if (startsWith(url, "https:")) // Java is still buggy there :(
disableCertificateValidation();
return ImageIO.read(new URL(url));
} catch (Exception __e) { throw rethrow(__e); } }
static boolean isAbsolutePath(String s) {
return s != null && new File(s).isAbsolute();
}
static boolean isAbsolutePath(File f) {
return f != null && f.isAbsolute();
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
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 IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
static File imageSnippetsCacheDir() {
return javaxCachesDir("Image-Snippets");
}
static String snippetImageURL_http(String snippetID) {
return snippetImageURL_http(snippetID, "png");
}
static String snippetImageURL_http(String snippetID, String contentType) {
return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080");
}
static A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () { public A get() { try { return nuObject(c, args); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret nuObject(c, args);"; }});
}
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt(String field, Object o) {
return getOpt_cached(o, field);
}
static Object getOpt_raw(Object o, String field) { try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
// access of static fields is not yet optimized
static Object getOpt(Class c, String field) { try {
if (c == null) return null;
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
makeAccessible(f);
return f.get(null);
} catch (Exception __e) { throw rethrow(__e); } }
static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static A or(A a, A b) {
return a != null ? a : b;
}
static int indexOf(List l, A a, int startIndex) {
if (l == null) return -1;
int n = l(l);
for (int i = startIndex; i < n; i++)
if (eq(l.get(i), a))
return i;
return -1;
}
static int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
static int indexOf(List l, A a) {
if (l == null) return -1;
return l.indexOf(a);
}
static int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(A[] x, A a) {
int n = l(x);
for (int i = 0; i < n; i++)
if (eq(x[i], a))
return i;
return -1;
}
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 int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static int cmp(Object a, Object b) {
if (a == null) return b == null ? 0 : -1;
if (b == null) return 1;
return ((Comparable) a).compareTo(b);
}
static IterableIterator iteratorFromFunction_withEndMarker_f0(final F0 f) {
class IFF2 extends IterableIterator {
A a;
boolean have, done;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done) throw fail();
A _a = a;
a = null;
have = false;
return _a;
}
void getNext() {
if (done || have) return;
Object o = f.get();
if (o == iteratorFromFunction_endMarker)
{ done = true; return; }
a = (A) o;
have = true;
}
};
return new IFF2();
}
static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null) return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}
static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
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 Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
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 boolean isImageFile(File f) {
return isImageFileName(fileName(f));
}
static BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() { public void run() { try { _inheritThreadInfo(info); callF(r);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_inheritThreadInfo(info); callF(r);"; }};
}
static Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static Class javax() {
return getJavaX();
}
static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Object swingCall(final Object o, final String method, final Object... args) {
return swing(new F0() { public Object get() { try { return call(o, method, args); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret call(o, method, args);"; }});
}
static String className(Object o) {
return getClassName(o);
}
static List _registerDangerousWeakMap_preList;
static A _registerDangerousWeakMap(A map) {
return _registerDangerousWeakMap(map, null);
}
static A _registerDangerousWeakMap(A map, Object init) {
callF(init, map);
if (init instanceof String) {
final String f = (String) init;
init = new VF1() { public void get(Map map) { try { callMC(f, map) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callMC(f, map)"; }};
}
if (javax() == null) {
// We're in class init
if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList();
_registerDangerousWeakMap_preList.add(pair(map, init));
return map;
}
call(javax(), "_registerDangerousWeakMap", map, init);
return map;
}
static void _onLoad_registerDangerousWeakMap() {
assertNotNull(javax());
if (_registerDangerousWeakMap_preList == null) return;
for (Pair p : _registerDangerousWeakMap_preList)
_registerDangerousWeakMap(p.a, p.b);
_registerDangerousWeakMap_preList = null;
}
static Class mc() {
return main.class;
}
static Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static String joinWithSpace(Collection c) {
return join(" ", c);
}
static String joinWithSpace(String... c) {
return join(" ", c);
}
static List classNames(Collection l) {
return getClassNames(l);
}
static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class) return arg instanceof Boolean;
if (type == int.class) return arg instanceof Integer;
if (type == long.class) return arg instanceof Long;
if (type == float.class) return arg instanceof Float;
if (type == short.class) return arg instanceof Short;
if (type == char.class) return arg instanceof Character;
if (type == byte.class) return arg instanceof Byte;
if (type == double.class) return arg instanceof Double;
return type.isInstance(arg);
}
static void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1) return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static String unnull(String s) {
return s == null ? "" : s;
}
static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
//ifclass Symbol
static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static String substring(String s, int x) {
return substring(s, x, strL(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
if (x >= s.length()) return "";
if (y < x) y = x;
if (y > s.length()) y = s.length();
return s.substring(x, y);
}
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 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);
}
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 htmlencode(Object o) {
return htmlencode(str(o));
}
static String htmlencode(String s) {
if (s == null) return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
int cp = s.codePointAt(i);
out.append("");
out.append(intToHex_flexLength(cp));
out.append(';');
i += Character.charCount(cp)-1;
} else
out.append(c);
}
return out.toString();
}
static final Map callOpt_cache = newDangerousWeakHashMap();
static Object callOpt_cached(Object o, String methodName, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
// TODO: (super-rare) case where method exists static and non-static
// with different args
Method me = cache.findMethod(methodName, args);
if (me == null || (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(methodName, args);
if (me == null) return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) { throw rethrow(__e); } }
static _MethodCache callOpt_getCache(Class c) {
synchronized(callOpt_cache) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
}
static Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length-1, nArgs = args.length;
if (nArgs < n) return null;
for (int i = 0; i < n; i++)
if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++)
if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n+1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs-n);
arraycopy(args, n, varArgs, 0, nArgs-n);
newArgs[n] = varArgs;
return newArgs;
}
static boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x)) return true; return false;
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a)) return false;
for (int i = 0; i < listL(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static volatile boolean disableCertificateValidation_attempted = false;
static void disableCertificateValidation() { try {
if (disableCertificateValidation_attempted) return;
disableCertificateValidation_attempted = true;
print("Disabling certificate validation for whole VM");
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}};
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) { return true; }
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Throwable __e) { _handleException(__e); }
} catch (Exception __e) { throw rethrow(__e); } }
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 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 InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) {
return call(target, method.getName(), unnull(args));
}
});
}
static A proxy(Object target, Class intrface) {
return proxy(intrface, target);
}
static File javaxCachesDir_dir; // can be set to work on different base dir
static File javaxCachesDir() {
return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
static File javaxCachesDir(String sub) {
return newFile(javaxCachesDir(), sub);
}
static String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix)) return s;
return replacement + substring(s, l(prefix));
}
static String snippetImageURL(long snippetID) {
return snippetImageURL(fsI(snippetID));
}
static String snippetImageURL(String snippetID) {
return snippetImageURL(snippetID, "png");
}
static String snippetImageURL(String snippetID, String contentType) {
if (isURL(snippetID)) return snippetID;
long id = parseSnippetID(snippetID);
String url;
if (isImageServerSnippet(id))
url = imageServerLink(id);
else
//url = "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=image/" + contentType;
url = "https://botcompany.de/img/" + id;
return url;
}
static Object nuObject(String className, Object... args) { try {
return nuObject(classForName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }
// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
ret nuObject(_getClass(realm, className), args);
}*/
static A nuObject(Class c, Object... args) { try {
if (args.length == 0) return nuObjectWithoutArguments(c); // cached!
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found"
+ (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
//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 Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
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 mapGet2(((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 A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null) return null;
A old = tl.get();
tl.set(value);
return old;
}
static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static A printException(A e) {
printStackTrace(e);
return e;
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static boolean isImageFileName(String s) {
return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif");
}
static String fileName(File f) {
return f == null ? null : f.getName();
}
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 Map vm_generalMap_map;
static Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static Class __javax;
static Class getJavaX() { try {
return __javax;
} catch (Exception __e) { throw rethrow(__e); } }
static HashMap> callMC_cache = new HashMap();
static String callMC_key;
static Method callMC_value;
// varargs assignment fixer for a single string array argument
static Object callMC(String method, String[] arg) {
return callMC(method, new Object[] {arg});
}
static Object callMC(String method, Object... args) { try {
Method me;
if (callMC_cache == null) callMC_cache = new HashMap(); // initializer time workaround
synchronized(callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null) try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
List m;
synchronized(callMC_cache) {
m = callMC_cache.get(method);
}
if (m == null) {
if (callMC_cache.isEmpty()) {
callMC_makeCache();
m = callMC_cache.get(method);
}
if (m == null) throw fail("Method named " + method + " not found in main");
}
int n = m.size();
if (n == 1) {
me = m.get(0);
synchronized(callMC_cache) {
callMC_key = method;
callMC_value = me;
}
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return invokeMethod(me, null, args);
}
throw fail("No method called " + method + " with arguments (" + joinWithComma(getClasses(args)) + ") found in main");
} catch (Exception __e) { throw rethrow(__e); } }
static void callMC_makeCache() {
synchronized(callMC_cache) {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods())
if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
makeAccessible(m);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
static Pair pair(A a, B b) {
return new Pair(a, b);
}
static Pair pair(A a) {
return new Pair(a, a);
}
static List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null) for (Object o : l)
out.add(o == null ? null : getClassName(o));
return out;
}
static Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null
: l(args) == 1 ? args[0]
: args;
}
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 Set vm_busListeners_live_cache;
static Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache; }
static Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static Map vm_busListenersByMessage_live_cache;
static Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache; }
static Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static Map emptyMap() {
return new HashMap();
}
static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static int strL(String s) {
return s == null ? 0 : s.length();
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
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 String intToHex_flexLength(int i) {
return Integer.toHexString(i);
}
static boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
static void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, min(a.length, b.length));
}
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
static A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
static A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
static boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static int listL(Collection l) {
return l == null ? 0 : l.size();
}
static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));
static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3); // not using pcall here - it could lead to endless loops
}
}
static long parseLong(String s) {
if (empty(s)) return 0;
return Long.parseLong(dropSuffix("L", s));
}
static long parseLong(Object s) {
return Long.parseLong((String) s);
}
static boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
static String _userHome;
static String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
static File userHome(String path) {
return new File(userDir(), path);
}
static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static File newFile(String name) {
return name == null ? null : new File(name);
}
static File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static String fsI(String id) {
return formatSnippetID(id);
}
static String fsI(long id) {
return formatSnippetID(id);
}
static boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static String imageServerLink(String md5OrID) {
if (possibleMD5(md5OrID))
return "https://botcompany.de/images/md5/" + md5OrID;
return imageServerLink(parseSnippetID(md5OrID));
}
static String imageServerLink(long id) {
return "https://botcompany.de/images/" + id;
}
static Map classForName_cache = synchroHashMap();
static Class classForName(String name) { try {
if (classForName_cache == null) return Class.forName(name); // in class init
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = Class.forName(name));
return c;
} catch (Exception __e) { throw rethrow(__e); } }
static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static Object nuObjectWithoutArguments(String className) { try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) { throw rethrow(__e); } }
static A nuObjectWithoutArguments(Class c) { try {
if (nuObjectWithoutArguments_cache == null)
// in class init
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors())
if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
static List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static void clear(Collection c) {
if (c != null) c.clear();
}
static void clear(Map map) {
if (map != null) map.clear();
}
static void put(Map map, A a, B b) {
if (map != null) map.put(a, b);
}
static void put(List l, int i, A a) {
if (l != null && i >= 0 && i < l(l)) l.set(i, a);
}
static B mapGet2(Map map, A a) {
return map == null ? null : map.get(a);
}
static B mapGet2(A a, Map map) {
return map == null ? null : map.get(a);
}
static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static Set reflection_classesNotToScan_value = litset(
"jdk.internal.loader.URLClassPath"
);
static Set reflection_classesNotToScan() {
return reflection_classesNotToScan_value;
}
static Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static A printStackTrace(A e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
return e;
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x)) return true; return false;
}
static String fileExtension(File f) {
if (f == null) return null;
return fileExtension(f.getName());
}
static String fileExtension(String s) {
return substring(s, smartLastIndexOf(s, '.'));
}
static Runnable toRunnable(final Object o) {
if (o instanceof Runnable) return (Runnable) o;
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 void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static A pcallF(F0 f) { try {
return f == null ? null : f.get();
} catch (Throwable __e) { return null; } }
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static void pcallF(VF1 f, A a) {
try {
if (f != null) f.get(a);
} catch (Throwable __e) { _handleException(__e); }
}
static Set vm_generalIdentityHashSet(Object name) {
synchronized(get(javax(), "generalMap")) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = syncIdentityHashSet());
return set;
}
}
static Map vm_generalHashMap(Object name) {
synchronized(get(javax(), "generalMap")) {
Map m = (Map) (vm_generalMap_get(name));
if (m == null)
vm_generalMap_put(name, m = syncHashMap());
return m;
}
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x) x = d;
return x;
}
static A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
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 String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static boolean possibleMD5(String s) { return isMD5(s); }
static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static Class _getClass(Object o) {
return o == null ? null
: o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static HashSet litset(A... items) {
return lithashset(items);
}
static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
hideCredentials(str(innerException2(e)))) + "\n");
}
static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
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(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 int smartLastIndexOf(String s, char c) {
if (s == null) return 0;
int i = s.lastIndexOf(c);
return i >= 0 ? i : l(s);
}
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
return null;
}
static Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static Map syncHashMap() {
return synchroHashMap();
}
static Throwable getInnerException(Throwable e) {
if (e == null) return null;
while (e.getCause() != null)
e = e.getCause();
return e;
}
static Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
static boolean isMD5(String s) {
return l(s) == 32 && isLowerHexString(s);
}
static Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static Class getClass(Object realm, String name) { try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) { throw rethrow(__e); } }
static String classNameToVM(String name) {
return name.replace(".", "$");
}
static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
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)=[^&\\s\"]*", "$1$2=");
}
static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null) return e;
while (e.getClass() == RuntimeException.class
&& e.getCause() != null && eq(e.getMessage(), str(e.getCause())))
e = e.getCause();
return e;
}
static Throwable innerException2(Throwable e) {
if (e == null) return null;
while (empty(e.getMessage()) && e.getCause() != null)
e = e.getCause();
return e;
}
// 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 asString(Object o) {
return o == null ? null : o.toString();
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static B mapPutOrRemove(Map map, A key, B value) {
if (map != null && key != null)
if (value != null) return map.put(key, value);
else return map.remove(key);
return null;
}
static Set synchronizedSet() {
return synchroHashSet();
}
static Set synchronizedSet(Set set) {
return Collections.synchronizedSet(set);
}
static Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static boolean isLowerHexString(String s) {
for (int i = 0; i < l(s); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
// ok
} else
return false;
}
return true;
}
static boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static String hostNameFromURL(String url) { try {
return new URL(url).getHost();
} catch (Exception __e) { throw rethrow(__e); } }
static Set synchroHashSet() {
return Collections.synchronizedSet(new HashSet ());
}
static boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
static String theAGIBlueDomain() {
return "agi.blue";
}
// immutable, has strong refs
final static class _MethodCache {
final Class c;
final HashMap> cache = new HashMap();
_MethodCache(Class c) {
this.c = c; _init(); }
void _init() {
Class _c = c;
while (_c != null) {
for (Method m : _c.getDeclaredMethods())
if (!reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
_c = _c.getSuperclass();
}
// add default methods - this might lead to a duplication
// because the overridden method is also added, but it's not
// a problem except for minimal performance loss.
for (Class intf : allInterfacesImplementedBy(c))
for (Method m : intf.getDeclaredMethods())
if (m.isDefault() && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
}
// Returns only matching methods
Method findMethod(String method, Object[] args) { try {
List m = cache.get(method);
if (m == null) return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) { throw rethrow(__e); } }
Method findStaticMethod(String method, Object[] args) { try {
List m = cache.get(method);
if (m == null) return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (isStaticMethod(me) && call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) { throw rethrow(__e); } }
}static abstract class VF1 implements IVF1 {
public abstract void get(A a);
}static class Rect {
int x, y, w, h;
Rect() {}
Rect(Rectangle r) {
x = r.x;
y = r.y;
w = r.width;
h = r.height;
}
Rect(int x, int y, int w, int h) {
this.h = h;
this.w = w;
this.y = y;
this.x = x;}
Rect(Pt p, int w, int h) {
this.h = h;
this.w = w; x = p.x; y = p.y; }
Rect(Rect r) { x = r.x; y = r.y; w = r.w; h = r.h; }
Rectangle getRectangle() {
return new Rectangle(x, y, w, h);
}
public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
public String toString() {
return x + "," + y + " / " + w + "," + h;
}
int x2() { return x + w; }
int y2() { return y + h; }
boolean contains(Pt p) {
return contains(p.x, p.y);
}
boolean contains(int _x, int _y) {
return _x >= x && _y >= y && _x < x+w && _y < y+h;
}
boolean empty() { return w <= 0 || h <= 0; }
}static class Pt {
int x, y;
Pt() {}
Pt(Point p) {
x = p.x;
y = p.y;
}
Pt(int x, int y) {
this.y = y;
this.x = x;}
Point getPoint() {
return new Point(x, y);
}
public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
public String toString() {
return x + ", " + y;
}
}static class Var implements IVar {
Var() {}
Var(A v) {
this.v = v;}
A v; // you can access this directly if you use one thread
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() { return v; }
public synchronized boolean has() { return v != null; }
public synchronized void clear() { v = null; }
public String toString() { return str(get()); }
}static abstract class F0 {
abstract A get();
}static abstract class F1 {
abstract B get(A a);
}// you still need to implement hasNext() and next()
static abstract class IterableIterator implements Iterator , Iterable {
public Iterator iterator() {
return this;
}
public void remove() {
unsupportedOperation();
}
} // thumbnailator
static class ImageSurface extends Surface {
BufferedImage image;
double zoomX = 1, zoomY = 1, zoomFactor = 1.5;
private Rectangle selection;
List tools = new ArrayList();
Object overlay; // voidfunc(Graphics2D)
Runnable onSelectionChange;
static boolean verbose = false;
boolean noMinimumSize = true;
String titleForUpload;
Object onZoom;
boolean specialPurposed = false; // true = don't show image changing commands in popup menu
boolean zoomable = true;
boolean noAlpha = false; // set to true to speed up drawing if you don't use alpha
Object interpolationMode = RenderingHints.VALUE_INTERPOLATION_BILINEAR;
Object onNewImage;
BufferedImage imageToDraw; // if you want to draw a different image
public ImageSurface() {
this(dummyImage());
}
static BufferedImage dummyImage() {
return new RGBImage(1, 1, new int[] { 0xFFFFFF }).getBufferedImage();
}
ImageSurface(MakesBufferedImage image) {
this(image != null ? image.getBufferedImage() : dummyImage());
}
ImageSurface(BufferedImage image) {
setImage(image);
clearSurface = false;
componentPopupMenu2(this, ImageSurface_popupMenuMaker());
new ImageSurfaceSelector(this);
jHandleFileDrop(this, new VF1() { public void get(File f) { try { setImage(loadBufferedImage(f)) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "setImage(loadBufferedImage(f))"; }});
}
public ImageSurface(RGBImage image, double zoom) {
this(image);
setZoom(zoom);
}
// point is already in image coordinates
protected void fillPopupMenu(JPopupMenu menu, final Point point) {
if (zoomable) {
JMenuItem miZoomReset = new JMenuItem("Zoom 100%");
miZoomReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setZoom(1.0);
centerPoint(point);
}
});
menu.add(miZoomReset);
JMenuItem miZoomIn = new JMenuItem("Zoom in");
miZoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
zoomIn(zoomFactor);
centerPoint(point);
}
});
menu.add(miZoomIn);
JMenuItem miZoomOut = new JMenuItem("Zoom out");
miZoomOut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
zoomOut(zoomFactor);
centerPoint(point);
}
});
menu.add(miZoomOut);
JMenuItem miZoomToWindow = new JMenuItem("Zoom to window");
miZoomToWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
zoomToDisplaySize();
}
});
menu.add(miZoomToWindow);
addMenuItem(menu, "Show full screen", new Runnable() { public void run() { try { showFullScreen() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showFullScreen()"; }});
addMenuItem(menu, "Point: " + point.x + "," + point.y + " (image: " + image.getWidth() + "*" + image.getHeight() + ")", null);
menu.addSeparator();
}
addMenuItem(menu, "Load image...", new Runnable() { public void run() { try { selectFile("Load image",
new VF1() { public void get(File f) { try { setImage(loadImage2(f)) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "setImage(loadImage2(f))"; }}) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "selectFile(\"Load image\",\r\n new VF1() { public void get(File f) cte..."; }});
addMenuItem(menu, "Save image...", new Runnable() { public void run() { try { saveImage() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "saveImage()"; }});
addMenuItem(menu, "Upload image...", new Runnable() { public void run() { try { uploadTheImage() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "uploadTheImage()"; }});
addMenuItem(menu, "Copy image to clipboard", new Runnable() { public void run() { try { copyImageToClipboard(getImage()) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyImageToClipboard(getImage())"; }});
if (!specialPurposed) {
addMenuItem(menu, "Paste image from clipboard", new Runnable() { public void run() { try { loadFromClipboard() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "loadFromClipboard()"; }});
addMenuItem(menu, "Load image snippet...", new Runnable() { public void run() { try {
selectImageSnippet(new VF1() { public void get(String imageID) { try {
setImage(loadImage2(imageID))
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "setImage(loadImage2(imageID))"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "selectImageSnippet(new VF1() { public void get(String imageID) ctex {..."; }});
}
if (selection != null)
addMenuItem(menu, "Crop", new Runnable() { public void run() { try { crop() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "crop()"; }});
if (!specialPurposed)
addMenuItem(menu, "No image", new Runnable() { public void run() { try { noImage() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "noImage()"; }});
}
void noImage() { setImage((BufferedImage) null); }
void crop() {
if (selection == null) return;
BufferedImage img = cloneClipBufferedImage(getImage(), selection);
selection = null;
setImage(img);
}
void loadFromClipboard() {
BufferedImage img = getImageFromClipboard();
if (img != null)
setImage(img);
}
void saveImage() {
RGBImage image = new RGBImage(getImage(), null);
JFileChooser fileChooser = new JFileChooser(getProgramDir());
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
image.save(fileChooser.getSelectedFile());
} catch (IOException e) {
popup(e);
}
}
}
public void render(int w, int h, Graphics2D g) {
if (verbose) _print("render");
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolationMode);
g.setColor(Color.white);
BufferedImage image = or(imageToDraw, this.image);
if (image == null)
g.fillRect(0, 0, w, h);
else {
int iw = getZoomedWidth(), ih = getZoomedHeight();
boolean alpha = !noAlpha && hasTransparency(image);
if (alpha) g.fillRect(0, 0, w, h);
if (eq(interpolationMode, "thumbnailator"))
g.drawImage(Thumbnailator.createThumbnail(image, iw, ih), 0, 0, null);
else if (interpolationMode == RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR || zoomX >= 1 || zoomY >= 1)
g.drawImage(image, 0, 0, iw, ih, null);
else
g.drawImage(resizeImage(image, iw, ih), 0, 0, null); // smoother
if (!alpha) {
g.fillRect(iw, 0, w-iw, h);
g.fillRect(0, ih, iw, h-ih);
}
}
if (overlay != null) {
if (verbose) _print("render overlay");
pcallF(overlay, g);
}
if (selection != null) {
if (verbose) _print("render selection");
// drawRect is inclusive, selection is exclusive, so... whatever, tests show it's cool.
drawSelectionRect(g, selection, Color.green, Color.white);
}
}
public void drawSelectionRect(Graphics2D g, Rectangle selection, Color green, Color white) {
drawSelectionRect(g, selection, green, white, zoomX, zoomY);
}
public void drawSelectionRect(Graphics2D g, Rectangle selection, Color green, Color white, double zoomX, double zoomY) {
g.setColor(green);
int top = (int) (selection.y * zoomY);
int bottom = (int) ((selection.y+selection.height) * zoomY);
int left = (int) (selection.x * zoomX);
int right = (int) ((selection.x+selection.width) * zoomX);
g.drawRect(left-1, top-1, right-left+1, bottom-top+1);
g.setColor(white);
g.drawRect(left - 2, top - 2, right - left + 3, bottom - top + 3);
}
public ImageSurface setZoom(double zoom) {
setZoom(zoom, zoom);
return this;
}
public void setZoom(double zoomX, double zoomY) {
if (this.zoomX == zoomX && this.zoomY == zoomY) return;
if (verbose) _print("Setting zoom");
this.zoomX = zoomX;
this.zoomY = zoomY;
revalidate();
repaint();
centerPoint(new Point(getImage().getWidth()/2, getImage().getHeight()/2));
pcallF(onZoom);
}
public Dimension getMinimumSize() {
if (noMinimumSize) return new Dimension(1, 1);
int w = getZoomedWidth();
int h = getZoomedHeight();
Dimension min = super.getMinimumSize();
return new Dimension(Math.max(w, min.width), Math.max(h, min.height));
}
private int getZoomedHeight() {
return (int) (image.getHeight() * zoomY);
}
private int getZoomedWidth() {
return (int) (image.getWidth() * zoomX);
}
public void setImage(MakesBufferedImage image) {
setImage(image == null ? null : image.getBufferedImage());
}
public void setImage(final BufferedImage img) {
{ swing(new Runnable() { public void run() { try {
BufferedImage newImage = img != null ? img : dummyImage();
BufferedImage oldImage = image;
image = newImage;
if (!imagesHaveSameSize(oldImage, newImage)) {
if (verbose) _print("New image size");
revalidate(); // do we need this?
}
repaint();
pcallF(onNewImage);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "BufferedImage newImage = img != null ? img : dummyImage();\r\n BufferedIma..."; }}); }
}
void setImageAndZoomToDisplay(BufferedImage img) {
setImage(img);
zoomToDisplaySize();
}
public BufferedImage getImage() {
return image;
}
public double getZoomX() {
return zoomX;
}
public double getZoomY() {
return zoomY;
}
public Dimension getPreferredSize() {
return new Dimension(getZoomedWidth(), getZoomedHeight());
}
/** returns a scrollpane with the scroll-mode prevent-garbage-drawing fix applied */
public JScrollPane makeScrollPane() {
JScrollPane scrollPane = new JScrollPane(this);
scrollPane.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
return scrollPane;
}
public void zoomToWindow() { zoomToDisplaySize(); }
public void zoomToDisplaySize() { swing(new Runnable() { public void run() { try {
if (image == null) return;
Dimension display = getDisplaySize();
double xRatio = (display.width-5)/(double) image.getWidth();
double yRatio = (display.height-5)/(double) image.getHeight();
setZoom(min(xRatio, yRatio));
revalidate();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (image == null) return;\r\n Dimension display = getDisplaySize();\r\n do..."; }}); }
/** tricky magic to get parent scroll pane */
private Dimension getDisplaySize() {
Container c = getParent();
while (c != null) {
if (c instanceof JScrollPane)
return c.getSize();
c = c.getParent();
}
return getSize();
}
public void setSelection(Rect r) {
setSelection(toRectangle(r));
}
public void setSelection(Rectangle r) {
if (neq(selection, r)) {
selection = r;
pcallF(onSelectionChange);
repaint();
}
}
public Rectangle getSelection() {
return selection;
}
public RGBImage getRGBImage() {
return new RGBImage(getImage());
}
// p is in image coordinates
void centerPoint(Point p) {
JScrollPane sp = enclosingScrollPane(this);
if (sp == null) return;
p = new Point((int) (p.x*getZoomX()), (int) (p.y*getZoomY()));
final JViewport viewport = sp.getViewport();
Dimension viewSize = viewport.getExtentSize();
//_print("centerPoint " + p);
int x = max(0, p.x-viewSize.width/2);
int y = max(0, p.y-viewSize.height/2);
//_print("centerPoint " + p + " => " + x + "/" + y);
p = new Point(x,y);
//_print("centerPoint " + p);
final Point _p = p;
awtLater(new Runnable() { public void run() { try {
viewport.setViewPosition(_p);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "viewport.setViewPosition(_p);"; }});
}
Pt pointFromEvent(MouseEvent e) {
return pointFromComponentCoordinates(new Pt(e.getX(), e.getY()));
}
Pt pointFromComponentCoordinates(Pt p) {
return new Pt((int) (p.x/zoomX), (int) (p.y/zoomY));
}
Pt pointToComponentCoordinates(double x, double y) {
return new Pt((int) (x*zoomX), (int) (y*zoomY));
}
void uploadTheImage() {
call(hotwire(/*#1007313*/"#1016427"), "go", getImage(), titleForUpload);
}
void showFullScreen() {
showFullScreenImageSurface(getImage());
}
void zoomIn(double f) { setZoom(getZoomX()*f, getZoomY()*f); }
void zoomOut(double f) { setZoom(getZoomX()/f, getZoomY()/f); }
}
// static function allows garbage collection
static VF2 ImageSurface_popupMenuMaker() {
return new VF2() { public void get(ImageSurface is, JPopupMenu menu) { try {
Point p = is.pointFromEvent(componentPopupMenu_mouseEvent.get()).getPoint();
is.fillPopupMenu(menu, p);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Point p = is.pointFromEvent(componentPopupMenu_mouseEvent.get()).getPoint();\r..."; }};
}static interface MakesBufferedImage {
BufferedImage getBufferedImage();
int getWidth();
int getHeight();
}static final class BWImage implements MakesBufferedImage, IBWImage {
int width, height;
byte[] pixels;
// color returned when getPixel is called with a position outside the actual image
float borderColor = 0.0f;
// for unstructure()
BWImage() {}
// BLACK!
BWImage(int width, int height) {
this.height = height;
this.width = width;
pixels = new byte[width*height];
}
BWImage(int width, int height, float brightness) {
this.height = height;
this.width = width;
pixels = new byte[width*height];
fillArrayUnlessZero(pixels, _toByte(brightness));
}
BWImage(int width, int height, float[] pixels) {
this.pixels = new byte[pixels.length];
this.height = height;
this.width = width;
for (int i = 0; i < pixels.length; i++)
this.pixels[i] = _toByte(pixels[i]);
}
public BWImage(int width, int height, byte[] pixels) {
this.height = height;
this.width = width;
this.pixels = pixels;
}
public BWImage(BWImage image) {
width = image.getWidth();
height = image.getHeight();
byte[] pixels = this.pixels = new byte[width*height];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
pixels[y*width+x] = image.getByte(x, y);
}
// TODO: optimize!
BWImage(RGBImage image) {
width = image.getWidth();
height = image.getHeight();
byte[] pixels = this.pixels = new byte[height*width];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
RGB rgb = image.getRGB(x, y);
pixels[y*width+x] = BWImage._toByte(rgb.getBrightness());
}
}
/*public BWImage(BufferedImage image) {
this(new RGBImage(image));
}*/
BWImage(BufferedImage image) { try {
width = image.getWidth();
height = image.getHeight();
int[] pixels = new int[width*height];
byte[] bytePixels = this.pixels = new byte[width*height];
PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
if (!pixelGrabber.grabPixels())
throw fail("Could not grab pixels");
int n = width*height;
for (int i = 0; i < n; i++) {
//bytePixels[i] = pixelToByte(pixels[i]);
int packed = pixels[i];
/*float r = ((packed >> 16) & 0xFF)/255f;
float g = ((packed >> 8) & 0xFF)/255f;
float b = (packed & 0xFF)/255f;
bytePixels[i] = (byte) iround((r+g+b)/3.0f*255f);*/
int r = ((packed >> 16) & 0xFF);
int g = ((packed >> 8) & 0xFF);
int b = (packed & 0xFF);
bytePixels[i] = (byte) ((r+g+b+1)/3);
}
} catch (Exception __e) { throw rethrow(__e); } }
// TODO: does it exactly match the other method? (asRGB+getBrightness+_toByte)
static byte pixelToByte(int packed) {
/*int r = (packed >> 16) & 0xFF;
int g = (packed >> 8) & 0xFF;
int b = packed & 0xFF;
ret (byte) ((r+g+b)/3.0f);*/
float r = ((packed >> 16) & 0xFF)/255f;
float g = ((packed >> 8) & 0xFF)/255f;
float b = (packed & 0xFF)/255f;
return (byte) ((r+g+b)/3.0f*255f);
}
public byte getByte(int x, int y) {
return inRange(x, y) ? getByte_noRangeCheck(x, y) : _toByte(borderColor);
}
int getInt(int x, int y) {
return ubyteToInt(getByte(x, y));
}
public double averageBrightness() {
double sum = 0;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
sum += getPixel(x, y);
return (sum/(double) (height*width));
}
public float minimumBrightness() {
float min = 1;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
min = Math.min(min, getPixel(x, y));
return min;
}
public float maximumBrightness() {
float max = 0;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
max = Math.max(max, getPixel(x, y));
return max;
}
float getPixel(int x, int y) {
return inRange(x, y) ? _toFloat(getByte(x,y )) : borderColor;
}
public float getFloatPixel(int x, int y) { return getPixel(x, y); }
float getPixel(Pt p) { return getPixel(p.x, p.y); }
static byte _toByte(float pixel) {
return (byte) (pixel*255f);
}
static float _toFloat(byte pixel) {
return (((int) pixel) & 255)/255f;
}
private boolean inRange(int x, int y) {
return x >= 0 && x < width && y >= 0 && y < height;
}
public int getWidth() { return width; }
int w() { return width; }
public int getHeight() { return height; }
int h() { return height; }
public RGBImage toRGB() {
int[] rgbs = new int[width*height];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
int b = getByte(x, y) & 0xFF;
rgbs[y*width+x] = 0xFF000000 | b*0x010101;
}
return new RGBImage(width, height, rgbs);
}
public RGBImage toRGB_slow() {
RGB[] rgbs = new RGB[width*height];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
float p = getPixel(x, y);
rgbs[y*width+x] = new RGB(p, p, p);
}
return new RGBImage(width, height, rgbs);
}
public BWImage clip(int x, int y, int w, int h) {
return clip(new Rectangle(x, y, w, h));
}
private Rectangle fixClipRect(Rectangle r) {
return r.intersection(new Rectangle(0, 0, width, height));
}
BWImage clip(Rect r) {
return clip(r.getRectangle());
}
/** this should be multithread-safe */
public BWImage clip(Rectangle r) {
r = fixClipRect(r);
byte[] newPixels = new byte[r.height*r.width];
for (int y = 0; y < r.height; y++)
for (int x = 0; x < r.width; x++)
newPixels[y*r.width+x] = getByte(r.x+x, r.y+y);
return new BWImage(r.width, r.height, newPixels);
}
public void setPixel(int x, int y, float brightness) {
setByte(x, y, _toByte(fixPixel(brightness)));
}
// i = 0 to 255
public void setInt(int x, int y, int i) {
setByte(x, y, (byte) limitToUByte(i));
}
public void setByte(int x, int y, byte b) {
if (x >= 0 && x < width && y >= 0 && y < height)
pixels[y*width+x] = b;
}
byte getByte_noRangeCheck(int x, int y) {
return pixels[y*width+x];
}
public void setByte(int x, int y, int brightness) {
setByte(x, y, (byte) brightness);
}
private float fixPixel(float pixel) {
return Math.max(0, Math.min(1, pixel));
}
public float getBorderColor() {
return borderColor;
}
public void setBorderColor(float borderColor) {
this.borderColor = borderColor;
}
public boolean anyPixelBrighterThan(double threshold) {
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
if (getPixel(x, y) > threshold)
return true;
return false;
}
public BufferedImage getBufferedImage() {
//ret toRGB().getBufferedImage();
// TYPE_BYTE_GRAY is buggy - see #1015235
BufferedImage bufferedImage = new BufferedImage(width, height, /*BufferedImage.TYPE_BYTE_GRAY*/BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
int b = ((int) getByte(x, y) & 0xFF);
bufferedImage.setRGB(x, y, b*0x010101);
}
return bufferedImage;
}
byte[] getBytes() {
return pixels;
}
}static class BetterLabel extends JLabel {
boolean autoToolTip = true;
BetterLabel() {
// Listeners given out to componentPopupMenu must not directly
// reference the outer object (-> weak map problem).
final WeakReference < BetterLabel > me = new WeakReference(this);
componentPopupMenu(this, BetterLabel_menuItems(me));
}
BetterLabel(String text) {
this();
this.setText(text);
}
public void setText(String text) {
super.setText(text);
if (autoToolTip)
if (!swic(text, "")) // HTML labels make super-huge, confusing tool tips
setToolTipText(nullIfEmpty(text));
}
}
// moved outside of class for GC reasons (see above)
static VF1 BetterLabel_menuItems(final WeakReference me) {
return new VF1() { public void get(JPopupMenu menu) { try {
addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(me.get().getText());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(me.get().getText());"; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(me..."; }};
}final static class BWIntegralImage implements MakesBufferedImage, IBWIntegralImage {
int w, h;
int[] data; // 1 entry per pixel
BWIntegralImage() {}
BWIntegralImage(File f) { this(loadImage2(f)); }
BWIntegralImage(BufferedImage img) { this(new BWImage(img)); }
BWIntegralImage(MakesBufferedImage img) { this(toBufferedImage(img)); }
BWIntegralImage(BWImage img) {
w = img.w();
h = img.h();
data = new int[w*h];
int i = 0;
for (int y = 0; y < h; y++) {
int sum = 0;
for (int x = 0; x < w; x++) {
sum += img.getByte(x, y) & 0xFF;
data[i] = y > 0 ? sum + data[i-w] : sum;
i++;
}
}
}
// pixels outside of image are considered black
int get(int x, int y) {
return x < 0 || y < 0 || x >= w || y >= h ? 0
: data[min(y, h-1)*w+min(x, w-1)];
}
public double getPixelAverage(int x1, int y1, int x2, int y2) {
int area = (x2-x1)*(y2-y1);
return doubleRatio(bwIntegralImage_sumRect(this, x1, y1, x2, y2), area);
}
public int getWidth() { return w; }
public int getHeight() { return h; }
// unoptimized
public BufferedImage getBufferedImage() {
return scaleDownUsingIntegralImageBW(this, w).getBufferedImage();
}
}static interface IBWIntegralImage {
public int getWidth();
public int getHeight();
// 0.0 to 255.0
public double getPixelAverage(int x1, int y1, int x2, int y2);
}static interface IF0 {
A get();
}static interface IF2 {
C get(A a, B b);
}abstract static class SteppableAndBest implements Steppable {
Best best = new Best();
boolean verbose = false;
A get() { return best.get(); }
double score() { return best.score(); }
}static interface IF1 {
B get(A a);
}static interface IResourceLoader {
String loadSnippet(String snippetID);
String getTranspiled(String snippetID); // with libs
int getSnippetType(String snippetID);
String getSnippetTitle(String snippetID);
File loadLibrary(String snippetID);
File pathToJavaXJar();
File getSnippetJar(String snippetID, String transpiledSrc);
}static class PersistableThrowable {
String className;
String msg;
String stacktrace;
PersistableThrowable() {}
PersistableThrowable(Throwable e) {
if (e == null)
className = "Crazy Null Error";
else {
className = getClassName(e).replace('/', '.');
msg = e.getMessage();
stacktrace = getStackTrace_noRecord(e);
}
}
public String toString() {
return nempty(msg) ? className + ": " + msg : className;
}
}static interface Steppable {
public boolean step(); // return false if done
}static class Scored extends Var {
float score;
Scored() {}
Scored(A a, float score) { super(a); this.score = score; }
Scored(A a, double score) { super(a); this.score = (float) score; }
float score() { return score; }
public String toString() {
return toIntPercent(score) + "%: " + str(get());
}
}static class Pair implements Comparable> {
A a;
B b;
Pair() {}
Pair(A a, B b) {
this.b = b;
this.a = a;}
public int hashCode() {
return hashCodeFor(a) + 2*hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Pair)) return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
public String toString() {
return "<" + a + ", " + b + ">";
}
public int compareTo(Pair p) {
if (p == null) return 1;
int i = ((Comparable ) a).compareTo(p.a);
if (i != 0) return i;
return ((Comparable) b).compareTo(p.b);
}
}
static interface IBWImage {
int getWidth();
int getHeight();
float getFloatPixel(int x, int y);
}static abstract class VF2 {
abstract void get(A a, B b);
}static interface IVF1 {
void get(A a);
}static class Best {
A best;
double score;
boolean verboseNewBest, replaceIfSameScore;
transient Object onChange;
transient Object stringifier; // func(A) -> S
synchronized boolean isNewBest(double score) {
return best == null || !isNaN(score)
&& (replaceIfSameScore
? score >= this.score
: score > this.score);
}
synchronized double bestScore() {
return best == null ? minusInfinity() : score;
}
double score() { return bestScore(); }
double getScore() { return bestScore(); }
synchronized float floatScoreOr(float defaultValue) {
return best == null ? defaultValue : (float) score;
}
boolean put(Pair extends A, Double> p) {
return p != null && put(p.a, p.b);
}
boolean put(A a, double score) {
ping();
boolean change = false;
if (a != null) synchronized(this) {
if (isNewBest(score)) {
best = a;
this.score = score;
change = true;
}
}
if (change) {
if (verboseNewBest) print("New best! " + this);
pcallF(onChange);
}
return change;
}
synchronized A get() { return best; }
synchronized boolean has() { return best != null; }
synchronized Pair pair() { return main.pair(best, bestScore()); }
synchronized A getIfScoreAbove(double x) { return score() >= x ? best : null; }
public String toString() {
return "Score " + formatDouble_significant2(score, 4) + ": " + callStringifier(stringifier, best);
}
boolean putAndPrintIfNewBest(A a, double score) {
if (!put(a, score)) return false;
{ print(this); return true; }
}
}static interface IVar {
void set(A a);
A get();
default boolean has() { return get() != null; }
default void clear() { set(null); }
}static class ImageSurfaceSelector extends MouseAdapter {
ImageSurface is;
Point startingPoint;
boolean enabled = true;
static boolean verbose = false;
ImageSurfaceSelector(ImageSurface is) {
this.is = is;
if (containsInstance(is.tools, ImageSurfaceSelector.class)) return;
is.tools.add(this);
is.addMouseListener(this);
is.addMouseMotionListener(this);
}
public void mousePressed(MouseEvent evt) {
if (verbose) print("mousePressed");
if (evt.getButton() != MouseEvent.BUTTON1) return;
if (enabled)
startingPoint = getPoint(evt);
}
public void mouseDragged(MouseEvent e) {
if (verbose) print("mouseDragged");
if (startingPoint != null) {
Point endPoint = getPoint(e);
Rectangle r = new Rectangle(startingPoint, new Dimension(endPoint.x-startingPoint.x+1, endPoint.y-startingPoint.y+1));
normalize(r);
r.width = min(r.width, is.getImage().getWidth()-r.x);
r.height = min(r.height, is.getImage().getHeight()-r.y);
is.setSelection(r);
}
if (verbose) print("mouseDragged done");
}
public static void normalize(Rectangle r) {
if (r.width < 0) {
r.x += r.width;
r.width = -r.width;
}
if (r.height < 0) {
r.y += r.height;
r.height = -r.height;
}
}
public void mouseReleased(MouseEvent e) {
if (verbose) print("mouseReleased");
mouseDragged(e);
if (getPoint(e).equals(startingPoint))
is.setSelection((Rectangle) null);
startingPoint = null;
}
Point getPoint(MouseEvent e) {
return new Point((int) (e.getX()/is.getZoomX()), (int) (e.getY()/is.getZoomY()));
}
}static class RGB {
public float r, g, b; // can't be final cause persistence
RGB() {}
public RGB(float r, float g, float b) {
this.r = r;
this.g = g;
this.b = b;
}
public RGB(double r, double g, double b) {
this.r = (float) r;
this.g = (float) g;
this.b = (float) b;
}
public RGB(int rgb) {
this(new Color(rgb));
}
public RGB(double brightness) {
this.r = this.g = this.b = max(0f, min(1f, (float) brightness));
}
public RGB(Color color) {
this.r = color.getRed()/255f;
this.g = color.getGreen()/255f;
this.b = color.getBlue()/255f;
}
public RGB(String hex) {
int i = l(hex)-6;
r = Integer.parseInt(hex.substring(i, i+2), 16)/255f;
g = Integer.parseInt(hex.substring(i+2, i+4), 16)/255f;
b = Integer.parseInt(hex.substring(i+4, i+6), 16)/255f;
}
public float getComponent(int i) {
return i == 0 ? r : i == 1 ? g : b;
}
public Color getColor() {
return new Color(r, g, b);
}
public static RGB newSafe(float r, float g, float b) {
return new RGB(Math.max(0, Math.min(1, r)), Math.max(0, Math.min(1, g)), Math.max(0, Math.min(1, b)));
}
int asInt() { return getColor().getRGB() & 0xFFFFFF; }
int getInt() { return getColor().getRGB() & 0xFFFFFF; }
public float getBrightness() {
return (r+g+b)/3.0f;
}
public String getHexString() {
return Integer.toHexString(asInt() | 0xFF000000).substring(2).toUpperCase();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RGB)) return false;
RGB rgb = (RGB) o;
if (Float.compare(rgb.b, b) != 0) return false;
if (Float.compare(rgb.g, g) != 0) return false;
if (Float.compare(rgb.r, r) != 0) return false;
return true;
}
@Override
public int hashCode() {
int result = (r != +0.0f ? Float.floatToIntBits(r) : 0);
result = 31 * result + (g != +0.0f ? Float.floatToIntBits(g) : 0);
result = 31 * result + (b != +0.0f ? Float.floatToIntBits(b) : 0);
return result;
}
public boolean isBlack() {
return r == 0f && g == 0f && b == 0f;
}
public boolean isWhite() {
return r == 1f && g == 1f && b == 1f;
}
public String toString() {
return getHexString();
}
int redInt() { return iround(r*255); }
int greenInt() { return iround(g*255); }
int blueInt() { return iround(b*255); }
}static class RGBImage implements MakesBufferedImage {
transient BufferedImage bufferedImage;
File file;
int width, height;
int[] pixels;
RGBImage() {}
RGBImage(BufferedImage image) {
this(image, null);
}
RGBImage(BufferedImage image, File file) {
this.file = file;
bufferedImage = image;
width = image.getWidth();
height = image.getHeight();
pixels = new int[width*height];
PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
try {
if (!pixelGrabber.grabPixels())
throw new RuntimeException("Could not grab pixels");
cleanPixels(); // set upper byte to 0
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
/** We assume it's a file name to load from */
RGBImage(String file) throws IOException {
this(new File(file));
}
RGBImage(Dimension size, Color color) {
this(size.width, size.height, color);
}
RGBImage(Dimension size, RGB color) {
this(size.width, size.height, color);
}
private void cleanPixels() {
for (int i = 0; i < pixels.length; i++)
pixels[i] &= 0xFFFFFF;
}
RGBImage(int width, int height, int[] pixels) {
this.width = width;
this.height = height;
this.pixels = pixels;
}
RGBImage(int w, int h, RGB[] pixels) {
this.width = w;
this.height = h;
this.pixels = asInts(pixels);
}
public static int[] asInts(RGB[] pixels) {
int[] ints = new int[pixels.length];
for (int i = 0; i < pixels.length; i++)
ints[i] = pixels[i] == null ? 0 : pixels[i].getColor().getRGB();
return ints;
}
public RGBImage(int w, int h) {
this(w, h, Color.black);
}
RGBImage(int w, int h, RGB rgb) {
this.width = w;
this.height = h;
this.pixels = new int[w*h];
int col = rgb.asInt();
if (col != 0)
for (int i = 0; i < pixels.length; i++)
pixels[i] = col;
}
RGBImage(RGBImage image) {
this(image.width, image.height, copyPixels(image.pixels));
}
RGBImage(int width, int height, Color color) {
this(width, height, new RGB(color));
}
RGBImage(File file) throws IOException {
this(javax.imageio.ImageIO.read(file));
}
RGBImage(MakesBufferedImage img) {
this(toBufferedImage(img));
}
private static int[] copyPixels(int[] pixels) {
int[] copy = new int[pixels.length];
System.arraycopy(pixels, 0, copy, 0, pixels.length);
return copy;
}
public int getIntPixel(int x, int y) {
if (inRange(x, y))
return pixels[y * width + x];
else
return 0xFFFFFF;
}
public static RGB asRGB(int packed) {
int r = (packed >> 16) & 0xFF;
int g = (packed >> 8) & 0xFF;
int b = packed & 0xFF;
return new RGB(r / 255f, g / 255f, b / 255f);
}
public RGB getRGB(int x, int y) {
if (inRange(x, y))
return asRGB(pixels[y * width + x]);
else
return new RGB(0xFFFFFF);
}
/** alias of getRGB - I kept typing getPixel instead of getRGB all the time, so I finally created it */
RGB getPixel(int x, int y) {
return getRGB(x, y);
}
RGB getPixel(Pt p) { return getPixel(p.x, p.y); }
public int getWidth() { return width; }
public int getHeight() { return height; }
int w() { return width; }
int h() { return height; }
/** Attention: cached, i.e. does not change when image itself changes */
/** @NotNull */
public BufferedImage getBufferedImage() {
if (bufferedImage == null) {
bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//bufferedImage.setData(Raster.createRaster(new SampleModel()));
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
bufferedImage.setRGB(x, y, pixels[y*width+x]);
}
return bufferedImage;
}
RGBImage clip(Rect r) {
return r == null ? null : clip(r.getRectangle());
}
RGBImage clip(Rectangle r) {
r = fixClipRect(r);
if (r.x == 0 && r.y == 0 && r.width == width && r.height == height) return this;
int[] newPixels;
try {
newPixels = new int[r.width*r.height];
} catch (RuntimeException e) {
System.out.println(r);
throw e;
}
for (int y = 0; y < r.height; y++) {
System.arraycopy(pixels, (y+r.y)*width+r.x, newPixels, y*r.width, r.width);
}
return new RGBImage(r.width, r.height, newPixels);
}
private Rectangle fixClipRect(Rectangle r) {
r = r.intersection(new Rectangle(0, 0, width, height));
if (r.isEmpty())
r = new Rectangle(r.x, r.y, 0, 0);
return r;
}
public File getFile() {
return file;
}
/** can now also do GIF (not just JPEG) */
public static RGBImage load(String fileName) {
return load(new File(fileName));
}
/** can now also do GIF (not just JPEG) */
public static RGBImage load(File file) {
try {
BufferedImage bufferedImage = javax.imageio.ImageIO.read(file);
return new RGBImage(bufferedImage);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int getInt(int x, int y) {
return pixels[y * width + x];
}
public void save(File file) throws IOException {
String name = file.getName().toLowerCase();
String type;
if (name.endsWith(".png")) type = "png";
else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) type = "jpeg";
else throw new IOException("Unknown image extension: " + name);
javax.imageio.ImageIO.write(getBufferedImage(), type, file);
}
public static RGBImage dummyImage() {
return new RGBImage(1, 1, new int[] {0xFFFFFF});
}
public int[] getPixels() {
return pixels;
}
void setPixel(int x, int y, int r, int g, int b) {
if (x >= 0 && y >= 0 && x < width && y < height)
pixels[y*width+x] = (limitToUByte(r) << 16) | (limitToUByte(g) << 8) | limitToUByte(b);
}
public void setPixel(int x, int y, RGB rgb) {
if (x >= 0 && y >= 0 && x < width && y < height)
pixels[y*width+x] = rgb.asInt();
}
public void setPixel(int x, int y, Color color) {
setPixel(x, y, new RGB(color));
}
void setInt(int x, int y, int rgb) {
setPixel(x, y, rgb);
}
public void setPixel(int x, int y, int rgb) {
if (x >= 0 && y >= 0 && x < width && y < height)
pixels[y*width+x] = rgb;
}
void setPixel(Pt p, RGB rgb) { setPixel(p.x, p.y, rgb); }
void setPixel(Pt p, Color color) { setPixel(p.x, p.y, color); }
public RGBImage copy() {
return new RGBImage(this);
}
public boolean inRange(int x, int y) {
return x >= 0 && y >= 0 && x < width && y < height;
}
public Dimension getSize() {
return new Dimension(width, height);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RGBImage rgbImage = (RGBImage) o;
if (height != rgbImage.height) return false;
if (width != rgbImage.width) return false;
if (!Arrays.equals(pixels, rgbImage.pixels)) return false;
return true;
}
@Override
public int hashCode() {
int result = width;
result = 31 * result + height;
result = 31 * result + Arrays.hashCode(pixels);
return result;
}
public String getHex(int x, int y) {
return getPixel(x, y).getHexString();
}
public RGBImage clip(int x, int y, int width, int height) {
return clip(new Rectangle(x, y, width, height));
}
public RGBImage clipLine(int y) {
return clip(0, y, width, 1);
}
public int numPixels() {
return width*height;
}
void uncacheBufferedImage() {
bufferedImage = null;
}
}
abstract static class Surface extends JPanel {
public boolean clearSurface = true;
private boolean clearOnce = false;
Surface() {
setDoubleBuffered(false);
}
Graphics2D createGraphics2D(int width, int height, Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setBackground(getBackground());
if (clearSurface || clearOnce) {
g2.clearRect(0, 0, width, height);
clearOnce = false;
}
return g2;
}
public abstract void render(int w, int h, Graphics2D g);
public void paintImmediately(int x,int y,int w, int h) {
RepaintManager repaintManager = null;
boolean save = true;
if (!isDoubleBuffered()) {
repaintManager = RepaintManager.currentManager(this);
save = repaintManager.isDoubleBufferingEnabled();
repaintManager.setDoubleBufferingEnabled(false);
}
super.paintImmediately(x, y, w, h);
if (repaintManager != null)
repaintManager.setDoubleBufferingEnabled(save);
}
public void paint(Graphics g) {
Dimension d = getSize();
Graphics2D g2 = createGraphics2D(d.width, d.height, g);
render(d.width, d.height, g2);
g2.dispose();
}
}
static boolean reflection_isForbiddenMethod(Method m) {
return m.getDeclaringClass() == Object.class
&& eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}
static Set allInterfacesImplementedBy(Class c) {
if (c == null) return null;
HashSet set = new HashSet();
allInterfacesImplementedBy_find(c, set);
return set;
}
static void allInterfacesImplementedBy_find(Class c, Set set) {
if (c.isInterface() && !set.add(c)) return;
do {
for (Class intf : c.getInterfaces())
allInterfacesImplementedBy_find(intf, set);
} while ((c = c.getSuperclass()) != null);
}
static Method findMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args);
}
static boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static Method findStaticMethod(Class c, String method, Object... args) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (!m.getName().equals(method))
continue;
if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static boolean findStaticMethod_checkArgs(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length)
return false;
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i])))
return false;
return true;
}
static boolean stdEq2(Object a, Object b) {
if (a == null) return b == null;
if (b == null) return false;
if (a.getClass() != b.getClass()) return false;
for (String field : allFields(a))
if (neq(getOpt(a, field), getOpt(b, field)))
return false;
return true;
}
static int stdHash2(Object a) {
if (a == null) return 0;
return stdHash(a, toStringArray(allFields(a)));
}
static UnsupportedOperationException unsupportedOperation() {
throw new UnsupportedOperationException();
}
static JLabel setImage(final BufferedImage img, final JLabel lbl) {
if (lbl != null) { swing(new Runnable() { public void run() { try { lbl.setIcon(imageIcon(img));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lbl.setIcon(imageIcon(img));"; }}); }
return lbl;
}
static JLabel setImage(JLabel lbl, BufferedImage img) {
return setImage(img, lbl);
}
static JLabel setImage(final String imageID, final JLabel lbl) {
if (lbl != null) { swing(new Runnable() { public void run() { try { lbl.setIcon(imageIcon(imageID));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lbl.setIcon(imageIcon(imageID));"; }}); }
return lbl;
}
static JLabel setImage(JLabel lbl, String imageID) {
return setImage(imageID, lbl);
}
static void componentPopupMenu2(A component, final VF2 menuMaker) {
final WeakReference < A > ref = new WeakReference(component);
componentPopupMenu(component, new VF1() { public void get(JPopupMenu menu) { try {
callF(menuMaker, ref.get(), menu);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callF(menuMaker, ref!, menu);"; }});
}
// onDrop: voidfunc(File), but may also return false
static A jHandleFileDrop(A c, final Object onDrop) {
new DropTarget(c, new DropTargetAdapter() {
public void drop(DropTargetDropEvent e) {
try {
Transferable tr = e.getTransferable();
DataFlavor[] flavors = tr.getTransferDataFlavors();
for (DataFlavor flavor : flavors) {
if (flavor.isFlavorJavaFileListType()) {
e.acceptDrop(e.getDropAction());
File file = first((List) tr.getTransferData(flavor));
if (file != null && !isFalse(callF(onDrop, file)))
e.dropComplete(true);
return;
}
}
} catch (Throwable __e) { _handleException(__e); }
e.rejectDrop();
}
});
return c;
}
static A jHandleFileDrop(Object onDrop, A c) {
return jHandleFileDrop(c, onDrop);
}
static void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static void addMenuItem(JMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(Menu menu, String text, Object action) {
menu.add(menuItem(text, action));
}
static void addMenuItem(JMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static JFrame showFullScreen(JComponent c) {
return showFullScreen(defaultFrameTitle(), c);
}
static JFrame showFullScreen(final String title, final JComponent c) {
return (JFrame) swingAndWait(new F0() { public Object get() { try {
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice();
if (!gd.isFullScreenSupported())
throw fail("No full-screen mode supported!");
boolean dec = JFrame.isDefaultLookAndFeelDecorated();
if (dec) JFrame.setDefaultLookAndFeelDecorated(false);
final JFrame window = new JFrame(title);
window.setUndecorated(true);
if (dec) JFrame.setDefaultLookAndFeelDecorated(true);
registerEscape(window, new Runnable() { public void run() { try { disposeWindow(window) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disposeWindow(window)"; }});
window.add(wrap(c));
gd.setFullScreenWindow(window);
// Only this hides the task bar in Peppermint Linux w/Substance
for (int i = 100; i <= 1000; i += 100)
awtLater(i, new Runnable() { public void run() { try { window.toFront() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.toFront()"; }});
return window;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()\r\n ..."; }});
}
static void selectFile(final String msg, VF1 action) {
selectFile(msg, userDir(), action);
}
static void selectFile(final String msg, final File defaultFile, VF1 action) {
inputFilePath(msg, defaultFile, action);
}
static void copyImageToClipboard(Image img) {
TransferableImage trans = new TransferableImage(img);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents( trans, null);
vmBus_send("newClipboardContents", img);
print("Copied image to clipboard (" + img.getWidth(null) + "*" + img.getHeight(null) + " px)");
}
static JComponent selectImageSnippet(VF1 onSelect) {
return selectSnippetID_v1(onSelect);
}
static JComponent selectImageSnippet(String defaultID, VF1 onSelect) {
return selectSnippetID_v1(defaultID, onSelect);
}
static BufferedImage cloneClipBufferedImage(BufferedImage src, Rectangle clip) {
return cloneBufferedImage(clipBufferedImage(src, clip));
}
static BufferedImage cloneClipBufferedImage(BufferedImage src, Rect r) {
return cloneBufferedImage(clipBufferedImage(src, r));
}
static BufferedImage cloneClipBufferedImage(BufferedImage src, int x, int y, int w, int h) {
return cloneBufferedImage(clipBufferedImage(src, x, y, w, h));
}
static BufferedImage getImageFromClipboard() { try {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (t == null) return null;
List l = (List) (getTransferData(t, DataFlavor.javaFileListFlavor));
if (nempty(l))
return loadImage2(first(l));
if (t.isDataFlavorSupported(DataFlavor.imageFlavor))
return (BufferedImage) t.getTransferData(DataFlavor.imageFlavor);
return imageFromDataURL(getTextFromClipboard());
} catch (Exception __e) { throw rethrow(__e); } }
static File getProgramDir() {
return programDir();
}
static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
static void popup(final Throwable throwable) {
popupError(throwable);
}
static void popup(final String msg) {
print(msg);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, msg);
}
});
}
static A _print(String s, A a) {
return print(s, a);
}
static A _print(A a) {
return print(a);
}
static void _print() {
print();
}
static boolean hasTransparency(BufferedImage img) {
return img.getColorModel().hasAlpha();
}
static BufferedImage resizeImage(BufferedImage img, int newW, int newH) {
return resizeImage(img, newW, newH, Image.SCALE_SMOOTH);
}
static BufferedImage resizeImage(BufferedImage img, int newW, int newH, int scaleType) {
if (newW == img.getWidth() && newH == img.getHeight()) return img;
Image tmp = img.getScaledInstance(newW, newH, scaleType);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
static BufferedImage resizeImage(BufferedImage img, int newW) {
int newH = iround(img.getHeight()*(double) newW/img.getWidth());
return resizeImage(img, newW, newH);
}
static BufferedImage resizeImage(int newW, BufferedImage img) {
return resizeImage(img, newW);
}
static A revalidate(final A c) {
if (c == null || !c.isShowing()) return c;
{ swing(new Runnable() { public void run() { try {
// magic combo to actually relayout and repaint
c.revalidate();
c.repaint();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// magic combo to actually relayout and repaint\r\n c.revalidate();\r\n c.r..."; }}); }
return c;
}
static void revalidate(JFrame f) { revalidate((Component) f); }
static void revalidate(JInternalFrame f) { revalidate((Component) f); }
static A repaint(A c) {
if (c != null) c.repaint();
return c;
}
static Dimension getMinimumSize(final Component c) {
return c == null ? null : swing(new F0() { public Dimension get() { try { return c.getMinimumSize(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret c.getMinimumSize();"; }});
}
static boolean imagesHaveSameSize(BufferedImage a, BufferedImage b) {
return a != null && b != null && a.getWidth() == b.getWidth()
&& a.getHeight() == b.getHeight();
}
static Dimension getPreferredSize(final Component c) {
return c == null ? null : swing(new F0() { public Dimension get() { try { return c.getPreferredSize(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret c.getPreferredSize();"; }});
}
static Container getParent(final Component c) {
return c == null ? null : swing(new F0() { public Container get() { try { return c.getParent(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret c.getParent();"; }});
}
static JScrollPane enclosingScrollPane(Component c) {
while (c.getParent() != null && !(c.getParent() instanceof JViewport) && c.getParent().getComponentCount() == 1) c = c.getParent(); // for jscroll_center
if (!(c.getParent() instanceof JViewport)) return null;
c = c.getParent().getParent();
return c instanceof JScrollPane ? (JScrollPane) c : null;
}
// independent timer
static void awtLater(int delay, final Object r) {
swingLater(delay, r);
}
static void awtLater(Object r) {
swingLater(r);
}
// dependent timer (runs only when component is visible)
static void awtLater(JComponent component, int delay, Object r) {
installTimer(component, r, delay, delay, false);
}
static void awtLater(JFrame frame, int delay, Object r) {
awtLater(frame.getRootPane(), delay, r);
}
static Class> hotwire(String src) {
assertFalse(_inCore());
Class j = getJavaX();
if (isAndroid()) {
synchronized(j) { // hopefully this goes well...
List libraries = new ArrayList();
File srcDir = (File) call(j, "transpileMain", src, libraries);
if (srcDir == null)
throw fail("transpileMain returned null (src=" + quote(src) + ")");
Object androidContext = get(j, "androidContext");
return (Class) call(j, "loadx2android", srcDir, src);
}
} else {
Class c = (Class) (call(j, "hotwire", src));
hotwire_copyOver(c);
return c;
}
}
static ImageSurface showFullScreenImageSurface(BufferedImage img) {
ImageSurface is = jImageSurface(img);
showFullScreen(jscroll_centered(disposeFrameOnClick(is)));
return is;
}
static void fillArrayUnlessZero(byte[] a, byte value) {
if (value != 0) Arrays.fill(a, value);
}
static void fillArrayUnlessZero(int[] a, int value) {
if (value != 0) Arrays.fill(a, value);
}
static void fillArrayUnlessZero(float[] a, float value) {
if (value != 0) Arrays.fill(a, value);
}
static boolean inRange(int x, int n) {
return x >= 0 && x < n;
}
static boolean inRange(int x, int a, int b) {
return x >= a && x < b;
}
static int ubyteToInt(byte b) {
return b & 0x0FF;
}
static double averageBrightness(BufferedImage img) {
return new BWImage(img).averageBrightness();
}
static int limitToUByte(int i) {
return max(0, min(255, i));
}
static ThreadLocal componentPopupMenu_mouseEvent;
static void componentPopupMenu_init() {
{ swing(new Runnable() { public void run() { try {
if (componentPopupMenu_mouseEvent == null)
componentPopupMenu_mouseEvent = (ThreadLocal) vm_generalMap_get("mouseEvent");
if (componentPopupMenu_mouseEvent == null)
vm_generalMap_put("componentPopupMenu_mouseEvent" , componentPopupMenu_mouseEvent = new ThreadLocal());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (componentPopupMenu_mouseEvent == null)\r\n componentPopupMenu_mouseEve..."; }}); }
}
// menuMaker = voidfunc(JPopupMenu)
static void componentPopupMenu(final JComponent component, final Object menuMaker) {
if (component == null || menuMaker == null) return;
{ swing(new Runnable() { public void run() { try {
Object adapter = componentPopupMenu_initForComponent(component);
((List) _get(adapter, "maker")).add(menuMaker);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object adapter = componentPopupMenu_initForComponent(component);\r\n ((List)..."; }}); }
}
static Object componentPopupMenu_initForComponent(final JComponent component) {
return component == null ? null : swing(new F0() { public Object get() { try {
componentPopupMenu_init();
Object adapter = findComponentPopupMenuListener_gen(component);
if (adapter == null) {
componentPopupMenu_Adapter a = new componentPopupMenu_Adapter();
component.addMouseListener(a);
adapter = a;
}
return adapter;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "componentPopupMenu_init();\r\n O adapter = findComponentPopupMenuListener_ge..."; }});
}
static class componentPopupMenu_Adapter extends MouseAdapter {
List maker = new ArrayList();
boolean internalFrameLeftButtonMagic = false;
Point pressedAt;
public void mousePressed(MouseEvent e) {
displayMenu(e);
pressedAt = internalFrameLeftButtonMagic && e.getClickCount() == 1 && internalFrameActive(e.getComponent()) ? e.getLocationOnScreen() : null;
}
public void mouseReleased(MouseEvent e) {
// TODO: show a little less often on left mouse click
if (internalFrameLeftButtonMagic && eq(pressedAt, e.getLocationOnScreen()))
displayMenu2(e);
else
displayMenu(e);
}
void displayMenu(MouseEvent e) {
if (e.getSource() instanceof JInternalFrame) return;
if (e.isPopupTrigger()) displayMenu2(e);
}
void displayMenu2(MouseEvent e) {
JPopupMenu menu = new JPopupMenu();
int emptyCount = menu.getComponentCount();
AutoCloseable __1 = tempSetTL(componentPopupMenu_mouseEvent, e); try {
for (Object menuMaker : maker)
pcallF(menuMaker, menu);
vmBus_send("showingPopupMenu", e.getComponent(), menu);
// show menu if any items in it
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
} finally { _close(__1); }}
}
static A setToolTipText(final A c, final Object toolTip) {
if (c == null) return null;
{ swing(new Runnable() { public void run() { try {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ..."; }}); }
return c;
}
static A setToolTipText(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
static String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
static List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
static String copyTextToClipboard(Object _text) {
String text = str(_text);
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
vmBus_send("newClipboardContents", text);
return text;
}
static int bwIntegralImage_sumRect(BWIntegralImage img, int x1, int y1, int x2, int y2) {
int bottomLeft = img.get(x1-1, y2-1);
int bottomRight = img.get(x2-1, y2-1);
int topLeft = img.get(x1-1, y1-1);
int topRight = img.get(x2-1, y1-1);
return bottomRight+topLeft-topRight-bottomLeft;
}
static BWImage scaleDownUsingIntegralImageBW(int w, BWIntegralImage img) {
return scaleDownUsingIntegralImageBW(img, w);
}
static BWImage scaleDownUsingIntegralImageBW(BWIntegralImage img, int w) {
return scaleDownUsingIntegralImageBW(img, w, iround(w*img.h/(double) img.w));
}
static BWImage scaleDownUsingIntegralImageBW(BWIntegralImage img, int w, int h) {
int w1 = img.w, h1 = img.h;
BWImage out = new BWImage(w, h);
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
int x1 = x*w1/w, x2 = max(x1+1, (x+1)*w1/w);
int y1 = y*h1/h, y2 = max(y1+1, (y+1)*h1/h);
int area = (x2-x1)*(y2-y1);
int pixel = bwIntegralImage_sumRect(img, x1, y1, x2, y2)/area;
out.setByte(x, y, (byte) pixel);
}
return out;
}
static float score(Scored s) {
return s == null ? 0 : s.score();
}
static File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
static boolean nempty(Collection c) {
return !empty(c);
}
static boolean nempty(CharSequence s) {
return !empty(s);
}
static boolean nempty(Object[] o) { return !empty(o); }
static boolean nempty(byte[] o) { return !empty(o); }
static boolean nempty(int[] o) { return !empty(o); }
static boolean nempty(Map m) {
return !empty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean nempty(Object o) { return !empty(o); }
static int toIntPercent(double ratio) {
return roundToInt(ratio*100);
}
// when used with map function
static int toIntPercent(float ratio) {
return toIntPercent((double) ratio);
}
static int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
static boolean isNaN(double d) {
return Double.isNaN(d);
}
static double minusInfinity() {
return negativeInfinity();
}
static String formatDouble_significant2(double d, int digits) {
try {
digits -= max(0, Math.floor(Math.log10(abs(d))+1));
return formatDouble(d, digits);
} catch (Throwable _e) {
print("Had number: " + d + ", digits: " + digits);
throw rethrow(_e); }
}
static String callStringifier(Object stringifier, Object o) {
return stringifier != null ? str(callF(stringifier, o)) : str(o);
}
static A set(A o, String field, Object value) {
if (o == null) return null;
if (o instanceof Class) set((Class) o, field, value);
else try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
static void set(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static boolean containsInstance(Iterable i, Class c) {
if (i != null) for (Object o : i)
if (isInstanceX(c, o))
return true;
return false;
}
static int asInt(Object o) {
return toInt(o);
}
static A setDoubleBuffered(A c, boolean b) {
{ swing(new Runnable() { public void run() { try { if (c != null) c.setDoubleBuffered(b);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c?.setDoubleBuffered(b);"; }}); }
return c;
}
static Color getBackground(final Component c) {
return c == null ? null : swing(new F0() { public Color get() { try { return c.getBackground(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret c.getBackground();"; }});
}
static Method findMethod_cached(Object o, String method, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
_MethodCache cache = callOpt_getCache(((Class) o));
List methods = cache.cache.get(method);
if (methods != null) for (Method m : methods)
if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
return m;
return null;
} else {
_MethodCache cache = callOpt_getCache(o.getClass());
List methods = cache.cache.get(method);
if (methods != null) for (Method m : methods)
if (findMethod_checkArgs(m, args, false))
return m;
return null;
}
} catch (Exception __e) { throw rethrow(__e); } }
static Set allFields(Object o) {
TreeSet fields = new TreeSet();
Class _c = _getClass(o);
do {
for (Field f : _c.getDeclaredFields())
fields.add(f.getName());
_c = _c.getSuperclass();
} while (_c != null);
return fields;
}
static int stdHash(Object a, String... fields) {
if (a == null) return 0;
int hash = getClassName(a).hashCode();
for (String field : fields)
hash = boostHashCombine(hash, hashCode(getOpt(a, field)));
return hash;
}
static String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++)
a[i] = it.next();
return a;
}
static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
static int imageIcon_cacheSize = 10;
static boolean imageIcon_verbose = false;
static Map imageIcon_cache;
static Lock imageIcon_lock = lock();
static ThreadLocal imageIcon_fixGIF = new ThreadLocal();
// not going through BufferedImage preserves animations
static ImageIcon imageIcon(String imageID) { try {
if (imageID == null) return null;
Lock __0 = imageIcon_lock; lock(__0); try {
if (imageIcon_cache == null)
imageIcon_cache = new MRUCache(imageIcon_cacheSize);
imageID = fsI(imageID);
ImageIcon ii = imageIcon_cache.get(imageID);
if (ii == null) {
if (imageIcon_verbose) print("Loading image icon: " + imageID);
File f = loadBinarySnippet(imageID);
Boolean b = imageIcon_fixGIF.get();
if (!isFalse(b))
ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
else
ii = new ImageIcon(f.toURI().toURL());
} else
imageIcon_cache.remove(imageID); // move to front of cache on access
imageIcon_cache.put(imageID, ii);
return ii;
} finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } }
// doesn't fix GIFs
static ImageIcon imageIcon(File f) { try {
return new ImageIcon(f.toURI().toURL());
} catch (Exception __e) { throw rethrow(__e); } }
static ImageIcon imageIcon(Image img) {
return new ImageIcon(img);
}
static ImageIcon imageIcon(RGBImage img) {
return imageIcon(img.getBufferedImage());
}
static boolean jmenuItem_newThreads = false;
static JMenuItem jmenuItem(final String text) {
return jMenuItem(text, null);
}
static JMenuItem jmenuItem(final String text, final Object r) {
return swing(new F0() { public JMenuItem get() { try {
Pair p = jmenu_autoMnemonic(dropPrefix("[disabled] ", text));
JMenuItem mi = new JMenuItem(p.a);
if (startsWith(text, "[disabled] ")) disableMenuItem(mi);
if (p.b != 0) mi.setMnemonic(p.b);
mi.addActionListener(jmenuItem_newThreads
? actionListenerInNewThread(r)
: actionListener(r));
return mi;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Pair p = jmenu_autoMnemonic(dropPrefix(\"[disabled] \", text));\r\n JM..."; }});
}
static MenuItem menuItem(String text, final Object r) {
MenuItem mi = new MenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
static String defaultFrameTitle() {
return autoFrameTitle();
}
static void defaultFrameTitle(String title) {
autoFrameTitle_value = title;
}
static void registerEscape(JFrame frame, final Runnable r) {
registerEscape_rootPane(frame.getRootPane(), r);
}
static void disposeWindow(final Window window) {
if (window != null) { swing(new Runnable() { public void run() { try {
window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); // call listeners
myFrames_list.remove(window);
window.dispose();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //..."; }}); }
}
static void disposeWindow(final Component c) {
disposeWindow(getWindow(c));
}
static void disposeWindow(Object o) {
if (o != null) disposeWindow(((Component) o));
}
static void disposeWindow() {
disposeWindow(heldInstance(Component.class));
}
static void inputFilePath(final String msg, final Object action) {
inputFilePath(msg, userDir(), action);
}
// action: voidfunc(File)
static void inputFilePath(final String msg, final File defaultFile, final Object action) {
swingLater(new Runnable() { public void run() { try {
final JTextField tfPath = jtextfield(f2s(or(defaultFile, userDir())));
String title = joinStrings(" | ", msg, programName());
JComponent form = showFormTitled(title,
unnull(msg), centerAndEast(tfPath, jbutton("Browse...", new Runnable() { public void run() { try {
JFileChooser fileChooser = new JFileChooser(getTextTrim(tfPath));
if (fileChooser.showOpenDialog(tfPath) == JFileChooser.APPROVE_OPTION) {
tfPath.setText(fileChooser.getSelectedFile().getAbsolutePath());
tfPath.requestFocus();
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFileChooser fileChooser = new JFileChooser(getTextTrim(tfPath));\r\n if..."; }})), new Runnable() { public void run() { try {
callF(action, new File(getTextTrim(tfPath)))
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(action, new File(getTextTrim(tfPath)))"; }});
renameSubmitButton(form, "OK");
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tfPath = jtextfield(f2s(or(defaultFile, userDir())));\r\n S..."; }});
}
static JComponent selectSnippetID_v1(final VF1 onSelect) {
return selectSnippetID_v1("#", onSelect);
}
static JComponent selectSnippetID_v1(String defaultID, final VF1 onSelect) {
final JTextField tfSnippetID = jtextfield(defaultID);
if (eq(defaultID, "#")) moveCaretToEnd(tfSnippetID);
JComponent panel;
renameSubmitButton(panel = showTitledForm("Select Snippet",
"Snippet ID:", tfSnippetID, runnableThread(new Runnable() { public void run() { try {
callF(onSelect, fsI(getTextTrim(tfSnippetID)));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onSelect, fsI(getTextTrim(tfSnippetID)));"; }})), "Select snippet");
return panel;
}
static BufferedImage cloneBufferedImage(BufferedImage image) {
return copyImage(image);
}
static BufferedImage clipBufferedImage(BufferedImage src, Rectangle clip) {
return clipBufferedImage(src, new Rect(clip));
}
static BufferedImage clipBufferedImage(BufferedImage src, Rect r) {
if (src == null || r == null) return null;
// fixClipRect
r = intersectRects(r, new Rect(0, 0, src.getWidth(), src.getHeight()));
if (rectEmpty(r)) return null; // can't make zero-sized BufferedImage
return src.getSubimage(r.x, r.y, r.w, r.h);
}
static BufferedImage clipBufferedImage(BufferedImage src, int x, int y, int w, int h) {
return clipBufferedImage(src, new Rect(x, y, w, h));
}
static Object getTransferData(Transferable t, DataFlavor flavor) { try {
return t != null && t.isDataFlavorSupported(flavor) ? t.getTransferData(flavor) : null;
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage imageFromDataURL(String url) {
String pref = "base64,";
int i = indexOf(url, pref);
if (i < 0) return null;
return decodeImage(base64decode(substring(url, i+l(pref))));
}
static String getTextFromClipboard() { try {
Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor))
return (String) transferable.getTransferData(DataFlavor.stringFlavor);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
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 void popupError(final Throwable throwable) {
throwable.printStackTrace(); // print stack trace to console for the experts
SwingUtilities.invokeLater(new Runnable() {
public void run() {
String text = throwable.toString();
//text = cutPrefix(text, "java.lang.RuntimeException: ");
JOptionPane.showMessageDialog(null, text);
}
});
}
static void swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
timer.setRepeats(false);
timer.start();
}
static void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
// first delay = delay
static Timer installTimer(JComponent component, Object r, long delay) {
return installTimer(component, r, delay, delay);
}
// first delay = delay
static Timer installTimer(RootPaneContainer frame, long delay, Object r) {
return installTimer(frame.getRootPane(), r, delay, delay);
}
// first delay = delay
static Timer installTimer(JComponent component, long delay, Object r) {
return installTimer(component, r, delay, delay);
}
static Timer installTimer(JComponent component, long delay, long firstDelay, Object r) {
return installTimer(component, r, delay, firstDelay);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) {
return installTimer(component, r, delay, firstDelay, true);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) {
if (component == null) return null;
return (Timer) swingAndWait(new F0() { public Object get() { try {
final Var timer = new Var();
timer.set(new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
AutoCloseable __1 = tempActivity(r); try {
try {
if (!allPaused())
if (isFalse(callF(r)))
cancelTimer(timer.get());
} catch (Throwable __e) { _handleException(__e); }
} finally { _close(__1); }} catch (Throwable __e) { messageBox(__e); }}}));
timer.get().setInitialDelay(toInt(firstDelay));
timer.get().setRepeats(repeats);
bindTimerToComponent(timer.get(), component);
return timer.get();
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final new Var timer;\r\n timer.set(new Timer(toInt(delay), actionList..."; }});
}
static Timer installTimer(RootPaneContainer frame, long delay, long firstDelay, Object r) {
return installTimer(frame.getRootPane(), delay, firstDelay, r);
}
static void assertFalse(Object o) {
if (!(eq(o, false) /*|| isFalse(pcallF(o))*/))
throw fail(str(o));
}
static boolean assertFalse(boolean b) {
if (b) throw fail("oops");
return b;
}
static boolean assertFalse(String msg, boolean b) {
if (b) throw fail(msg);
return b;
}
static boolean _inCore() {
return false;
}
static String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder((int) (l(s)*1.5+2));
quote_impl(s, out);
return out.toString();
}
static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static List hotwire_copyOver_after = synchroList();
static void hotwire_copyOver(Class c) {
// TODO: make a mechanism for making such "inheritable" fields
for (String field : ll("print_log", "print_silent", "androidContext", "_userHome"))
setOptIfNotNull(c, field, getOpt(mc(), field));
setOptIfNotNull(c, "mainBot" , getMainBot());
setOpt(c, "creator_class" , new WeakReference(mc()));
pcallFAll(hotwire_copyOver_after, c);
}
static A disposeFrameOnClick(final A c) {
onClick(c, new Runnable() { public void run() { try { disposeFrame(c) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disposeFrame(c)"; }});
return c;
}
static A _get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static Object _get(Object o, String field) {
return get(o, field);
}
static Object _get(String field, Object o) {
return get(o, field);
}
static A _get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
static Object findComponentPopupMenuListener_gen(final JComponent c) {
return c == null ? null : swing(new F0() { public Object get() { try {
return firstWithClassShortNamed("componentPopupMenu_Adapter", c.getMouseListeners());
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret firstWithClassShortNamed('componentPopupMenu_Adapter, c.getMouseListeners..."; }});
}
static boolean internalFrameActive(Component c) {
final JInternalFrame f = getInternalFrame(c);
return f != null && swing(new F0() { public Boolean get() { try { return f.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret f.isSelected();"; }});
}
static AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static void _close(AutoCloseable c) {
if (c != null) try {
c.close();
} catch (Throwable e) {
// Some classes stupidly throw an exception on double-closing
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else throw rethrow(e);
}
}
static boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static boolean isEmpty(Object[] a) { return a == null || a.length == 0; }
static boolean isEmpty(byte[] a) { return a == null || a.length == 0; }
static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static File loadBinarySnippet(String snippetID) { try {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
long id = parseSnippetID(snippetID);
if (isImageServerSnippet(id)) return loadImageAsFile(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile(snippetID);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static int roundToInt(double d) {
return (int) Math.round(d);
}
static double negativeInfinity() {
return Double.NEGATIVE_INFINITY;
}
static float abs(float f) { return Math.abs(f); }
static int abs(int i) { return Math.abs(i); }
static double abs(double d) { return Math.abs(d); }
static String formatDouble(double d, int digits) {
String format = digits <= 0 ? "0" : "0." + rep(digits, '#');
return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d);
}
static void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
// take care of common case (long to int)
if (type == int.class && value instanceof Long)
value = ((Long) value).intValue();
if (type == LinkedHashMap.class && value instanceof Map)
{ f.set(o, asLinkedHashMap((Map) value)); return; }
throw e;
}
}
static int toInt(Object o) {
if (o == null) return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt(((String) o));
if (o instanceof Boolean)
return boolToInt(((Boolean) o));
throw fail("woot not int: " + getClassName(o));
}
static int toInt(long l) {
if (l != (int) l) throw fail("Too large for int: " + l);
return (int) l;
}
static Map myFrames_list = weakHashMap();
static List myFrames() {
return swing(new F0>() { public List get() { try { return keysList(myFrames_list); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret keysList(myFrames_list);"; }});
}
static int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
static int hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static void lock(Lock lock) { try {
ping();
if (lock == null) return;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
print("Locking interrupted! I probably deadlocked, oops.");
printStackTrace(e);
rethrow(e);
}
ping();
} catch (Exception __e) { throw rethrow(__e); } }
static void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static ReentrantLock lock() {
return fairLock();
}
static boolean loadBufferedImageFixingGIFs_debug = false;
static ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal();
static Image loadBufferedImageFixingGIFs(File file) { try {
if (!file.exists()) return null;
// Load anything but GIF the normal way
if (!isGIF(file))
return ImageIO.read(file);
if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": checking gif");
// Get GIF reader
ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
// Give it the stream to decode from
reader.setInput(ImageIO.createImageInputStream(file));
int numImages = reader.getNumImages(true);
// Get 'metaFormatName'. Need first frame for that.
IIOMetadata imageMetaData = reader.getImageMetadata(0);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
// Find out if GIF is bugged
boolean foundBug = false;
for (int i = 0; i < numImages && !foundBug; i++) {
// Get metadata
IIOMetadataNode root = (IIOMetadataNode)reader.getImageMetadata(i).getAsTree(metaFormatName);
// Find GraphicControlExtension node
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
// Get delay value
String delay = ((IIOMetadataNode)node).getAttribute("delayTime");
// Check if delay is bugged
if (Integer.parseInt(delay) == 0) {
foundBug = true;
}
break;
}
}
}
if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
// Load non-bugged GIF the normal way
Image image;
if (!foundBug) {
image = Toolkit.getDefaultToolkit().createImage(f2s(file));
} else {
// Prepare streams for image encoding
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
{
ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream); try {
// Get GIF writer that's compatible with reader
ImageWriter writer = ImageIO.getImageWriter(reader);
// Give it the stream to encode to
writer.setOutput(ios);
writer.prepareWriteSequence(null);
for (int i = 0; i < numImages; i++) {
// Get input image
BufferedImage frameIn = reader.read(i);
// Get input metadata
IIOMetadataNode root = (IIOMetadataNode)reader.getImageMetadata(i).getAsTree(metaFormatName);
// Find GraphicControlExtension node
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
// Get delay value
String delay = ((IIOMetadataNode)node).getAttribute("delayTime");
// Check if delay is bugged
if (Integer.parseInt(delay) == 0) {
// Overwrite with a valid delay value
((IIOMetadataNode)node).setAttribute("delayTime", "10");
}
break;
}
}
// Create output metadata
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
// Copy metadata to output metadata
metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
// Create output image
IIOImage frameOut = new IIOImage(frameIn, null, metadata);
// Encode output image
writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
}
writer.endWriteSequence();
} finally { _close(ios); }}
// Create image using encoded data
byte[] data = baoStream.toByteArray();
setVar(loadBufferedImageFixingGIFs_output.get(), data);
if (loadBufferedImageFixingGIFs_debug) print("Data size: " + l(data));
image = Toolkit.getDefaultToolkit().createImage(data);
}
return image;
} catch (Exception __e) { throw rethrow(__e); } }
static void unlock(Lock lock, String msg) {
if (lock == null) return;
print("Unlocking: " + msg);
lock.unlock();
}
static void unlock(Lock lock) {
if (lock == null) return;
lock.unlock();
}
static JMenuItem jMenuItem(final String text) {
return jmenuItem(text);
}
static JMenuItem jMenuItem(String text, Object r) {
return jmenuItem(text, r);
}
static Pair jmenu_autoMnemonic(String s) {
int i = indexOf(s, '&');
if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i+1)))
return pair(substring(s, 0, i) + substring(s, i+1), (int) s.charAt(i+1));
return pair(s, 0);
}
static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static JMenuItem disableMenuItem(final JMenuItem mi) {
if (mi != null) { swing(new Runnable() { public void run() { try { mi.setEnabled(false);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "mi.setEnabled(false);"; }}); }
return mi;
}
static ActionListener actionListenerInNewThread(final Object runnable) {
return actionListenerInNewThread(runnable, null);
}
static ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
startThread("Action Listener", new Runnable() { public void run() { try {
AutoCloseable __1 = holdInstance(instanceToHold); try {
callF(runnable);
} finally { _close(__1); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __1 = holdInstance(instanceToHold); try {\r\n callF(runnable..."; }});
} catch (Throwable __e) { messageBox(__e); }}};
}
static ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
static ActionListener actionListener(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
final Object info = _threadInfo();
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
_threadInheritInfo(info);
AutoCloseable __1 = holdInstance(instanceToHold); try {
callF(runnable);
} finally { _close(__1); }} catch (Throwable __e) { messageBox(__e); }}};
}
static String autoFrameTitle_value;
static String autoFrameTitle() {
return autoFrameTitle_value != null ? autoFrameTitle_value : getProgramTitle();
}
static void autoFrameTitle(Component c) {
setFrameTitle(getFrame(c), autoFrameTitle());
}
static void registerEscape_rootPane(JComponent rootPane, final Runnable r) {
String name = "Escape";
Action action = abstractAction(name, r);
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
rootPane.getActionMap().put(name, action);
rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name);
}
static Window getWindow(Object o) {
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof Window) return (Window) c;
c = c.getParent();
}
return null;
}
static A heldInstance(Class c) {
List l = holdInstance_l.get();
for (int i = l(l)-1; i >= 0; i--) {
Object o = l.get(i);
if (isInstanceOf(o, c))
return (A) o;
}
throw fail("No instance of " + className(c) + " held");
}
static JTextField jtextfield() {
return jTextField();
}
static JTextField jtextfield(String text) {
return jTextField(text);
}
static JTextField jtextfield(Object o) {
return jTextField(o);
}
static String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static String f2s(String s) { return f2s(newFile(s)); }
static String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static String joinStrings(String sep, String... strings) {
return joinStrings(sep, Arrays.asList(strings));
}
static String joinStrings(String sep, Collection strings) {
StringBuilder buf = new StringBuilder();
for (String s : unnull(strings)) if (nempty(s)) {
if (nempty(buf)) buf.append(sep);
buf.append(s);
}
return str(buf);
}
static String programName() {
return getProgramName();
}
static int showForm_defaultGap = 4;
static int showForm_gapBetweenColumns = 10;
static JPanel showFormTitled(final String title, final Object... _parts) {
JDesktopPane desktop = mainDesktopPane();
if (desktop != null) return showInternalFrameFormTitled(desktop, title, _parts);
return swing(new F0() { public JPanel get() { try {
final Var frame = new Var();
JPanel panel = showForm_makePanel(false, _parts);
frame.set(showForm_makeFrame(title, panel));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final new Var frame;\r\n JPanel panel = showForm_makePanel(false, _p..."; }});
}
static JPanel showForm_makePanel(Boolean internalFrame, Object... _parts) {
List out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts));
return vstackWithSpacing(out, showForm_defaultGap);
}
static JPanel centerAndEast(final Component c, final Component e) {
return swing(new F0() { public JPanel get() { try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.EAST, wrap(e));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT..."; }});
}
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 String getTextTrim(JTextComponent c) {
return trim(getText(c));
}
// tested for editable combo box - returns the contents of text field
static String getTextTrim(JComboBox cb) {
return trim(getText(cb));
}
static String getTextTrim(JComponent c) {
if (c instanceof JLabel) return trim(((JLabel) c).getText());
if (c instanceof JComboBox) return getTextTrim((JComboBox) c);
return getTextTrim((JTextComponent) c);
}
static A renameSubmitButton(A form, String newName) {
renameButton(form, showFormSubmitButtonName(), newName);
return form;
}
static A renameSubmitButton(String newName, A form) {
return renameSubmitButton(form, newName);
}
static A moveCaretToEnd(A ta) {
setCaretPosition(ta, textAreaTextLength(ta));
return ta;
}
static JComponent showTitledForm(String title, Object... _parts) {
return showFormTitled(title, _parts);
}
static Runnable runnableThread(final Runnable r) {
return new Runnable() { public void run() { try { startThread(r) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "startThread(r)"; }};
}
static BufferedImage copyImage(BufferedImage bi) {
if (bi == null) return null;
ColorModel cm = bi.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = bi.copyData(bi.getRaster().createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
static Rect intersectRects(Rect a, Rect b) {
int x = max(a.x, b.x), y = max(a.y, b.y);
int x2 = min(a.x+a.w, b.x+b.w), y2 = min(a.y+a.h, b.y+b.h);
return new Rect(x, y, x2-x, y2-y);
}
static boolean rectEmpty(Rect r) {
return r == null || r.w <= 0 || r.h <= 0;
}
static BufferedImage decodeImage(byte[] data) { try {
return ImageIO.read(new ByteArrayInputStream(data));
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] base64decode(String s) {
byte[] alphaToInt = base64decode_base64toint;
int sLen = s.length();
int numGroups = sLen/4;
if (4*numGroups != sLen)
throw new IllegalArgumentException(
"String length must be a multiple of four.");
int missingBytesInLastGroup = 0;
int numFullGroups = numGroups;
if (sLen != 0) {
if (s.charAt(sLen-1) == '=') {
missingBytesInLastGroup++;
numFullGroups--;
}
if (s.charAt(sLen-2) == '=')
missingBytesInLastGroup++;
}
byte[] result = new byte[3*numGroups - missingBytesInLastGroup];
// Translate all full groups from base64 to byte array elements
int inCursor = 0, outCursor = 0;
for (int i=0; i> 4));
result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
result[outCursor++] = (byte) ((ch2 << 6) | ch3);
}
// Translate partial group, if present
if (missingBytesInLastGroup != 0) {
int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
if (missingBytesInLastGroup == 1) {
int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
}
}
// assert inCursor == s.length()-missingBytesInLastGroup;
// assert outCursor == result.length;
return result;
}
static int base64decode_base64toint(char c, byte[] alphaToInt) {
int result = alphaToInt[c];
if (result < 0)
throw new IllegalArgumentException("Illegal character " + c);
return result;
}
static final byte base64decode_base64toint[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};
static String programID;
static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
// TODO: ask JavaX instead
static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b)) return false;
return parseSnippetID(a) == parseSnippetID(b);
}
static String programID() {
return getProgramID();
}
static String programID(Object o) {
return getProgramID(o);
}
static File javaxDataDir_dir; // can be set to work on different base dir
static File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static File javaxDataDir(String... subs) {
return newFile(javaxDataDir(), subs);
}
static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static volatile String caseID_caseID;
static String caseID() { return caseID_caseID; }
static void caseID(String id) {
caseID_caseID = id;
}
static Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
static AutoCloseable tempActivity(Object r) {
return null;
}
static boolean allPaused() {
return ping_pauseAll;
}
static void cancelTimer(javax.swing.Timer timer) {
if (timer != null) timer.stop();
}
static void cancelTimer(java.util.Timer timer) {
if (timer != null) timer.cancel();
}
static void cancelTimer(Object o) {
if (o instanceof java.util.Timer) cancelTimer((java.util.Timer) o);
else if (o instanceof javax.swing.Timer) cancelTimer((javax.swing.Timer) o);
else if (o instanceof AutoCloseable) { try { ((AutoCloseable) o).close(); } catch (Throwable __e) { _handleException(__e); }}
}
static void messageBox(final String msg) {
if (headless()) print(msg);
else { swing(new Runnable() { public void run() { try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES..."; }}); }
}
static void messageBox(Throwable e) {
//showConsole();
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
static void bindTimerToComponent(final Timer timer, JFrame f) {
bindTimerToComponent(timer, f.getRootPane());
}
static void bindTimerToComponent(final Timer timer, JComponent c) {
if (c.isShowing())
timer.start();
c.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
timer.start();
}
public void ancestorRemoved(AncestorEvent event) {
timer.stop();
}
public void ancestorMoved(AncestorEvent event) {
}
});
}
static void setOptIfNotNull(Object o, String field, Object value) {
if (value != null) setOpt(o, field, value);
}
static Object mainBot;
static Object getMainBot() {
return mainBot;
}
static Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
static void setOpt(Object o, String field, Object value) { try {
if (o == null) return;
Class c = o.getClass();
HashMap map;
if (getOpt_cache == null)
map = getOpt_makeCache(c); // in class init
else synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
// It's probably a subclass of Map. Use raw method
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null)
{ smartSet(f, o, value); return; } // possible improvement: skip setAccessible
if (o instanceof DynamicObject)
setDyn(((DynamicObject) o), field, value);
} catch (Exception __e) { throw rethrow(__e); } }
static void setOpt(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = setOpt_findStaticField(c, field); // TODO: optimize
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
makeAccessible(f);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static A onClick(final A c, final Object runnable) {
if (c != null) { swing(new Runnable() { public void run() { try {
c.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
callF(runnable, e);
}
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(MouseEv..."; }}); }
return c;
}
// re-interpreted for buttons
static void onClick(JButton btn, final Object runnable) {
onEnter(btn, runnable);
}
static void disposeFrame(final Component c) {
disposeWindow(c);
}
static A firstWithClassShortNamed(String shortName, Iterable l) {
if (l != null) for (A o : l)
if (eq(shortClassName(o), shortName))
return o;
return null;
}
static A firstWithClassShortNamed(String shortName, A[] l) {
if (l != null) for (A o : l)
if (eq(shortClassName(o), shortName))
return o;
return null;
}
static JInternalFrame getInternalFrame(final Object _o) {
return _o == null ? null : swing(new F0() { public JInternalFrame get() { try {
Object o = _o;
if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JInternalFrame) return (JInternalFrame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; }});
}
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 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 {
snippetID = fsI(snippetID);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(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 String rep(int n, char c) {
return repeat(c, n);
}
static String rep(char c, int n) {
return repeat(c, n);
}
static List rep(A a, int n) {
return repeat(a, n);
}
static List rep(int n, A a) {
return repeat(n, a);
}
static LinkedHashMap asLinkedHashMap(Map map) {
if (map instanceof LinkedHashMap) return (LinkedHashMap) map;
LinkedHashMap m = new LinkedHashMap();
if (map != null) synchronized(collectionMutex(map)) {
m.putAll(map);
}
return m;
}
static int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static int parseInt(char c) {
return Integer.parseInt(str(c));
}
static int boolToInt(boolean b) {
return b ? 1 : 0;
}
static ThreadLocal> holdInstance_l = new ThreadLocal();
static AutoCloseable holdInstance(Object o) {
if (o == null) return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
static Map weakHashMap() {
return newWeakHashMap();
}
static List keysList(Map map) {
return cloneListSynchronizingOn(keys(map), map);
}
static void lockOrFail(Lock lock, long timeout) { try {
ping();
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
ping();
} catch (Exception __e) { throw rethrow(__e); } }
static ReentrantLock fairLock() {
return new ReentrantLock(true);
}
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 boolean isLetterOrDigit(char c) {
return Character.isLetterOrDigit(c);
}
static Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static String getProgramTitle() {
return getProgramName();
}
static A setFrameTitle(A c, final String title) {
final Frame f = getAWTFrame(c);
if (f != null) { swing(new Runnable() { public void run() { try { f.setTitle(title);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.setTitle(title);"; }}); }
return c;
}
static A setFrameTitle(String title, A c) {
return setFrameTitle(c, title);
}
// magically find a field called "frame" in main class :-)
static JFrame setFrameTitle(String title) {
Object f = getOpt(mc(), "frame");
if (f instanceof JFrame)
return setFrameTitle((JFrame) f, title);
return null;
}
static JFrame getFrame(final Object _o) {
return swing(new F0() { public JFrame get() { try {
Object o = _o;
if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JFrame) return (JFrame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; }});
}
static AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
static boolean isInstanceOf(Object o, Class type) {
return type.isInstance(o);
}
static JTextField jTextField() {
return jTextField("");
}
static JTextField jTextField(final String text) {
return swing(new F0() { public JTextField get() { try {
JTextField tf = new JTextField(unnull(text));
standardTextFieldPopupMenu(tf);
jenableUndoRedo(tf);
tf.selectAll();
return tf;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JTextField tf = new JTextField(unnull(text));\r\n standardTextFieldPopupMenu..."; }});
}
static JTextField jTextField(Object o) {
return jTextField(strOrEmpty(o));
}
static String getProgramName_cache;
static String getProgramName() {
Lock __0 = downloadLock(); lock(__0); try {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitleOpt(programID());
return getProgramName_cache;
} finally { unlock(__0); } }
static void _onLoad_getProgramName() {
{ startThread(new Runnable() { public void run() { try { getProgramName();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getProgramName();"; }}); }
}
static JDesktopPane mainDesktopPane_value;
static JDesktopPane mainDesktopPane() {
return mainDesktopPane_value;
}
static JPanel showInternalFrameFormTitled(final JDesktopPane desktop, final String title, final Object... _parts) {
JPanel panel = showForm_makePanel(true, _parts);
showForm_makeInternalFrame(desktop, title, panel);
return panel;
}
static JFrame showForm_makeFrame(String title, JPanel panel) {
return handleEscapeKey(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400));
}
static List showForm_arrange1(List> l) {
int minW = showForm_leftWidth(l);
List out = new ArrayList();
for (List row : l)
out.add(westAndCenter(withRightMargin(showForm_gapBetweenColumns, jMinWidth(minW, first(row))), second(row)));
return out;
}
static List> showForm_makeComponents(final Boolean internalFrame, Object... _parts) {
List> l = new ArrayList();
List parts = asList(_parts);
JButton submitButton = null;
for (int i = 0; i < l(parts); i++) {
final Object o = parts.get(i), next = get(parts, i+1);
if (o instanceof String && next instanceof Component)
setComponentID((Component) next, (String) o);
if (o instanceof Component || o instanceof String || next instanceof Component) { // smartAdd accepts strings
l.add(mapLL("wrapForSmartAdd",
o == null ? new JPanel()
: o instanceof String ? humanizeFormLabel((String) o)
: o, next));
if (next instanceof JButton && submitButton == null)
submitButton = (JButton) next;
i++;
} else if (isRunnable(o))
l.add(mapLL("wrapForSmartAdd",null, submitButton = jbutton(showFormSubmitButtonName(), new Runnable() { public void run() { try {
Object result = call(o);
if (neq(Boolean.FALSE, result)) {
if (isTrue(internalFrame))
disposeInternalFrame(heldInstance(JButton.class));
else if (isFalse(internalFrame))
disposeFrame(heldInstance(JButton.class));
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object result = call(o);\r\n if (neq(Boolean.FALSE, result)) {\r\n ..."; }})));
else print("showForm: Unknown element type: " + getClassName(o));
}
if (submitButton != null) {
final JButton _submitButton = submitButton;
onEnterInAllTextFields(concatLists(l), new Runnable() { public void run() { try { clickButton(_submitButton) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "clickButton(_submitButton)"; }});
}
// massage labels
for (List row : l) {
JComponent left = first(row);
if (left instanceof JLabel) makeBold((JLabel) left).setVerticalAlignment(JLabel.TOP);
}
return l;
}
static int vstackWithSpacing_default = 10;
static JPanel vstackWithSpacing(final List parts) {
return vstackWithSpacing(parts, vstackWithSpacing_default);
}
static JPanel vstackWithSpacing(final List parts, final int spacing) {
return swing(new F0() { public JPanel get() { try {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(spacing/2, 0, spacing/2, 0); // well...
smartAddWithLayout(panel, gbc, toObjectArray(nonNulls(parts)));
//gbc = (GridBagConstraints) gbc.clone();
//gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
gbc.insets = new Insets(0, 0, 0, 0);
panel.add(jrigid(), gbc);
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new GridBagLayout);\r\n new GridBagConstraints gbc..."; }});
}
static JPanel vstackWithSpacing(Component... parts) {
return vstackWithSpacing(asList(parts), vstackWithSpacing_default);
}
static JPanel vstackWithSpacing(int spacing, Component... parts) {
return vstackWithSpacing(asList(parts), spacing);
}
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);
final JButton btn = new JButton(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 final JButton btn = new JButt..."; }});
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret c.getText();"; }});
}
static String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret c.getText();"; }});
}
static String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return l.getText(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret l.getText();"; }});
}
// returns the contents of text field for editable combo box
static String getText(final JComboBox cb) {
if (cb == null) return null;
if (isEditableComboBox(cb))
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
static JButton renameButton(JComponent c, String name) {
JButton b = first(childrenOfType(c, JButton.class));
if (b != null)
b.setText(name);
return b;
}
static JButton renameButton(JComponent c, String oldName, String newName) {
JButton b = findButton(c, oldName);
if (b != null) b.setText(newName);
return b;
}
static String showFormSubmitButtonName() {
return "Submit";
}
static void setCaretPosition(final JTextComponent c, final int pos) {
if (c != null) { swing(new Runnable() { public void run() { try {
try {
int _pos = max(0, min(l(c.getText()), pos));
c.setCaretPosition(_pos);
} catch (Throwable __e) { _handleException(__e); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall {\r\n int _pos = max(0, min(l(c.getText()), pos));\r\n c.setCaret..."; }}); }
}
static int textAreaTextLength(JTextComponent ta) {
return l(getText(ta));
}
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;
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) { throw rethrow(__e); } }
static boolean headless() {
return isHeadless();
}
static void setOpt_raw(Object o, String field, Object value) { try {
if (o == null) return;
if (o instanceof Class) setOpt_raw((Class) o, field, value);
else {
Field f = setOpt_raw_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
smartSet(f, o, value);
}
}
} catch (Exception __e) { throw rethrow(__e); } }
static void setOpt_raw(Class c, String field, Object value) { try {
if (c == null) return;
Field f = setOpt_raw_findStaticField(c, field);
if (f != null) {
makeAccessible(f);
smartSet(f, null, value);
}
} catch (Exception __e) { throw rethrow(__e); } }
static Field setOpt_raw_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Field setOpt_raw_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static A setDyn(A o, String key, Object value) {
if (o == null) return o;
setDynObjectValue(o, key, value);
return o;
}
static JTextField onEnter(final JTextField tf, final Object action) {
if (action == null || tf == null) return tf;
tf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
tf.selectAll();
callF(action);
} catch (Throwable __e) { messageBox(__e); }}});
return tf;
}
static JButton onEnter(JButton btn, final Object action) {
if (action == null || btn == null) return btn;
btn.addActionListener(actionListener(action));
return btn;
}
static JList onEnter(JList list, Object action) {
list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
return list;
}
static JComboBox onEnter(final JComboBox cb, final Object action) {
{ swing(new Runnable() { public void run() { try {
if (cb.isEditable()) {
JTextField text = (JTextField) cb.getEditor().getEditorComponent();
onEnter(text, action);
} else {
cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
cb.getActionMap().put("enter", abstractAction("", new Runnable() { public void run() { try { cb.hidePopup(); callF(action);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.hidePopup(); callF(action);"; }}));
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (cb.isEditable()) {\r\n JTextField text = (JTextField) cb.getEditor().g..."; }}); }
return cb;
}
static JTable onEnter(final JTable table, final Object action) {
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
table.getActionMap().put("Enter", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
callF(action, table.getSelectedRow());
}
});
return table;
}
/*static JTextArea onEnter(final JTextArea ta, fO action) {
addKeyListener(ta, enterKeyListener(action));
ret ta;
}*/
static JTextField onEnter(Object action, JTextField tf) {
return onEnter(tf, action);
}
static String shortClassName(Object o) {
if (o == null) return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
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>> loadBinaryPage_responseHeaders = new ThreadLocal();
static ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal();
static byte[] loadBinaryPage(String url) { try {
print("Loading " + url);
return loadBinaryPage(loadPage_openConnection(new URL(url)));
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] loadBinaryPage(URLConnection con) { try {
Map extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders);
setHeaders(con);
for (String key : keys(extraHeaders))
con.setRequestProperty(key, extraHeaders.get(key));
return loadBinaryPage_noHeaders(con);
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] loadBinaryPage_noHeaders(URLConnection con) { try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
InputStream inputStream = con.getInputStream();
loadBinaryPage_responseHeaders.set(con.getHeaderFields());
long len = 0;
try { len = con.getContentLength/*Long*/(); } catch (Throwable e) { printStackTrace(e); }
int n = 0;
while (true) {
int ch = inputStream.read();
if (ch < 0)
break;
buf.write(ch);
if (++n % 100000 == 0)
println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
}
inputStream.close();
return buf.toByteArray();
} catch (Exception __e) { throw rethrow(__e); } }
/** writes safely (to temp file, then rename) */
public static byte[] saveBinaryFile(String fileName, byte[] contents) { try {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
FileOutputStream fileOutputStream = newFileOutputStream(tempFileName);
fileOutputStream.write(contents);
fileOutputStream.close();
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
vmBus_send("wroteFile", file);
return contents;
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] saveBinaryFile(File fileName, byte[] contents) {
return saveBinaryFile(fileName.getPath(), contents);
}
static File getGlobalCache() {
File file = new File(javaxCachesDir(), "Binary Snippets");
file.mkdirs();
return file;
}
static String dataSnippetLink(String snippetID) {
long id = parseSnippetID(snippetID);
if (id >= 1100000 && id < 1200000)
return imageServerURL() + id;
if (id >= 1200000 && id < 1300000) { // Woody files, actually
String pw = muricaPassword();
if (empty(pw)) throw fail("Please set 'murica password by running #1008829");
return "http://butter.botcompany.de:8080/1008823/raw/" + id + "?_pass=" + pw; // XXX, although it typically gets hidden when printing
}
return fileServerURL() + "/" + id /*+ "?_pass=" + muricaPassword()*/;
}
static String tb_mainServer_default = "http://code.botcompany.de:8081";
static Object tb_mainServer_override; // func -> S
static String tb_mainServer() {
if (tb_mainServer_override != null) return (String) callF(tb_mainServer_override);
return trim(loadTextFile(tb_mainServer_file(),
tb_mainServer_default));
}
static File tb_mainServer_file() {
return getProgramFile("#1001638", "mainserver.txt");
}
static boolean tb_mainServer_isDefault() {
return eq(tb_mainServer(), tb_mainServer_default);
}
static A addAndReturn(Collection c, A a) {
if (c != null) c.add(a);
return a;
}
static void loadBinaryPageToFile(String url, File file) { try {
print("Loading " + url);
loadBinaryPageToFile(openConnection(new URL(url)), file);
} catch (Exception __e) { throw rethrow(__e); } }
static void loadBinaryPageToFile(URLConnection con, File file) { try {
setHeaders(con);
loadBinaryPageToFile_noHeaders(con, file);
} catch (Exception __e) { throw rethrow(__e); } }
static void loadBinaryPageToFile_noHeaders(URLConnection con, File file) { try {
File ftemp = new File(f2s(file) + "_temp");
FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
try {
InputStream inputStream = con.getInputStream();
long len = 0;
try { len = con.getContentLength/*Long*/(); } catch (Throwable e) { printStackTrace(e); }
String pat = " {*}" + (len != 0 ? "/" + len : "") + " bytes loaded.";
copyStreamWithPrints(inputStream, buf, pat);
inputStream.close();
buf.close();
file.delete();
renameFile_assertTrue(ftemp, file);
} finally {
if (buf != null) buf.close();
}
} catch (Exception __e) { throw rethrow(__e); } }
static URLConnection openConnection(String url) { try {
return openConnection(new URL(url));
} catch (Exception __e) { throw rethrow(__e); } }
static URLConnection openConnection(URL url) { try {
ping();
callOpt(javax(), "recordOpenURLConnection", str(url));
return url.openConnection();
} catch (Exception __e) { throw rethrow(__e); } }
static long psI(String snippetID) {
return parseSnippetID(snippetID);
}
static String repeat(char c, int n) {
n = Math.max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++)
chars[i] = c;
return new String(chars);
}
static List repeat(A a, int n) {
n = Math.max(n, 0);
List l = new ArrayList(n);
for (int i = 0; i < n; i++)
l.add(a);
return l;
}
static List repeat(int n, A a) {
return repeat(a, n);
}
static boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null) tl.set(l = new ArrayList());
l.add(a);
}
static A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null) return null;
A a = popLast(l);
if (empty(l)) tl.set(null);
return a;
}
static ArrayList cloneListSynchronizingOn(Collection l, Object mutex) {
if (l == null) return new ArrayList();
synchronized(mutex) {
return new ArrayList (l);
}
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static byte[] bytesFromHex(String s) {
return hexToBytes(s);
}
static boolean byteArrayStartsWith(byte[] a, byte[] b) {
if (a == null || b == null) return false;
if (a.length < b.length) return false;
for (int i = 0; i < b.length; i++)
if (a[i] != b[i])
return false;
return true;
}
static byte[] loadBeginningOfBinaryFile(File file, int maxBytes) {
return loadBinaryFilePart(file, 0, maxBytes);
}
static String defaultThreadName_name;
static String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
// runnable = Runnable or String (method name)
static Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
static Thread newThread(Object runnable, String name) {
if (name == null) name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
static Map _registerThread_threads;
static Object _onRegisterThread; // voidfunc(Thread)
static Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static void _registerThread() { _registerThread(Thread.currentThread()); }
static Frame getAWTFrame(final Object _o) {
return swing(new F0 () { public Frame get() { try {
Object o = _o;
/*
ifdef HaveProcessing
if (o instanceof PApplet) o = ((PApplet) o).getSurface();
endifdef
*/
if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof Frame) return (Frame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "O o = _o;\r\n /*\r\n ifdef HaveProcessing\r\n if (o instanceof PApplet) ..."; }});
}
static JTextField standardTextFieldPopupMenu(final JTextField tf) {
final WeakReference ref = weakRef(tf);
componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(ref.get().getText())
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(ref.get().getText())"; }});
componentPopupMenuItem(tf, "Paste", new Runnable() { public void run() { try { ref.get().paste() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ref.get().paste()"; }});
return tf;
}
static A jenableUndoRedo(final A textcomp) {
{ swing(new Runnable() { public void run() { try {
final UndoManager undo = new UndoManager();
vm_generalWeakSet("Undo Managers").add(undo);
textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() { public void run() { try {
if (undo.canUndo()) undo.undo()
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canUndo()) undo.undo()"; }}));
textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() { public void run() { try {
if (undo.canRedo()) undo.redo()
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canRedo()) undo.redo()"; }}));
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new UndoManager undo;\r\n vm_generalWeakSet(\"Undo Managers\").add(undo)..."; }}); }
return textcomp;
}
static String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static Lock downloadLock_lock = fairLock();
static Lock downloadLock() {
return downloadLock_lock;
}
static String getSnippetTitleOpt(String s) {
return isSnippetID(s) ? getSnippetTitle(s) : s;
}
static JInternalFrame showForm_makeInternalFrame(JDesktopPane desktop, String title, JPanel panel) {
JInternalFrame f = addInternalFrame(desktop, title, withMargin(panel));
minInternalFrameWidth(f, 400);
packInternalFrameVertically(f);
centerInternalFrame(f);
// TODO: handleEscapeKey(f);
return f;
}
static JFrame handleEscapeKey(final JFrame frame) {
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
frame.getRootPane().registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
frame.dispose();
}
}, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
return frame;
}
static JFrame minFrameWidth(JFrame frame, int w) {
if (frame != null && frame.getWidth() < w)
frame.setSize(w, frame.getHeight());
return frame;
}
static JFrame minFrameWidth(int w, JFrame frame) {
return minFrameWidth(frame, w);
}
static JFrame showPackedFrame(String title, Component contents) {
return packFrame(showFrame(title, contents));
}
static JFrame showPackedFrame(Component contents) {
return packFrame(showFrame(contents));
}
static int showForm_leftWidth(List> l) {
int minW = 0;
for (List row : l)
minW = max(minW, getMinimumSize(first(row)).width);
return minW;
}
static JPanel westAndCenter(final Component w, final Component c) {
return swing(new F0() { public JPanel get() { try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.WEST, wrap(w));
panel.add(BorderLayout.CENTER, wrap(c));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST..."; }});
}
static int withRightMargin_defaultWidth = 6;
static JPanel withRightMargin(Component c) {
return withRightMargin(withRightMargin_defaultWidth, c);
}
static JPanel withRightMargin(final int w, final Component c) {
return swing(new F0() { public JPanel get() { try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, w));
p.add(c);
return p;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat..."; }});
}
static