Warning : session_start(): open(/var/lib/php/sessions/sess_2ps8hgh3db8doh6u2a65nm8dg8, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
// formerly: Universal Search Data
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.StringSelection;
import javax.swing.undo.UndoManager;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.text.*;
class main {
static class Actions extends DynTable {
transient Map actions = synchroMap();
void onDoubleClick(Map line) {
AutoCloseable __0 = enter(); try {
callF(mapGet(actions, line));
} finally { _close(__0); }}
List calc() {
List> l = dm_universalSearchData();
actions.clear();
return map(l, new F1, Map>() { Map get(T3 t) { try {
return mapPut_returnKey(actions, litorderedmap("Name" , t.a, "Module" , t.c), t.b);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "mapPut_returnKey(actions, litorderedmap(\"Name\" := t.a, \"Module\" := t.c), t.b)"; }});
}
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static Map> callF_cache = newDangerousWeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Object f, Object... args) { try {
if (f instanceof String)
return callMC((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1) return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
m.setAccessible(true);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(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);
}
}
// triples of (name, action, module ID)
static List> dm_universalSearchData() {
List < T3 < String , Object , String > > out = new ArrayList();
for (Object m : dm_listModules()) { try {
List> result = (List) quickImport(callOpt(m, "uSearchData"));
if (nempty(result)) {
String id = dm_moduleID(m);
for (Pair p : takeFirst(3, result))
out.add(t3(p.a, p.b, id));
}
} catch (Throwable __e) { _handleException(__e); }}
return out;
}
static List map(Iterable l, Object f) { return map(f, l); }
static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null) for (Object o : l)
x.add(callF(f, o));
return x;
}
static List map(Iterable l, F1 f) { return map(f, l); }
static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null) for (Object o : l)
x.add(callF(f, o));
return x;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }
static List map(Object f, Map map) {
return map(map, f);
}
// map: func(key, value) -> list element
static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null) for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o == null) return null;
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
f.setAccessible(true);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(Object o, String field) {
try {
Field f = get_findField(o.getClass(), field);
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_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 get_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 A mapPut_returnKey(Map map, A key, B value) {
mapPut(map, key, value);
return key;
}
static LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
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 matching arguments 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) {
m.setAccessible(true);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(short[] a) { return a == null ? 0 : a.length; }
static int l(long[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(double[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); }
static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o == null ? 0
: o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: o instanceof Collection ? l((Collection) o)
: o instanceof Object[] ? l((Object[]) o)
: o instanceof boolean[] ? l((boolean[]) o)
: o instanceof byte[] ? l((byte[]) o)
: o instanceof char[] ? l((char[]) o)
: o instanceof short[] ? l((short[]) o)
: o instanceof int[] ? l((int[]) o)
: o instanceof float[] ? l((float[]) o)
: o instanceof double[] ? l((double[]) o)
: o instanceof long[] ? l((long[]) o)
: (Integer) call(o, "size");
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static Object invokeMethod(Method m, Object o, Object... args) { try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) { throw rethrow(__e); } }
static boolean call_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 List dm_listModules() {
return callCreator("listModules");
}
static Object quickImport(Object o) {
return quickExport(o, mc());
}
static Object callOpt(Object o) {
return callF(o);
}
static A callOpt(Object o, String method, Object... args) {
return (A) callOpt_cached(o, method, args);
}
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 String dm_moduleID(Object module) {
return strOrNull(getOpt(dm_getStem(module), "id"));
}
static String dm_moduleID() {
return dm_moduleID(dm_current_mandatory());
}
static List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
static List takeFirst(int n, List l) {
return takeFirst(l, n);
}
static String takeFirst(int n, String s) { return substring(s, 0, n); }
static String takeFirst(String s, int n) { return substring(s, 0, n); }
static List takeFirst(int n, Iterable i) {
List l = new ArrayList();
Iterator it = i.iterator();
for (int _repeat_4 = 0; _repeat_4 < n; _repeat_4++) { if (it.hasNext()) l.add(it.next()); else break; }
return l;
}
static T3 t3(A a, B b, C c) {
return new T3(a, b, c);
}
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 ArrayList emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
// Try to match capacity
static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
// get correct type at once
static ArrayList emptyList(Class c) {
return new ArrayList();
}
static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static ArrayList asList(int[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(float[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static ArrayList asList(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null) while ((a = p.next()) != null)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
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 RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null) map.put(key, value);
}
static HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length-1; i += 2)
if (x[i+1] != null)
map.put(x[i], x[i+1]);
}
static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
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 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 List classNames(Collection l) {
return getClassNames(l);
}
static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static Class mc() {
return main.class;
}
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 A call(Object o) {
return (A) callF(o);
}
// varargs assignment fixer for a single string array argument
static A call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static A call(Object o, String method, Object... args) {
return (A) call_cached(o, method, args);
}
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 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 A callCreator(String functionName, Object... args) {
return (A) call(creator(), functionName, args);
}
static Object quickExport(Object o, Object dest) {
return quickExport_impl(o, dest, new IdentityHashMap(), new HashMap());
}
static Object quickExport(Object o, Object dest, int expectedNumberOfObjects) {
return quickExport_impl(o, dest, new IdentityHashMap(expectedNumberOfObjects), new HashMap());
}
/*sclass quickExport_info {
Class destClass;
Field[] fields;
}*/
static Object quickExport_impl(Object o, Object dest, IdentityHashMap seen, HashMap classMap) { try {
if (o == null || o instanceof String || o instanceof Number) return o;
Object oo = seen.get(o);
if (oo != null) return oo;
if (o instanceof Object[]) {
Object[] l = (Object[]) o;
Object[] destO = newObjectArrayOfSameType(l, l.length);
seen.put(o, destO);
for (int i = 0; i < l.length; i++)
destO[i] = quickExport_impl(l[i], dest, seen, classMap);
return destO;
}
if (o instanceof List) {
List l = (List) ( o);
List destO = new ArrayList(l.size());
seen.put(o, destO);
for (int i = 0; i < l.size(); i++)
destO.add(quickExport_impl(l.get(i), dest, seen, classMap));
return destO;
}
if (o instanceof Map) {
Map m = (Map) ( o);
Map destO = new HashMap();
seen.put(o, destO);
for (Object e : ((Map) o).entrySet())
destO.put(
quickExport_impl(((Map.Entry) e).getKey(), dest, seen, classMap),
quickExport_impl(((Map.Entry) e).getValue(), dest, seen, classMap));
return destO;
}
Class c = o.getClass();
String className = c.getName();
if (className.startsWith("main$")) {
Class destClass = classMap.get(c);
if (destClass == null) {
if (!classMap.containsKey(c)) {
if (!isAnonymousClassName(className))
destClass = getClass_vmName(dest, className);
classMap.put(c, destClass);
}
if (destClass == null) return o; // Class not found in target realm, keep object as is
}
if (c == destClass) return o; // no export necessary
// actually make a new object, copy fields
Object destO = nuObjectWithoutArguments(destClass);
seen.put(o, destO);
while (c != Object.class) {
// TODO: cache fields and destination fields
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
field.setAccessible(true);
Object value = field.get(o);
setOpt(destO, field.getName(), quickExport_impl(value, dest, seen, classMap));
}
c = c.getSuperclass();
}
return destO;
}
// assume it's a shared library object
return o;
} catch (Exception __e) { throw rethrow(__e); } }
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 boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(CharSequence s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
if (o instanceof byte[]) return empty((byte[]) o);
if (o == null) return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static boolean empty(byte[] a) { return a == null || a.length == 0; }
static boolean empty(File f) { return getFileSize(f) == 0; }
static String strOrNull(Object o) {
return o == null ? null : str(o);
}
static A getOpt(Object o, String field) {
return (A) 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;
f.setAccessible(true);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
// access of static fields is not yet optimized
static A getOpt(Class c, String field) { try {
if (c == null) return null;
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
f.setAccessible(true);
return (A) 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 Object dm_getStem(Object moduleOrID) {
if (isStringOrIntOrLong(moduleOrID))
return dm_getStemByID(moduleOrID);
return or(getOpt(dm_getModule(moduleOrID), "_host"), moduleOrID);
}
static DynModule dm_current_mandatory() {
return assertNotNull("No module set!", dm_currentModule());
}
static List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
static List newSubListOrSame(List l, int startIndex, int endIndex) {
if (l == null) return null;
startIndex = max(0, startIndex);
endIndex = min(l(l), endIndex);
if (startIndex >= endIndex) return ll();
if (startIndex == 0 && endIndex == l(l)) return l;
return cloneList(l.subList(startIndex, endIndex));
}
static String substring(String s, int x) {
return substring(s, x, l(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 List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || b != null && a.equals(b);
}
static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static ArrayList cloneList(Collection l) {
if (l == null) return new ArrayList();
synchronized(collectionMutex(l)) {
return new ArrayList (l);
}
}
static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static float max(float[] c) {
if (c.length == 0) return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x) x = d;
return x;
}
static Class javax() {
return getJavaX();
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
//static int print_maxLineLength = 0; // 0 = unset
static boolean print_silent; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal print_byThread; // special handling by thread - prefers F1
static volatile Object print_allThreads;
static void print() {
print("");
}
static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
// slightly overblown signature to return original object...
static A print(A o) {
ping_okInCleanUp();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
Object f = print_byThread == null ? null : print_byThread.get();
if (f == null) f = print_allThreads;
if (f != null)
// We do need the general callF machinery here as print_byThread is sometimes shared between modules
if (isFalse(
f instanceof F1 ? ((F1) f).get(s) :
callF(f, s))) return;
print_raw(s);
}
static void print_raw(String s) {
s = fixNewLines(s);
// TODO if (print_maxLineLength != 0)
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
hideCredentials(str(innerException2(e)))) + "\n");
}
static Pair pair(A a, B b) {
return new Pair(a, b);
}
static Pair pair(A a) {
return new Pair(a, a);
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return 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 call_cached(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);
// TODO: (super-rare) case where method exists static and non-static
// with different args
Method me = cache.findMethod(method, args);
if (me == null)
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
if ((me.getModifiers() & Modifier.STATIC) == 0)
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not static");
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me == null)
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
return invokeMethod(me, o, args);
}
} catch (Exception __e) { throw rethrow(__e); } }
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
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 WeakReference creator_class;
static Object creator() {
return creator_class == null ? null : creator_class.get();
}
static A[] newObjectArrayOfSameType(A[] a, int n) {
return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
}
static boolean isAnonymousClassName(String s) {
for (int i = 0; i < l(s); i++)
if (s.charAt(i) == '$' && Character.isDigit(s.charAt(i+1)))
return true;
return false;
}
static Class getClass_vmName(Object realm, String name) { try {
try {
return getClass(realm).getClassLoader().loadClass(name);
} catch (ClassNotFoundException e) {
return null;
}
} 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())) {
m.setAccessible(true);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
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); // possible improvement: skip setAccessible
} 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);
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) {
f.setAccessible(true);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static String getType(Object o) {
return getClassName(o);
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
//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 ((DynamicObject) o).fieldValues.get(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();
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
f.setAccessible(true);
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 boolean isStringOrIntOrLong(Object o) {
return o instanceof String || o instanceof Integer || o instanceof Long;
}
static Object dm_getStemByID(Object id) {
return dm_callOS("getModuleByID", str(id));
}
static A or(A a, A b) {
return a != null ? a : b;
}
static Object dm_getModule(Object moduleOrID) {
if (eq(moduleOrID, "")) return null;
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
static InheritableThreadLocal < WeakReference < DynModule > > dm_currentModule_value = new InheritableThreadLocal();
static DynModule dm_currentModule() {
return getWeakRef(dm_currentModule_value.get());
}
static void _onLoad_dm_currentModule() {
setOptMC("dm_currentModule_generic", dm_currentModule_value);
}
// prevent memory leak
static void cleanMeUp_dm_currentModule() {
dm_currentModule_value = new InheritableThreadLocal();
}
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 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 Object collectionMutex(Object o) {
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
static Class __javax;
static Class getJavaX() { try {
return __javax;
} catch (Exception __e) { throw rethrow(__e); } }
static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1));
}
static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions )
ping_impl(true);
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0) return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i+1 < l && s.charAt(i+1) == '\n') ++i;
}
}
return out.toString();
}
static void print_append(Appendable _buf, String s, int max) { try {
synchronized(_buf) {
_buf.append(s);
if (!(_buf instanceof StringBuilder)) return;
StringBuilder buf = (StringBuilder) ( _buf);
max /= 2;
if (buf.length() > max) 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);
}
}
} catch (Exception __e) { throw rethrow(__e); } }
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }
static String hideCredentials(String url) {
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
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 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 String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix)) return s;
return replacement + substring(s, l(prefix));
}
static Throwable innerException2(Throwable e) {
if (e == null) return null;
while (empty(e.getMessage()) && e.getCause() != null)
e = e.getCause();
return e;
}
static void assertTrue(Object o) {
if (!(eq(o, true) /*|| isTrue(pcallF(o))*/))
throw fail(str(o));
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static String joinWithComma(Collection c) {
return join(", ", c);
}
static String joinWithComma(String... c) {
return join(", ", c);
}
static String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
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 Map classForName_cache = synchroHashMap();
static Class classForName(String name) { try {
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 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) {
f.setAccessible(true);
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) {
f.setAccessible(true);
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 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; }
try {
if (f.getType() == Concept.Ref.class) {
f.set(o, ((Concept) o).new Ref((Concept) value));
return;
}
if (o instanceof Concept.Ref) {
f.set(o, ((Concept.Ref) o).get());
return;
}
} catch (Throwable _e) {}
throw e;
}
}
static void clear(Collection c) {
if (c != null) c.clear();
}
static void put(Map map, A a, B b) {
if (map != null) map.put(a, b);
}
static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static A dm_callOS(String functionName, Object... args) {
return (A) call(dm_os(), functionName, args);
}
static Object dm_resolveModule(Object moduleOrStem) {
return dm_callOS("resolveModule", moduleOrStem);
}
static A getWeakRef(WeakReference ref) {
return ref == null ? null : ref.get();
}
static void setOptMC(String field, Object value) {
setOpt(mc(), field, value);
}
static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static String className(Object o) {
return getClassName(o);
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = newWeakHashMap();
static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions ) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized(ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static int indexOf(List l, A a, int startIndex) {
if (l == null) return -1;
for (int i = startIndex; i < l(l); 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) {
if (x == null) return -1;
for (int i = 0; i < l(x); i++)
if (eq(x[i], a))
return i;
return -1;
}
// 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 boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, char c) {
return nempty(a) && a.charAt(0) == c;
}
static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
m.m = new String[] {substring(a, l(b))};
return true;
}
static boolean startsWith(List a, List b) {
if (a == null || l(b) > l(a)) return false;
for (int i = 0; i < l(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static String classNameToVM(String name) {
return name.replace(".", "$");
}
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 Object dm_os() {
return creator();
}
static Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
// TODO: test if android complains about this
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isAWTThread_awt();
}
static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
if (o instanceof ThreadLocal)
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static Thread currentThread() {
return Thread.currentThread();
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
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 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 volatile boolean licensed_yes = true;
static boolean licensed() {
if (!licensed_yes) return false;
ping_okInCleanUp();
return true;
}
static void licensed_off() {
licensed_yes = false;
}
static void printException(Throwable e) {
printStackTrace(e);
}
static Throwable printStackTrace(Throwable 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));
}
// 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()) {
m.setAccessible(true);
multiMapPut(cache, m.getName(), m);
}
_c = _c.getSuperclass();
}
}
// 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); } }
}static abstract class VF1 {
abstract void get(A a);
}abstract static class DynTable extends DynModule {
transient JTable table;
transient List data;
JComponent visualize() {
table = dataToTable_uneditable(sexyTable(), data = calc());
onDoubleClickOrEnter(table, new VF1() { public void get(Integer row) { try {
Map line = _get(data, row);
if (line != null) onDoubleClick(line);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Map line = _get(data, row);\r\n if (line != null) onDoubleClick(line);"; }});
return table;
}
void unvisualize() { table = null; }
void onDoubleClick(Map line) {}
void update() {
if (table != null) dataToTable_uneditable(table, data = calc());
}
// should cache results if they are expensive to make
abstract List calc();
}
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 abstract class F1 {
abstract B get(A a);
}static abstract class DynModule {
String name, toolTip;
PersistableThrowable _error;
Map> mechLists;
Map _persistenceInfo;
transient Object _host;
transient Map timers = newWeakHashMap(); // all kinds of resources actually; value is closer helper
transient Set _resources = synchroHashSet();
transient Lock lock; // set by stem
transient boolean persistOnChangedField = true;
transient int changeCount;
transient Object changeCountSync = new Object();
transient List onChange;
transient boolean verboseTimers;
transient ReliableSingleThread rstUpdate;
transient Set componentFieldsToKeep;
transient Map transientGeneralMap = synchroHashMap();
transient Q q; // module command queue
DynModule() {
dm_initErrorHandling();
setMainDesktopPane((JDesktopPane) getCreatorOpt("desktop"));
}
boolean isVisible() { return isTrue(getOpt(_host, "visible")); }
String moduleName() { return name; }
void setModuleName(String name) {
String oldName = this.name;
if (!eq(name, oldName)) {
this.name = name;
possiblyInternalFrameTitle(vis(), name);
vmBus_send("moduleNameChange", this, oldName, name);
}
}
void setModuleToolTip(String toolTip) {
this.toolTip = toolTip;
}
JComponent vis() {
return (JComponent) getOpt(_host, "vis");
}
A ownResource(A a) {
if (a != null)
_resources.add(a);
return a;
}
A ownTimer(A timer) {
if (timer instanceof AutoCloseable) ownResource((AutoCloseable) timer);
ownTimer(timer, "cancelTimerOrInterruptThread");
return timer;
}
void ownTimer(Object timer, Object closerHelper) {
timers.put(timer, closerHelper);
}
void singleTimer(java.util.Timer timer) {
stopAllTimers();
ownTimer(timer);
}
void stopAllTimers() {
for (AutoCloseable resource : getAndClearList(_resources)) {
if (verboseTimers)
print("Releasing resource: " + resource);
try { resource.close(); } catch (Throwable __e) { _handleException(__e); }
}
{ final Map __361 = getAndClearMap(timers); for (Object timer : keys( __361)) { Object closerHelper =__361.get(timer);
if (verboseTimers)
print("Stopping timer: " + closerHelper + " / " + timer);
pcallFInRealOrMyMC(this, closerHelper, timer);
}
}}
void cleanMeUp_dynModule() {
stopAllTimers();
}
void persistMe() {
synchronized(changeCountSync) { ++changeCount; }
pcallFAll(onChange); callOpt(_host, "_change");
updateMe();
}
void _change() { persistMe(); }
void change() { persistMe(); }
void updateMe() {
rstUpdate().trigger();
}
void changeAndUpdate() { _change(); updateMe(); }
boolean setField(String name, Object value) { AutoCloseable __364 = enter(); try {
{
// lock lock; // this leads to too many problems
try { // some really weird classes fail on equals() (BCEL JavaClass, I'm looking at you)
if (eq(get(this, name), value)) return false;
} catch (Throwable __e) { _handleException(__e); }
set(this, name, value);
} // releasing lock before calling _change()!
if (persistOnChangedField && !isFalse(mapGet(_persistenceInfo, name)))
_change();
return true;
} finally { _close(__364); }}
A setFieldAndReturn(String name, A value) {
setField(name, value);
return value;
}
boolean setFields(Object... params) {
boolean change = false;
for (int i = 0; i < l(params); i += 2)
if (setField((String) params[i], params[i+1])) change = true;
return change;
}
void start() {}
void revisualize() {
call(creator(), "revisualizeModule", _host);
}
AutoCloseable enter() {
AutoCloseable c = tempSetThreadLocal(dm_currentModule_value, new WeakReference(this));
final Object realMC = getMainClass(this);
if (realMC != mc()) {
c = combineAutoCloseables(tempInterceptPrint(new F1() { Boolean get(String s) { try {
{ call(realMC, "print", s); return false; }
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret false with call(realMC, 'print, s);"; }}), c);
c = combineAutoCloseables(tempSetTL(realMC_tl(), realMC), c);
}
return c;
}
AutoCloseable enterAndLock() {
return combineAutoCloseables(enter(), tempLock(lock));
}
boolean setError(Throwable e) {
setField("_error" , persistableThrowable(e));
return true;
}
void clearError() {
setField("_error" , null);
}
void onChange(Runnable r) {
Lock __362 = lock; lock(__362); try {
if (onChange == null) onChange = synchroList();
addIfNotThere(onChange, r);
} finally { unlock(__362); } }
void onChangeAndNow(Runnable r) {
onChange(r);
callF(r);
}
void update() {}
void unvisualize() {
zeroAllFieldsOfTypeExcept(this, Component.class, componentFieldsToKeep);
}
List menuItems() {
return null;
}
void enhanceFrame(Container f) {
internalFramePopupMenuFromActions_threaded(f, menuItems());
String switchableFields = callOpt(this, "switchableFields");
for (String field : splitAtSpace(switchableFields)) {
Class type = fieldType(this, field);
if (eq(boolean.class, type))
dm_boolFieldMenuItem(f, field);
else if (eq(int.class, type))
dm_intFieldMenuItem(f, field);
else if (eq(double.class, type))
dm_doubleFieldMenuItem(f, field);
}
}
// assume this is called in start(), so no locking
ReliableSingleThread rstUpdate() {
if (rstUpdate == null) rstUpdate = dm_rst(this, new Runnable() { public void run() { try { AutoCloseable __365 = enter(); try { update(); } finally { _close(__365); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __365 = enter(); try { update(); } finally { _close(__365); }"; }});
return rstUpdate;
}
Q q() { AutoCloseable __366 = enter(); try {
if (q == null) {
Lock __363 = lock; lock(__363); try {
if (q == null) q = dm_startQ();
} finally { unlock(__363); } }
return q;
} finally { _close(__366); }}
A withUpdate(A a) {
rstUpdate().trigger();
return a;
}
DynModule module() { return this; }
}
static void _registerTimer(java.util.Timer timer) {
_registerTimer_original(timer);
dm_currentModule().ownTimer(timer);
}
static class T3 {
A a;
B b;
C c;
T3() {}
T3(A a, B b, C c) {
this.c = c;
this.b = b;
this.a = a;}
T3(T3 t) { a = t.a; b = t.b; c = t.c; }
public int hashCode() {
return _hashCode(a) + 2*_hashCode(b) - 4*_hashCode(c);
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof T3)) return false;
T3 t = (T3) o;
return eq(a, t.a) && eq(b, t.b) && eq(c, t.c);
}
public String toString() {
return "(" + quoteBorderless(a) + ", " + quoteBorderless(b) + ", " + quoteBorderless(c) + ")";
}
}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 class Q implements AutoCloseable {
String name = "Unnamed Queue";
List q = synchroLinkedList();
ReliableSingleThread rst = new ReliableSingleThread(new Runnable() { public void run() { try { _run() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_run()"; }});
volatile boolean retired;
Q() {}
Q(String name) {
this.name = name;}
void add(Runnable r) {
q.add(r);
_trigger();
}
void _trigger() {
rst.name = name;
rst.go();
}
void add(Object r) {
add(toRunnable(r));
}
void _run() {
Runnable r;
while (licensed() && !retired && (r = syncPopFirst(q)) != null) {
try { r.run(); } catch (Throwable __e) { _handleException(__e); }
}
}
public void close() { retired = true; } // TODO: interrupt thread
void done() {} // legacy function
boolean isEmpty() { return q.isEmpty(); }
int size() { return q.size(); }
}static class ReliableSingleThread implements Runnable {
Object runnable;
boolean trigger;
Thread thread;
String name = "Single Thread";
F0 enter; // optional ownership marker, e.g. for DynModules
ReliableSingleThread(Object runnable) {
this.runnable = runnable;}
void trigger() { go(); }
synchronized void go() {
trigger = true;
if (!running()) {
AutoCloseable __381 = callF(enter); try {
thread = startThread(name, new Runnable() { public void run() { try { _run();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_run();"; }});
} finally { _close(__381); }}
}
public void run() { go(); }
void get() { go(); } // so you can use the ! syntax
synchronized boolean running() { return thread != null; }
// use only if this is the last time you trigger this
void triggerAndWait() {
trigger();
while (running()) sleep(1);
}
void _run() {
while (licensed()) {
synchronized(this) {
if (!trigger) {
thread = null;
break;
}
trigger = false;
}
pcallF(runnable);
}
}
synchronized void cancel() {
cancelAndInterruptThread(thread);
thread = null;
}
}
static abstract class F0 {
abstract A get();
}
static List myInnerClasses_list=litlist(
"VF1", null, "Derefable", "VF2", "Var", "TokCondition", "IFieldIndex", "talkToThisVM_IO", "Str", "ReliableSingleThread", "DynModule", "FixedRateTimer", "Concept", "Rect", "Pt", "ProgramScan", "Actions", "F0", "F1", "IterableIterator", "F2", "RemoteDB", "MakesBufferedImage", "Flag", "unstructure_Receiver", "ScannedBot", "Concepts", "RC", "XRef", "CloseableIterableIterator", "BaseXRef", "getOpt_Map", "Producer", "structure_Data", "tablePopupMenu_Maker", "IVar", "Cache", "_MethodCache", "talkTo_IO", "Matches", "TableWithTooltips", "LiveValue", "DynTable", "Q", "CriticalAction", "DialogHandler", "T3", "Pair", "DialogIO", "BetterLabel", "componentPopupMenu_Adapter", "MRUCache", "TransferableImage", "DynamicObject", "IConceptIndex", "PersistableThrowable", "talkToSubBot_IO", "Android3", "SmartTimerTask", "Responder");
static List myInnerClasses() {
return myInnerClasses_list;
}
static void cancelTimerOrInterruptThread(Object timer) {
if (timer instanceof Thread && !(timer instanceof AutoCloseable)) // AutoCloseable takes precedence
interruptThread((Thread) timer);
else
cancelTimer(timer);
}
static Method findMethod(Object o, String method, Object... args) {
try {
if (o == null) return null;
if (o instanceof Class) {
Method m = findMethod_static((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m;
} else {
Method m = findMethod_instance(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Method findMethod_static(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (!m.getName().equals(method)) {
if (debug) System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & Modifier.STATIC) == 0 || !findMethod_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method findMethod_instance(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && findMethod_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
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 JTable dataToTable_uneditable(Object data, final JTable table) {
return dataToTable_uneditable(table, data);
}
static JTable dataToTable_uneditable(final JTable table, final Object data) {
{ swing(new Runnable() { public void run() { try {
dataToTable(table, data, true);
makeTableUneditable(table);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "dataToTable(table, data, true);\r\n makeTableUneditable(table);"; }}); }
return table;
}
static JTable dataToTable_uneditable(final Object data) {
return dataToTable_uneditable(showTable(), data);
}
static JTable dataToTable_uneditable(Object data, String title) {
return dataToTable_uneditable(showTable(title), data);
}
static boolean sexyTable_drag = false;
static JTable sexyTable() {
final JTable table = sexyTableWithoutDrag();
if (sexyTable_drag)
tableEnableTextDrag(table); // TODO: seems to interfere with double clicks
return table;
}
static JTable onDoubleClickOrEnter(final JTable table, final Object runnable) {
onDoubleClick(table, runnable);
onEnter(table, runnable);
return table;
}
static JList onDoubleClickOrEnter(final JList list, final Object runnable) {
onDoubleClick(list, runnable);
onEnter(list, runnable);
return list;
}
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 A _get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// runnable can be a func(O o) {} receving the selected item
static JList onDoubleClick(final JList list, final Object runnable) {
{ swing(new Runnable() { public void run() { try {
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2) {
int idx = list.locationToIndex(evt.getPoint());
Object item = list.getModel().getElementAt(idx);
list.setSelectedIndex(idx);
callF(runnable, item);
}
}
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "list.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(Mous..."; }}); }
return list;
}
// runnable can be a func(O o) {} receving the selected row index
static JTable onDoubleClick(final JTable table, final Object runnable) {
{ swing(new Runnable() { public void run() { try {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2) {
int idx = table.rowAtPoint(evt.getPoint());
table.setRowSelectionInterval(idx, idx);
callF(runnable, idx);
}
}
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "table.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(Mou..."; }}); }
return table;
}
// other components get the pointer position
// only reacts on left button
static void onDoubleClick(final JComponent c, final Object runnable) {
{ swing(new Runnable() { public void run() { try {
c.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getButton() == 1 && evt.getClickCount() == 2)
callF(runnable, evt.getPoint());
}
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(MouseEv..."; }}); }
}
static Set synchroHashSet() {
return Collections.synchronizedSet(new HashSet ());
}
static Flag dm_initErrorHandling_flag = new Flag();
static void dm_initErrorHandling() {
raiseFlagAndDo(dm_initErrorHandling_flag, new Runnable() { public void run() { try {
_handleException_addHandler("dm_initErrorHandling_handler");
assertNull(_onRegisterThread);
_onRegisterThread = new VF1() { public void get(Thread t) { try {
DynModule m = dm_currentModule();
if (m == null) printStackTrace("New thread made outside of a module");
else m.ownTimer(t);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "DynModule m = dm_currentModule();\r\n if (m == null) printStackTrace(\"New ..."; }};
_threadInfo_makers.add(new VF1() { public void get(Map map) { try { mapPut(map, "dm_currentModule_value", dm_currentModule()) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "mapPut(map, 'dm_currentModule_value, dm_currentModule())"; }});
_threadInheritInfo_retrievers.add(new VF1() { public void get(Map map) { try {
Object mod = map.get("dm_currentModule_value");
if (mod instanceof DynModule) dm_currentModule_value.set(new WeakReference((DynModule) mod));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "O mod = map.get('dm_currentModule_value);\r\n if (mod instanceof DynModule..."; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_handleException_addHandler(f dm_initErrorHandling_handler);\r\n \r\n asser..."; }});
}
static void dm_initErrorHandling_handler(Throwable e) {
DynModule m = dm_currentModule();
if (m == null)
print("Weird: Error outside of module");
else
m.setField("_error" , persistableThrowable(e));
}
static void setMainDesktopPane(JDesktopPane desktop) {
mainDesktopPane_value = desktop;
}
static A getCreatorOpt(String field) {
return (A) getOpt(creator(), field);
}
static A possiblyInternalFrameTitle(A c, String title) {
JInternalFrame f = getInternalFrame(c);
if (f != null) internalFrameTitle(f, title);
else frameTitle(getFrame(c), title);
return c;
}
static void vmBus_send(String msg, Object... args) {
Object arg = empty(args) ? null
: l(args) == 1 ? args[0]
: 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);
}
static void ownResource(AutoCloseable c) {
_registerAutoCloseable(c);
}
static List getAndClearList(Collection l) {
if (l == null) return emptyList();
synchronized(collectionMutex(l)) {
List out = cloneList(l);
l.clear();
return out;
}
}
static Map getAndClearMap(Map map) {
if (map == null) return emptyMap();
synchronized(collectionMutex(map)) {
Map out = cloneMap(map);
map.clear();
return out;
}
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static Object pcallFInRealOrMyMC(final Object realm, final Object f, final Object... args) {
try { return callFInRealOrMyMC(realm, f, args); } catch (Throwable __e) { _handleException(__e); }
return null;
}
static A pcallFInRealOrMyMC(Object realm, F0 f) { try {
return f == null ? null : f.get();
} catch (Throwable __e) { return null; } }
static B pcallFInRealOrMyMC(Object realm, F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
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 void set(Object o, String field, Object value) {
if (o instanceof Class) set((Class) o, field, value);
else try {
Field f = set_findField(o.getClass(), field);
f.setAccessible(true);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void set(Class c, String field, Object value) {
try {
Field f = set_findStaticField(c, field);
f.setAccessible(true);
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 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 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 AutoCloseable combineAutoCloseables(final AutoCloseable a, final AutoCloseable b) {
return a == null ? b : b == null ? a : new AutoCloseable() { public String toString() { return "a.close(); b.close();"; } public void close() throws Exception { a.close(); b.close(); }};
}
static AutoCloseable combineAutoCloseables(Iterable l) {
return foldl(new F2() { AutoCloseable get(AutoCloseable a, AutoCloseable b) { try { return combineAutoCloseables(a,b); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "combineAutoCloseables(a,b)"; }}, null, l);
}
// f can return false to suppress regular printing
// call print_raw within f to actually print something
static AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static ThreadLocal realMC_tl_tl = new ThreadLocal();
static ThreadLocal realMC_tl() {
return realMC_tl_tl;
}
static AutoCloseable tempLock(final Lock lock) {
if (lock == null) return null;
lock(lock);
return new AutoCloseable() { public String toString() { return "unlock(lock);"; } public void close() throws Exception { unlock(lock); }};
}
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 addIfNotThere(Collection c, A a) {
return setAdd(c, a);
}
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 void onChange(JSpinner spinner, Object r) {
spinner.addChangeListener(changeListener(r));
}
static A onChange(A b, Object r) {
b.addItemListener(itemListener(r));
return b;
}
static void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
static void onChange(final JSlider slider, final Object r) {
{ swing(new Runnable() { public void run() { try {
slider.addChangeListener(changeListener(r));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "slider.addChangeListener(changeListener(r));"; }}); }
}
static void onChange(JComboBox cb, final Object r) {
if (isEditableComboBox(cb))
onChange(textFieldFromComboBox(cb), r);
else
onSelectedItem(cb, new VF1() { public void get(String s) { try { callF(r) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callF(r)"; }});
}
static void zeroAllFieldsOfTypeExcept(Object o, Class type, String... exceptions) {
zeroAllFieldsOfTypeExcept(o, type, asSet(exceptions));
}
static void zeroAllFieldsOfTypeExcept(Object o, Class type, Collection exceptions) {
Set set = asSet(exceptions);
for (String field : allFields(o))
if (!set.contains(field) && instanceOf(getOpt(o, field), type))
set(o, field, null);
}
static void internalFramePopupMenuFromActions_threaded(Container f, List actions) {
if (!(f instanceof JInternalFrame)) return;
for (final AbstractAction a : unnull(actions))
if (a != null)
internalFramePopupMenuItem(((JInternalFrame) f), str(a.getValue(Action.NAME)), runnableThread(new Runnable() { public void run() { try { callAction(a) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callAction(a)"; }}));
}
static List splitAtSpace(String s) {
return empty(s) ? emptyList() : asList(s.split("\\s+"));
}
static Class fieldType(Object o, String field) {
Field f = getField(o, field);
return f == null ? null : f.getType();
}
static void dm_boolFieldMenuItem(Container frame, final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
final String humanized = humanizeFormLabel(field);
internalFrameTitlePopupMenu(((JInternalFrame) frame), new VF1() { public void get(JPopupMenu menu) { try {
menu.add(jCheckBoxMenuItem(humanized, (boolean) _get(m, field), new VF1() { public void get(Boolean b) { try {
m.setField(field, b);
callF(optPar(__, "onSet"));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "m.setField(field, b);\r\n callF(optPar(_, 'onSet));"; }}));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "menu.add(jCheckBoxMenuItem(humanized, (bool) _get(m, field), voidfunc(bool b)..."; }});
}
static void dm_intFieldMenuItem(Container frame, final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
final String humanized = humanizeFormLabel(field);
internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() { public void run() { try {
final JTextField tf = jtextfield(get(m, field));
showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized),
humanized + ":", tf, new Runnable() { public void run() { try {
m.setField(field, parseInt(gtt(tf)));
callF(optPar(__, "onSet"));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, parseInt(gtt(tf)));\r\n callF(optPar(__, \"onSet\"));"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tf = jtextfield(get(m, field));\r\n showFormTitled(or2(stri..."; }});
}
static void dm_doubleFieldMenuItem(Container frame, final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
final String humanized = humanizeFormLabel(field);
internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() { public void run() { try {
final JTextField tf = jtextfield(get(m, field));
showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized),
humanized + ":", tf, new Runnable() { public void run() { try {
m.setField(field, parseDouble(gtt(tf)));
callF(optPar(__, "onSet"));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, parseDouble(gtt(tf)));\r\n callF(optPar(__, \"onSet\"));"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tf = jtextfield(get(m, field));\r\n showFormTitled(or2(stri..."; }});
}
static ReliableSingleThread dm_rst(DynModule mod, Runnable r) {
return dm_rst(mod, new ReliableSingleThread(r));
}
static ReliableSingleThread dm_rst(DynModule mod, ReliableSingleThread rst) {
rst.enter = dm_rEnter(mod);
return rst;
}
static Q dm_startQ() {
Q q = startQ();
q.rst.enter = dm_rEnter(dm_current_mandatory());
dm_ownResource(q);
return q;
}
static Set _registerTimer_list = newWeakHashSet();
static void _registerTimer_original(java.util.Timer timer) {
_registerTimer_list.add(timer);
}
static void cleanMeUp__registerTimer() {
cancelTimers(getAndClearList(_registerTimer_list));
}
static int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static String quoteBorderless(Object o) {
if (o == null) return "null";
return quoteBorderless(str(o));
}
static String quoteBorderless(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder((int) (l(s)*1.5));
quoteBorderless_impl(s, out);
return out.toString();
}
static void quoteBorderless_impl(String s, StringBuilder out) {
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
out.append(c);
}
}
static int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
static List synchroLinkedList() {
return Collections.synchronizedList(new LinkedList ());
}
static Class _run(String progID, String... args) {
Class main = hotwire(progID);
callMain(main, args);
return main;
}
static void add(BitSet bs, int i) {
bs.set(i);
}
static boolean add(Collection c, A a) {
return c != null && c.add(a);
}
static void add(Container c, Component x) {
addToContainer(c, x);
}
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 A syncPopFirst(List l) {
if (empty(l)) return null;
synchronized(l) {
A a = first(l);
l.remove(0);
return a;
}
}
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 volatile boolean sleep_noSleep;
static void sleep(long ms) {
ping();
if (ms < 0) return;
// allow spin locks
if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) { throw new RuntimeException(e); }
}
static void sleep() { try {
if (sleep_noSleep) throw fail("nosleep");
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) { throw rethrow(__e); } }
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 cancelAndInterruptThread(Thread t) {
if (t == null) return;
cancelThread(t);
t.interrupt();
}
static ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
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 List> _threadInheritInfo_retrievers = synchroList();
static void _threadInheritInfo(Object info) {
if (info == null) return;
pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
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 Object _onAWTEnter_f;
static AutoCloseable _onAWTEnter() {
return (AutoCloseable) callF(_onAWTEnter_f);
}
static JDesktopPane mainDesktopPane_value;
static JDesktopPane mainDesktopPane() {
return mainDesktopPane_value;
}
static void interruptThread(Thread t) {
if (t == null) return;
t.interrupt();
URLConnection c = (URLConnection) ( vm_generalSubMap("URLConnection per thread").get(t));
if (c != null) { try {
print("Closing URLConnection of interrupted thread.");
call(c, "disconnect");
} catch (Throwable __e) { _handleException(__e); }}
}
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 Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static JTable dataToTable(Object data) {
return dataToTable(showTable(), data);
}
static JTable dataToTable(Object data, String title) {
return dataToTable(showTable(title), data);
}
static JTable dataToTable(JTable table, Object data) {
return dataToTable(table, data, false);
}
// "now" is ignored now
static JTable dataToTable(JTable table, Object data, boolean now) {
List rows = new ArrayList();
List cols = new ArrayList();
if (data instanceof List) {
for (Object x : (List) data) { try {
rows.add(dataToTable_makeRow(x, cols));
} catch (Throwable __e) { _handleException(__e); }}
} else if (data instanceof Map) {
Map map = (Map) ( data);
for (Object key : map.keySet()) {
Object value = map.get(key);
rows.add(litlist(structureOrTextForUser(key), structureOrTextForUser(value)));
}
} else if (data != null)
print("Unknown data type: " + data);
fillTableWithData(table, rows, cols);
return table;
}
static void makeTableUneditable(JTable table) {
for (int c = 0; c < table.getColumnCount(); c++) {
Class> col_class = table.getColumnClass(c);
//O ed = table.getDefaultEditor(col_class);
//print("Column " + c + " class: " + col_class + " editor: " + ed);
table.setDefaultEditor(col_class, null); // remove editor
}
}
static boolean showTable_searcher = true;
static JTable showTable(Object data) {
return dataToTable_uneditable(data);
}
static JTable showTable(String title, Object data) {
return showTable(data, title);
}
static JTable showTable(Object data, String title) {
return dataToTable_uneditable(data, title);
}
static JTable showTable(JTable table, Object data) {
return showTable(table, data, autoFrameTitle());
}
static JTable showTable(Object data, JTable table) {
return showTable(table, data);
}
static JTable showTable(JTable table, Object data, String title) {
if (table == null)
table = showTable(data, title);
else {
setFrameTitle(table, title);
dataToTable_uneditable(table, data);
}
return table;
}
static JTable showTable() {
return showTable(new ArrayList>(), new ArrayList());
}
static JTable showTable(String title) {
return showTable(new ArrayList>(), new ArrayList(), title);
}
static JTable showTable(List> rows, List cols) {
return showTable(rows, cols, autoFrameTitle());
}
static JTable showTable(List> rows, List cols, String title) {
JTable tbl = sexyTable();
fillTableWithStrings(tbl, rows, cols);
showFrame(title, tbl);
return tbl;
}
static JTable sexyTableWithoutDrag() {
final JTable table = tableWithToolTips();
tablePopupMenu(table, sexyTableWithoutDrag_popupMenuMaker(table));
// Disable Ctrl+PageUp and Ctrl+PageDown
table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
//table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, InputEvent.CTRL_MASK), "none");
/*table.registerKeyboardAction(
null,
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
);*/
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_FOCUSED)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
((InputMap) UIManager.get("Table.ancestorInputMap")).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
return table;
}
static VF2 sexyTableWithoutDrag_popupMenuMaker(JTable t) {
final WeakReference ref = weakRef(t);
return new VF2() { public void get(JPopupMenu menu, Integer row) { try {
final JTable table = ref.get();
final String item = first(getTableLine(table, row));
MouseEvent e = tablePopupMenu_mouseEvent.get();
final int col = table.columnAtPoint(e.getPoint());
final Object value = table.getModel().getValueAt(row, col);
//print("Cell type: " + getClassName(value));
if (value instanceof ImageIcon) {
addMenuItem(menu, "Copy image to clipboard", new Runnable() { public void run() { try {
copyImageToClipboard(((ImageIcon) value).getImage());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyImageToClipboard(((ImageIcon) value).getImage());"; }});
} else {
final String text = str(value);
addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(text);
print("Copied text to clipboard: " + quote(text));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(text);\r\n print(\"Copied text to clipboard: \" + quot..."; }});
}
addMenuItem(menu, "Set row height...", new Runnable() { public void run() { try {
final JTextField tf = jTextField(table.getRowHeight());
showTitledForm("Set row height",
"Pixels", tf, new Runnable() { public void run() { try {
table.setRowHeight(parseInt(trim(tf.getText())))
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "table.setRowHeight(parseInt(trim(tf.getText())))"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tf = jTextField(table.getRowHeight());\r\n showTitledForm..."; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final JTable table = ref!;\r\n final S item = first(getTableLine(table, row)..."; }};
}
static void tableEnableTextDrag(final JTable table) {
TransferHandler th = new TransferHandler() {
@Override
public int getSourceActions(JComponent c) { return COPY; }
@Override
protected Transferable createTransferable(JComponent c) {
//print("Row/Column: " + table.getSelectedRow() + " / " + table.getSelectedColumn());
Object o = selectedTableCell(table);
//print("Value: " + o);
return new StringSelection(str(o));
}
};
tableEnableDrag(table, th);
}
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 void raiseFlagAndDo(Flag flag, Runnable r) {
if (flag.raise()) callF(r);
}
static void _handleException_addHandler(Object handler) {
addIfNotThere(_handleException_onException, handler);
}
static A assertNull(A a) {
assertTrue(a == null);
return a;
}
static A assertNull(String msg, A a) {
assertTrue(msg, a == null);
return a;
}
static JInternalFrame getInternalFrame(final Object _o) {
return _o == null ? null : swing(new F0() { 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 A internalFrameTitle(A c, final String title) {
final JInternalFrame f = getInternalFrame(c);
if (f != null) { swing(new Runnable() { public void run() { try {
f.setTitle(unnull(title));
toolTip(getInternalFrameTitlePaneComponent(f), title);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.setTitle(unnull(title));\r\n toolTip(getInternalFrameTitlePaneComponent(f)..."; }}); }
return c;
}
static A internalFrameTitle(String title, A c) {
return internalFrameTitle(c, title);
}
static String internalFrameTitle(Component c) {
final JInternalFrame f = getInternalFrame(c);
return f == null ? null : swing(new F0() { String get() { try { return f.getTitle(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret f.getTitle();"; }});
}
static A frameTitle(A c, String title) {
return setFrameTitle(c, title);
}
static A frameTitle(String title, A c) {
return setFrameTitle(c, title);
}
static String frameTitle(Component c) {
return getFrameTitle(c);
}
static JFrame getFrame(final Object _o) {
return swing(new F0() { 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 Cache vm_busListeners_live_cache = new Cache("vm_busListeners_live_load");
static Set vm_busListeners_live() { return vm_busListeners_live_cache.get(); }
static Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static Cache> vm_busListenersByMessage_live_cache = new Cache("vm_busListenersByMessage_live_load");
static Map vm_busListenersByMessage_live() { return vm_busListenersByMessage_live_cache.get(); }
static Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static Set _registerAutoCloseable_set = synchroHashSet();
static void _registerAutoCloseable(AutoCloseable c) {
addIfNotNull(_registerAutoCloseable_set, c);
}
static void cleanMeUp__registerAutoCloseable() {
closeAutoCloseables(getAndClearList(_registerAutoCloseable_set));
}
static Map emptyMap() {
return new HashMap();
}
static Map cloneMap(Map map) {
if (map == null) return new HashMap();
// assume mutex is equal to collection
synchronized(map) {
return map instanceof TreeMap ? new TreeMap((TreeMap) map) // copies comparator
: map instanceof LinkedHashMap ? new LinkedHashMap(map)
: new HashMap(map);
}
}
static A callFInRealOrMyMC(Object realm, F0 f) {
return f == null ? null : f.get();
}
static B callFInRealOrMyMC(Object realm, F1 f, A a) {
return f == null ? null : f.get(a);
}
static C callFInRealOrMyMC(Object realm, F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callFInRealOrMyMC(Object realm, VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callFInRealOrMyMC(Object realm, Object f, Object... args) {
if (f instanceof String) {
Class mc = getMainClass(realm);
if (hasMethod(mc, ((String) f), args))
return call(mc, ((String) f), args);
}
return callF(f, args);
}
static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null) return null;
A old = tl.get();
tl.set(value);
return old;
}
static A foldl(F2 f, A seed, Iterable l) {
A a = seed;
if (l != null) for(B b : l)
a = callF(f, a, b);
return a;
}
static ThreadLocal print_byThread() {
synchronized(print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
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 boolean setAdd(Collection c, A a) {
if (c == null || c.contains(a)) return false;
c.add(a);
return true;
}
static ChangeListener changeListener(final Object r) {
return new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(r);
}
};
}
static ItemListener itemListener(final Object r) {
return new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pcallF(r);
}
};
}
// action = runnable or method name
static void onUpdate(JComponent c, final Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
call(r);
}
public void removeUpdate(DocumentEvent e) {
call(r);
}
public void changedUpdate(DocumentEvent e) {
call(r);
}
});
else if (c instanceof ItemSelectable) // JCheckBox and others
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
call(r);
}
});
else
print("Warning: onUpdate doesn't know " + getClassName(c));
}
static void onUpdate(List extends JComponent> l, Object r) {
for (JComponent c : l)
onUpdate(c, r);
}
static boolean isEditableComboBox(final JComboBox cb) {
return cb != null && swing(new F0() { Boolean get() { try { return cb.isEditable(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret cb.isEditable();"; }});
}
static JTextField textFieldFromComboBox(JComboBox cb) {
return (JTextField) cb.getEditor().getEditorComponent();
}
static JComboBox onSelectedItem(final JComboBox cb, final VF1 f) {
addActionListener(cb, new Runnable() { public void run() { try {
pcallF(f, selectedItem(cb))
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(f, selectedItem(cb))"; }});
return cb;
}
static Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array)
if (o != null)
set.add(o);
return set;
}
static Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array)
if (o != null)
set.add(o);
return set;
}
static Set asSet(Iterable l) {
if (l instanceof Set) return (Set) l;
HashSet set = new HashSet();
for (A o : unnull(l))
if (o != null)
set.add(o);
return set;
}
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 boolean instanceOf(Object o, String className) {
if (o == null) return false;
String c = o.getClass().getName();
return eq(c, className) || eq(c, "main$" + className);
}
static boolean instanceOf(Object o, Class c) {
if (c == null) return false;
return c.isInstance(o);
}
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 void internalFramePopupMenuItem(Container f, final String name, final Object action) {
internalFrameTitlePopupMenuItem(((JInternalFrame) f), name, action);
}
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 void callAction(Action a) {
if (a != null) a.actionPerformed(null);
}
static Field getField(Object o, String field) {
if (o == null) return null;
return setOpt_findField(_getClass(o), field);
}
static Map humanizeFormLabel_replacements = litmap("id" , "ID", "md5" , "MD5");
static String humanizeFormLabel(String s) {
if (containsSpace(s)) return s;
return firstToUpper(
joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID")
);
}
// menuMaker = voidfunc(JPopupMenu)
static void internalFrameTitlePopupMenu(final JInternalFrame f, final Object... params) {
{ swing(new Runnable() { public void run() { try {
Object menuMaker;
if (l(params) == 1)
menuMaker = params[0];
else
menuMaker = new VF1() { public void get(JPopupMenu menu) { try { addMenuItems(menu, params) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "addMenuItems(menu, params)"; }};
Component titleComponent = getInternalFrameTitlePaneComponent(f);
if (!(titleComponent instanceof JComponent))
print("Can't add internal frame title popup menu!");
else
componentPopupMenu((JComponent) titleComponent, menuMaker);
// Also add to the frame so we can show the items e.g. in a JFrame menu
componentPopupMenu(f, menuMaker);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object menuMaker;\r\n if (l(params) == 1)\r\n menuMaker = params[0];\r\n ..."; }}); }
}
// r : runnable or voidfunc(bool)
static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
final JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked);
addActionListener(mi, new Runnable() { public void run() { try { callF(r, isChecked(mi)) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(r, isChecked(mi))"; }});
return mi;
}
static A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
static A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
static A optPar(Object[] params, String name) {
return optParam(params, name);
}
static A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
static JTextField jtextfield() {
return jTextField();
}
static JTextField jtextfield(String text) {
return jTextField(text);
}
static JTextField jtextfield(Object o) {
return jTextField(o);
}
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() { 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 String or2(String a, String b) {
return nempty(a) ? a : b;
}
static String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
static String stringOptPar(Object[] params, String name) {
return optPar(params, name);
}
static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
static int parseInt(char c) {
return Integer.parseInt(str(c));
}
static String gtt(JTextComponent c) {
return getTextTrim(c);
}
static String gtt(JComboBox cb) {
return getTextTrim(cb);
}
static double parseDouble(String s) {
return Double.parseDouble(s);
}
static F0 dm_rEnter(final DynModule mod) {
return mod == null ? null : new F0() { AutoCloseable get() { try { return mod.enter(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret mod.enter();"; }};
}
static Q startQ() {
return new Q();
}
static Q startQ(String name) {
return new Q(name);
}
static AutoCloseable dm_ownResource(AutoCloseable resource) {
dm_currentModuleMandatory().ownResource(resource);
return resource;
}
static Set newWeakHashSet() {
return synchroWeakHashSet();
}
static void cancelTimers(Collection timers) {
for (Object timer : timers) cancelTimer(timer);
}
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 A callMain(A c, String... args) {
callOpt(c, "main", new Object[] {args});
return c;
}
static void callMain() {
callMain(mc());
}
static void addToContainer(final Container a, final Component b) {
if (a != null && b != null) { swing(new Runnable() { public void run() { try { a.add(b);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.add(b);"; }}); }
}
static Object first(Object list) {
return first((Iterable) list);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(IterableIterator i) {
return first((Iterator ) i);
}
static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static A first(T3 t) {
return t == null ? null : t.a;
}
static String defaultThreadName_name;
static String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
// 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 Object sleepQuietly_monitor = new Object();
static void sleepQuietly() { try {
assertFalse(isAWTThread());
synchronized(sleepQuietly_monitor) { sleepQuietly_monitor.wait(); }
} catch (Exception __e) { throw rethrow(__e); } }
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
return null;
}
static void cancelThread(Thread t) {
if (t == null) return;
ping();
/*O mc = getWeakRef((WeakReference) vm_generalWeakSubMap("thread2mc").get(t));
ifdef cancelThread_verbose
print("cancelThread: mc=" + mc);
endifdef
if (mc != null) {
Map ping_actions = cast get(mc, 'ping_actions);
synchronized(ping_actions) {
ping_actions.put(t, "cancelled");
set(mc, ping_anyActions := true);
}
} else*/ synchronized(ping_actions) {
ping_actions.put(t, "cancelled");
ping_anyActions = true;
}
}
static Map vm_generalWeakSubMap(Object name) {
synchronized(get(javax(), "generalMap")) {
Map map = (Map) ( vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = newWeakMap());
return map;
}
}
static WeakReference weakRef(A a) {
return newWeakReference(a);
}
static Map vm_generalSubMap(Object name) {
synchronized(get(javax(), "generalMap")) {
Map map = (Map) ( vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = synchroMap());
return map;
}
}
static void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) { throw rethrow(__e); } }
static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() { public void run() { try {
result.set(callF(f));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; }});
return result.get();
}
}
static void dataToTable_dynSet(List l, int i, Object s) {
while (i >= l.size()) l.add("");
l.set(i, s);
}
static List dataToTable_makeRow(Object x, List cols) {
if (instanceOf(x, "DynamicObject"))
x = get_raw(x, "fieldValues");
if (x instanceof Map) {
Map m = (Map) ( x);
List row = new ArrayList();
for (Object _field : keysWithoutHidden(m)) {
String field = (String) ( _field);
Object value = m.get(field);
int col = cols.indexOf(field);
if (col < 0) {
cols.add(field);
col = cols.size()-1;
}
dataToTable_dynSet(row, col, dataToTable_wrapValue(value));
}
return row;
}
return litlist(structureOrText(x));
}
static Object dataToTable_wrapValue(Object o) {
if (o instanceof BufferedImage) return o;
if (o instanceof MakesBufferedImage) return ((MakesBufferedImage) o).getBufferedImage();
if (o instanceof Boolean) return o;
return structureOrTextForUser(o);
}
static String structureOrTextForUser(Object o) {
return o instanceof String ? (String) o : structureForUser(o);
}
static void fillTableWithData(final JTable table, List rows, List colNames) {
fillTableWithData(table, rows, toStringArray(colNames));
}
// thread-safe
static void fillTableWithData(final JTable table, List rows, String... colNames) {
final DefaultTableModel model = fillTableWithData_makeModel(rows, colNames);
// TODO: keep model if columns identical?
setTableModel(table, model);
}
static DefaultTableModel fillTableWithData_makeModel(List rows, String... colNames) {
Pair p = fillTableWithData_makeData(rows, colNames);
return new DefaultTableModel(p.a, p.b) {
public Class getColumnClass(int column) {
return or(_getClass(getValueAt(0, column)), String.class);
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
};
}
static String autoFrameTitle_value;
static String autoFrameTitle() {
return autoFrameTitle_value != null ? autoFrameTitle_value : getProgramTitle();
}
static void autoFrameTitle(Component c) {
setFrameTitle(getFrame(c), autoFrameTitle());
}
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 void fillTableWithStrings(final JTable table, List> rows, List colNames) {
fillTableWithStrings(table, rows, toStringArray(colNames));
}
// thread-safe
static void fillTableWithStrings(final JTable table, List> rows, String... colNames) {
final DefaultTableModel model = fillTableWithStrings_makeModel(rows, colNames);
swingNowOrLater(new Runnable() { public void run() { try {
setTableModel(table, model);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setTableModel(table, model);"; }});
}
static DefaultTableModel fillTableWithStrings_makeModel(List> rows, String... colNames) {
Object[][] data = new Object[rows.size()][];
int w = 0;
for (int i = 0; i < rows.size(); i++) {
List l = rows.get(i);
Object[] r = new Object[l.size()];
for (int j = 0; j < l.size(); j++)
r[j] = l.get(j);
data[i] = r;
w = Math.max(w, l.size());
}
Object[] columnNames = new Object[w];
for (int i = 0; i < w; i++)
columnNames[i] = i < l(colNames) ? colNames[i] : "?";
return new DefaultTableModel(data, columnNames);
}
static JFrame showFrame() {
return makeFrame();
}
static JFrame showFrame(Object content) {
return makeFrame(content);
}
static JFrame showFrame(String title) {
return makeFrame(title);
}
static JFrame showFrame(String title, Object content) {
return makeFrame(title, content);
}
static JFrame showFrame(final JFrame f) {
if (f != null) { swing(new Runnable() { public void run() { try {
if (frameTooSmall(f)) frameStandardSize(f);
if (!f.isVisible()) f.setVisible(true); // XXX
if (f.getState() == Frame.ICONIFIED) f.setState(Frame.NORMAL);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (frameTooSmall(f)) frameStandardSize(f);\r\n if (!f.isVisible()) f.setVis..."; }}); }
return f;
}
// make or update frame
static JFrame showFrame(String title, Object content, JFrame frame) {
if (frame == null)
return showFrame(title, content);
else {
frame.setTitle(title);
setFrameContents(frame, content);
return frame;
}
}
static TableWithTooltips tableWithToolTips() {
return tableWithTooltips();
}
static class tablePopupMenu_Maker {
List menuMakers = new ArrayList();
}
static Map tablePopupMenu_map = newWeakHashMap();
static ThreadLocal tablePopupMenu_mouseEvent = new ThreadLocal();
static ThreadLocal tablePopupMenu_first = new ThreadLocal();
// menuMaker = voidfunc(JPopupMenu, int row)
static void tablePopupMenu(final JTable table, final Object menuMaker) {
final boolean first = isTrue(getAndClearThreadLocal(tablePopupMenu_first));
{ swing(new Runnable() { public void run() { try {
tablePopupMenu_Maker maker = tablePopupMenu_map.get(table);
if (maker == null) {
tablePopupMenu_map.put(table, maker = new tablePopupMenu_Maker());
final tablePopupMenu_Maker _maker = maker;
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) { displayMenu(e); }
public void mouseReleased(MouseEvent e) { displayMenu(e); }
void displayMenu(MouseEvent e) {
if (!e.isPopupTrigger()) return;
JPopupMenu menu = new JPopupMenu();
int row = table.rowAtPoint(e.getPoint());
if (table.getSelectedRowCount() < 2)
table.setRowSelectionInterval(row, row);
int modelRow = convertTableRowToModel(table, row);
int emptyCount = menu.getComponentCount();
tablePopupMenu_mouseEvent.set(e);
for (Object menuMaker : _maker.menuMakers)
pcallF(menuMaker, menu, modelRow);
vmBus_send("showingPopupMenu", table, menu);
// show menu if any items in it
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
if (first)
maker.menuMakers.add(0, menuMaker);
else
maker.menuMakers.add(menuMaker);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tablePopupMenu_Maker maker = tablePopupMenu_map.get(table);\r\n if (maker ==..."; }}); }
}
static List getTableLine(JTable tbl, int row) {
if (row >= 0 && row < tbl.getModel().getRowCount()) {
List l = new ArrayList();
for (int i = 0; i < tbl.getModel().getColumnCount(); i++)
l.add(String.valueOf(tbl.getModel().getValueAt(row, i)));
return l;
}
return null;
}
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 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 String copyTextToClipboard(String text) {
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
vmBus_send("newClipboardContents", text);
return text;
}
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 JTextField jTextField() {
return jTextField("");
}
static JTextField jTextField(final String text) {
return swing(new F0() { 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 JComponent showTitledForm(String title, Object... _parts) {
return showFormTitled(title, _parts);
}
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 Object selectedTableCell(JTable t, int col) {
return getTableCell(t, selectedTableRow(t), col);
}
static Object selectedTableCell(final JTable t) {
return swing(new F0() { Object get() { try { return selectedTableCell(t, t.getSelectedColumn()); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret selectedTableCell(t, t.getSelectedColumn());"; }});
}
static Object selectedTableCell(final JTable t, final String colName) {
return swing(new F0() { Object get() { try { return selectedTableCell(t, tableColumnViewIndex(t, colName)); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret selectedTableCell(t, tableColumnViewIndex(t, colName));"; }});
}
static void tableEnableDrag(final JTable table, TransferHandler th) {
if (table.getDragEnabled()) {
print("Table drag already enabled");
return;
}
table.setDragEnabled(true);
table.setTransferHandler(th);
table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == 1 && e.getClickCount() == 1)
table.getTransferHandler().exportAsDrag(table, e, TransferHandler.COPY);
}
});
}
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 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 __71 = holdInstance(instanceToHold); try {
callF(runnable);
} finally { _close(__71); }} catch (Throwable __e) { messageBox(__e); }}};
}
static KeyListener enterKeyListener(final Object action) {
return new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER)
pcallF(action);
}
};
}
static Runnable rCallOnSelectedListItem(final JList list, final Object action) {
return new Runnable() { public void run() { try { pcallF(action, getSelectedItem(list)) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, getSelectedItem(list))"; }};
}
static AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
static A toolTip(A c, final Object toolTip) {
return setToolTipText(c, toolTip);
}
static A toolTip(Object toolTip, A c) {
return setToolTipText(toolTip, c);
}
static JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) {
return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane");
}
static String getFrameTitle(Component c) {
JFrame f = getFrame(c);
return f == null ? null : f.getTitle();
}
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 void addIfNotNull(Collection l, A a) {
if (a != null && l != null) l.add(a);
}
static void closeAutoCloseables(Collection l) {
if (l != null) for (AutoCloseable c : l) { try { c.close(); } catch (Throwable __e) { _handleException(__e); }}
}
static boolean hasMethod(Object o, String method, Object... args) {
return findMethod(o, method, args) != null;
}
static void addActionListener(JTextField tf, final Runnable action) {
onEnter(tf, action);
}
static void addActionListener(final JComboBox cb, final Runnable action) {
if (cb != null) { swing(new Runnable() { public void run() { try {
cb.addActionListener(actionListener(action));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.addActionListener(actionListener(action));"; }}); }
}
static void addActionListener(final AbstractButton b, final Runnable action) {
if (b != null) { swing(new Runnable() { public void run() { try {
b.addActionListener(actionListener(action));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "b.addActionListener(actionListener(action));"; }}); }
}
static String selectedItem(JList l) {
return getSelectedItem(l);
}
static String selectedItem(JComboBox cb) {
return getSelectedItem(cb);
}
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 void internalFrameTitlePopupMenuItem(JInternalFrame f, final String name, final Object action) {
internalFrameTitlePopupMenu(f, new VF1() { public void get(JPopupMenu menu) { try {
addMenuItem(menu, name, action)
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "addMenuItem(menu, name, action)"; }});
}
static boolean containsSpace(String s) {
return containsSpaces(s);
}
static String firstToUpper(String s) {
if (empty(s)) return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
static List replaceElementsUsingMap(Iterable l, final Map map) {
return map(l, new F1 () { A get(A a) { try { return getOrKeep(map, a); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "getOrKeep(map, a)"; }});
}
static List splitCamelCase(String s) {
return ai_splitCamelCase(s);
}
static void addMenuItems(JMenu m, Object... x) {
fillJMenu(m, x);
}
static void addMenuItems(JPopupMenu m, Object... x) {
fillJPopupMenu(m, x);
}
// TODO: get rid of map (just look for adapter in listeners)
static Map componentPopupMenu_map;
static ThreadLocal componentPopupMenu_mouseEvent;
static void componentPopupMenu_init() {
{ swing(new Runnable() { public void run() { try {
if (componentPopupMenu_map == null)
componentPopupMenu_map = or((Map) getOpt(creator(), "componentPopupMenu_map"), (Map) (Map) newWeakHashMap());
if (componentPopupMenu_mouseEvent == null)
componentPopupMenu_mouseEvent = or((ThreadLocal) getOpt(creator(), "componentPopupMenu_mouseEvent"), new ThreadLocal());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (componentPopupMenu_map == null)\r\n componentPopupMenu_map = or((Map() { Boolean get() { try { return checkBox.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret checkBox.isSelected();"; }});
}
static boolean isChecked(final JCheckBoxMenuItem mi) {
return mi != null && (boolean) swing(new F0() { Boolean get() { try { return mi.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret mi.isSelected();"; }});
}
static A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static A optParam(ThreadLocal tl) {
return optPar(tl);
}
static A optParam(Object[] opt, String name, A defaultValue) {
if (!even(l(opt))) throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2)
if (eq(opt[i], name))
return (A) opt[i+1];
return defaultValue;
}
static A optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
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 < List < JComponent > > 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() { 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(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 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 DynModule dm_currentModuleMandatory() {
return dm_current_mandatory();
}
static Set synchroWeakHashSet() {
return Collections.newSetFromMap((Map) newWeakHashMap());
}
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 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 String programID() {
return getProgramID();
}
static String programID(Object o) {
return getProgramID(o);
}
static Runnable _topLevelErrorHandling(final Runnable runnable) {
final Object info = _threadInfo();
return new Runnable() { public void run() { try {
try {
_threadInheritInfo(info);
runnable.run();
} catch (Throwable __e) { _handleException(__e); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }"; }};
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static A vm_generalMap_get(Object key) {
return (A) vm_generalMap().get(key);
}
static Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static Map newWeakMap() {
return newWeakHashMap();
}
static WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
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 List keysWithoutHidden(Map map) {
return filter(keys(map) , new F1() { Boolean get(Object o) { try { return !eq(o, "[hidden]") && !isStringStartingWith(o, "[hidden] "); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "!eq(o, \"[hidden]\") && !isStringStartingWith(o, \"[hidden] \")"; }});
}
static String structureOrText(Object o) {
return o instanceof String ? (String) o : structure(o);
}
static String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
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 Map> setTableModel_after = weakHashMap();
static Map> setTableModel_fixSorter = weakHashMap();
static void setTableModel(final JTable table, final TableModel model) {
{ swing(new Runnable() { public void run() { try {
Map widths = tableColumnWidthsByName(table);
int[] i = table.getSelectedRows();
TableRowSorter sorter = model.getColumnCount() == tableColumnCount(table) ? (TableRowSorter) table.getRowSorter() : null;
List extends RowSorter.SortKey> sortKeys = sorter == null ? null : sorter.getSortKeys();
table.setModel(model);
int n = model.getRowCount();
ListSelectionModel sel = table.getSelectionModel();
for (int j = 0; j < i.length; j++)
if (i[j] < n)
sel.addSelectionInterval(i[j], i[j]);
tableSetColumnPreferredWidths(table, widths);
if (sorter != null) {
sorter.setModel(model);
callF(setTableModel_fixSorter.get(table), table, sorter);
//print("Keeping sorter: " + sorter + " Sort keys: " + sortKeys);
if (sortKeys != null) sorter.setSortKeys(sortKeys);
}
table.setRowSorter(sorter);
callF(setTableModel_after.get(table), table);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Map widths = tableColumnWidthsByName(table);\r\n int[] i = ..."; }}); }
}
static Pair fillTableWithData_makeData(List rows, List colNames) {
return fillTableWithData_makeData(rows, asStringArray(colNames));
}
static Pair fillTableWithData_makeData(List rows, String... colNames) {
Object[][] data = new Object[rows.size()][];
int w = 0;
for (int i = 0; i < rows.size(); i++) {
List l = rows.get(i);
Object[] r = new Object[l.size()];
for (int j = 0; j < l.size(); j++) {
Object o = l.get(j);
if (o instanceof BufferedImage) o = imageIcon((BufferedImage) o);
r[j] = o;
}
data[i] = r;
w = Math.max(w, l.size());
}
Object[] columnNames = new Object[w];
for (int i = 0; i < w; i++)
columnNames[i] = i < l(colNames) ? colNames[i] : "?";
return pair(data, columnNames);
}
static String getProgramTitle() {
return getProgramName();
}
static Frame getAWTFrame(final Object _o) {
return swing(new F0 () { 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 void swingNowOrLater(Runnable r) {
if (isAWTThread())
r.run();
else
swingLater(r);
}
static String makeFrame_defaultIcon;
static boolean makeFrame_hideConsole;
static ThreadLocal < VF1 < JFrame > > makeFrame_post = new ThreadLocal();
static JFrame makeFrame() {
return makeFrame((Component) null);
}
static JFrame makeFrame(Object content) {
return makeFrame(programTitle(), content);
}
static JFrame makeFrame(String title) {
return makeFrame(title, null);
}
static JFrame makeFrame(String title, Object content) {
return makeFrame(title, content, true);
}
static JFrame makeFrame(final String title, final Object content, final boolean showIt) {
final VF1 post = optParam(makeFrame_post);
return swing(new F0() { JFrame get() { try {
if (getFrame(content) != null)
return getFrame(setFrameTitle((Component) content, title));
final JFrame frame = new JFrame(title);
if (makeFrame_defaultIcon != null)
setFrameIconLater(frame, makeFrame_defaultIcon);
_initFrame(frame);
Component wrapped = wrap(content);
if (wrapped != null)
frame.getContentPane().add(wrapped);
frame.setBounds(defaultNewFrameBounds());
callF(post, frame);
if (showIt)
frame.setVisible(true);
//callOpt(content, "requestFocus");
//exitOnFrameClose(frame);
if (showIt && makeFrame_hideConsole) {
hideConsole();
makeFrame_hideConsole = false;
}
return frame;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (getFrame(content) != null)\r\n ret getFrame(setFrameTitle((Component) ..."; }});
}
static boolean frameTooSmall(JFrame frame) {
return frame.getWidth() < 100 || frame.getHeight() < 50;
}
static void frameStandardSize(JFrame frame) {
frame.setBounds(300, 100, 500, 400);
}
static void setFrameContents(final Component c, final Object contents) {
{ swing(new Runnable() { public void run() { try {
JFrame frame = getFrame(c);
frame.getContentPane().removeAll();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrap(contents));
revalidate(frame);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFrame frame = getFrame(c);\r\n frame.getContentPane().removeAll();\r\n fra..."; }}); }
}
static TableWithTooltips tableWithTooltips() {
return (TableWithTooltips) swing(new F0() { Object get() { try { return new TableWithTooltips(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret new TableWithTooltips;"; }});
}
static class TableWithTooltips extends JTable {
public String getToolTipText(MouseEvent e) {
String tip = null;
Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
try {
return str(getValueAt(rowIndex, colIndex));
} catch (Throwable _e) {
return null;
}
}
}
static A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
static int convertTableRowToModel(final JTable t, final int viewRow) {
return t == null || viewRow < 0 ? -1 : swing(new F0() { Integer get() { try {
return t.convertRowIndexToModel(viewRow);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret t.convertRowIndexToModel(viewRow);"; }});
}
static boolean jmenuItem_newThreads;
static JMenuItem jmenuItem(final String text) {
return jMenuItem(text, null);
}
static JMenuItem jmenuItem(final String text, final Object r) {
return swing(new F0() { JMenuItem get() { try {
Pair p = jmenu_autoMnemonic(text);
JMenuItem mi = new JMenuItem(p.a);
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(text);\r\n JMenuItem mi = new JMenuItem(..."; }});
}
static MenuItem menuItem(String text, final Object r) {
MenuItem mi = new MenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
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 Object getTableCell(JTable tbl, int row, int col) {
if (row >= 0 && row < tbl.getModel().getRowCount())
return tbl.getModel().getValueAt(row, col);
return null;
}
static int selectedTableRow(final JTable t) {
return t == null ? -1 : swing(new F0() { Integer get() { try { return t.getSelectedRow(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret t.getSelectedRow();"; }});
}
static int tableColumnViewIndex(final JTable t, final String colName) {
return swing(new F0() { Integer get() { try {
return t.convertColumnIndexToView(t.getColumn(colName).getModelIndex());
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret t.convertColumnIndexToView(t.getColumn(colName).getModelIndex());"; }});
}
static boolean headless() {
return isHeadless();
}
static ThreadLocal < List < Object > > 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 String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
static String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
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 Component childWithClassNameEndingWith(Component c, String suffix) {
if (endsWith(className(c), suffix)) return c;
Component x;
for (Component comp : getComponents(c))
if ((x = childWithClassNameEndingWith(comp, suffix)) != null) return x;
return null;
}
static Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static Map syncHashMap() {
return synchroHashMap();
}
static boolean containsSpaces(String s) {
return indexOf(s, ' ') >= 0;
}
static A getOrKeep(Map map, A a) {
A v = map.get(a);
return v != null ? v : a;
}
static List ai_splitCamelCase(String s) {
int j = 0;
List l = new ArrayList();
for (int i = 0; i < l(s); i++)
if (isUpperCaseLetter(s.charAt(i)) && i > j) {
l.add(substring(s, j, i));
j = i;
}
if (j < l(s))
l.add(substring(s, j));
return l;
}
static void fillJMenu(final JMenu m, Object... x) {
//ifdef fillJMenu_debug
//print("fillJMenu " + m);
//endifdef
if (x == null) return;
for (int i = 0; i < l(x); i++) {
Object o = x[i], y = get(x, i+1);
if (o instanceof List)
fillJMenu(m, asArray((List) o));
else if (isMenuSeparatorIndicator(o))
m.addSeparator();
else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) {
final LiveValue lv = (LiveValue) ( o);
final JMenuItem mi = jmenuItem(or2(unCurlyBracket(lv.get()), "..."), y);
bindLiveValueListenerToComponent(mi, lv, new Runnable() { public void run() { try {
String s = lv.get();
if (isCurlyBracketed(s)) {
setEnabled(mi, false);
s = unCurlyBracket(s);
} else
setEnabled(mi, true);
setText(mi, s);
revalidate(m);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = lv.get();\r\n if (isCurlyBracketed(s)) {\r\n setEnable..."; }});
print("bound live value " + lv + " to menu item " + mi);
m.add(mi);
++i;
}
else if (o instanceof String && isRunnableX(y)) {
m.add(jmenuItem((String) o, y));
++i;
} else if (o instanceof JMenuItem)
m.add((JMenuItem) o); // "call" might use wrong method
else if (o instanceof String || o instanceof Action || o instanceof Component)
call(m, "add", o);
else if (o == null && y instanceof Runnable)
++i; // text == null => disabled item
else
print("Unknown menu item: " + o);
}
}
static void fillJPopupMenu(JPopupMenu m, Object... x) {
if (x == null) return;
for (int i = 0; i < l(x); i++) {
Object o = x[i], y = get(x, i+1);
if (o instanceof List)
fillJPopupMenu(m, asArray((List) o));
else if (isMenuSeparatorIndicator(o))
m.addSeparator();
else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) {
final LiveValue lv = (LiveValue) ( o);
final JMenuItem mi = jmenuItem("", y);
bindLiveValueListenerToComponent(mi, lv, new Runnable() { public void run() { try {
String s = lv.get();
if (isCurlyBracketed(s)) {
setEnabled(mi, false);
s = unCurlyBracket(s);
} else
setEnabled(mi, true);
setText(mi, s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = lv.get();\r\n if (isCurlyBracketed(s)) {\r\n setEnable..."; }});
m.add(mi);
}
else if (o instanceof String && isRunnableX(y)) {
m.add(jmenuItem((String) o, y));
++i;
} else if (o instanceof JMenuItem)
m.add((JMenuItem) o); // "call" might use wrong method
else if (o instanceof String || o instanceof Action || o instanceof Component)
call(m, "add", o);
else
print("Unknown menu item: " + o);
}
}
static boolean even(int i) {
return (i & 1) == 0;
}
static boolean even(long i) {
return (i & 1) == 0;
}
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 withMargin_defaultWidth = 6;
static JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
static JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
static JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
return swing(new F0() { JPanel get() { try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
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 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() { 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() { 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 A jMinWidth(final int w, final A c) {
if (c == null) return null;
return swing(new F0 () { A get() { try {
Dimension size = c.getMinimumSize();
c.setMinimumSize(new Dimension(/*max(w, size.width) ??? */w, size.height));
return jPreferWidth(w, c);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Dimension size = c.getMinimumSize();\r\n c.setMinimumSize(new Dimension(/*ma..."; }});
}
static A second(List l) {
return get(l, 1);
}
static A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static B second(Pair p) {
return p == null ? null : p.b;
}
static B second(T3 t) {
return t == null ? null : t.b;
}
static void setComponentID(Component c, String id) {
if (c != null) componentID_map.put(c, id);
}
static List mapLL(Object f, Object... data) {
return map(f, ll(data));
}
static Component wrapForSmartAdd(Object o) {
if (o == null) return jpanel();
if (o instanceof String) return jlabel((String) o);
return wrap(o);
}
static boolean isRunnable(Object o) {
return o instanceof Runnable || hasMethod(o, "get");
}
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 showFormSubmitButtonName() {
return "Submit";
}
static void disposeInternalFrame(Component c) {
final JInternalFrame f = getInternalFrame(c);
if (f != null) { swing(new Runnable() { public void run() { try {
f.dispose();
setOpt(f, "lastFocusOwner" , null); // Help GC
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.dispose();\r\n setOpt(f, \"lastFocusOwner\" , null); // Help GC"; }}); }
}
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 void disposeFrame(final Component c) {
disposeWindow(c);
}
static void onEnterInAllTextFields(JComponent c, Object action) {
if (action == null) return;
for (Component tf : allChildren(c))
onEnterIfTextField(tf, action);
}
static void onEnterInAllTextFields(List c, Object action) {
for (Object o : unnull(c))
if (o instanceof JComponent)
onEnterInAllTextFields((JComponent) o, action);
}
static List concatLists(Collection ... lists) {
List l = new ArrayList();
for (Collection list : lists)
if (list != null)
l.addAll(list);
return l;
}
static List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
for (Collection list : lists)
if (list != null)
l.addAll(list);
return l;
}
static void clickButton(final JButton b) {
if (b != null) { swing(new Runnable() { public void run() { try {
if (b.isEnabled())
b.doClick();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (b.isEnabled())\r\n b.doClick();"; }}); }
}
static A makeBold(final A c) {
if (c != null) { swing(new Runnable() { public void run() { try { c.setFont(c.getFont().deriveFont(Font.BOLD));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.setFont(c.getFont().deriveFont(Font.BOLD));"; }}); }
return c;
}
static JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
for (Object o : parts)
panel.add(wrapForSmartAdd(o), layout);
return panel;
}
static JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
return smartAddWithLayout(panel, layout, asList(flattenArray2(parts)));
}
static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static Component jrigid() {
return javax.swing.Box.createRigidArea(new Dimension(0, 0));
}
static String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() { 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() { 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() { 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 void setOptIfNotNull(Object o, String field, Object value) {
if (value != null) setOpt(o, field, value);
}
static Object mainBot;
static Object getMainBot() {
return mainBot;
}
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 Map componentID_map = weakHashMap();
static String componentID(Component c) {
return c == null ? null : componentID_map.get(c);
}
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 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 Runnable asRunnable(Object o) {
return toRunnable(o);
}
static void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static List filter(Iterable c, Object pred) {
if (pred instanceof F1) return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null) for (Object o : c)
if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
static List filter(Object pred, Iterable c) {
return filter(c, pred);
}
static List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null) for (B o : c)
if (pred.get(o).booleanValue())
x.add(o);
return x;
}
static List filter(F1 pred, Iterable