> _threadInfo_makers = synchroList();
static Object _threadInfo() {
if (empty(_threadInfo_makers)) return null;
HashMap map = new HashMap();
pcallFAll(_threadInfo_makers, map);
return map;
}
static Runnable asRunnable(Object o) {
return toRunnable(o);
}
static void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static Class javax() {
return getJavaX();
}
static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static 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 boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static boolean swic(String a, String b, Matches m) {
if (!swic(a, b)) return false;
m.m = new String[] {substring(a, l(b))};
return true;
}
static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static boolean containsNewLines(String s) {
return containsNewLine(s);
}
static String jlabel_textAsHTML_center(String text) {
return ""
+ replace(htmlencode(text), "\n", " ")
+ "
";
}
static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
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 Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
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 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 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 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 CloseableIterableIterator linesFromFile(File f) { try {
if (!f.exists()) return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
return linesFromReader(utf8bufferedReader(f));
} catch (Exception __e) { throw rethrow(__e); } }
static void pcallFAll(Collection l, Object... args) {
if (l != null) for (Object f : cloneList(l)) pcallF(f, args);
}
static void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static Runnable toRunnable(final Object o) {
if (o instanceof Runnable) return (Runnable) o;
return new Runnable() { public void run() { try { callF(o) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; }};
}
static List> _threadInheritInfo_retrievers = synchroList();
static void _threadInheritInfo(Object info) {
if (info == null) return;
pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
static Class __javax;
static Class getJavaX() { try {
return __javax;
} catch (Exception __e) { throw rethrow(__e); } }
static boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static String substring(String s, int x) {
return substring(s, x, 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 boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la-lb, b, 0, lb);
}
static boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b)) return false;
m.m = new String[] { substring(a, 0, l(a)-l(b)) };
return true;
}
static boolean containsNewLine(String s) {
return contains(s, '\n'); // screw \r, nobody needs it
}
static List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++)
if (eq(l.get(i), a))
l.set(i, b);
return l;
}
static String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
static String htmlencode(Object o) {
return htmlencode(str(o));
}
static String htmlencode(String s) {
if (s == null) return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
/*if (c >= 0x100)
out.append("").append(charToHex(c)).append(';');
else*/ if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&')
out.append("").append((int) c).append(';');
else
out.append(c);
}
return out.toString();
}
static void printException(Throwable e) {
printStackTrace(e);
}
static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
public Object next() { throw fail(); }
public boolean hasNext() { return false; }
};
static CloseableIterableIterator emptyCloseableIterableIterator() {
return emptyCloseableIterableIterator_instance;
}
static CloseableIterableIterator linesFromReader(Reader r) {
final BufferedReader br = bufferedReader(r);
return iteratorFromFunction_f0_autoCloseable(new F0() { String get() { try { return readLineFromReaderWithClose(br); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret readLineFromReaderWithClose(br);"; }}, _wrapIOCloseable(r));
}
static BufferedReader utf8bufferedReader(InputStream in) { try {
return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedReader utf8bufferedReader(File f) { try {
return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) { throw rethrow(__e); } }
static GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
static GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
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 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 boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static 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));
}
static BufferedReader bufferedReader(Reader r) {
return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
}
static CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) {
class IFF2 extends CloseableIterableIterator {
A a;
boolean done;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done) throw fail();
A _a = a;
a = null;
return _a;
}
void getNext() {
if (done || a != null) return;
a = f.get();
done = a == null;
}
public void close() throws Exception {
if (closeable != null) closeable.close();
}
};
return new IFF2();
}
static String readLineFromReaderWithClose(BufferedReader r) { try {
String s = r.readLine();
if (s == null) r.close();
return s;
} catch (Exception __e) { throw rethrow(__e); } }
static AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
return c == null ? null : new AutoCloseable() { public String toString() { return "c.close();\r\n _registerIO(c, null, false);"; } public void close() throws Exception {
c.close();
_registerIO(c, null, false);
}};
}
static A _registerIOWrap(A wrapper, Object wrapped) {
return wrapper;
}
static FileInputStream newFileInputStream(File path) throws IOException {
return newFileInputStream(path.getPath());
}
static FileInputStream newFileInputStream(String path) throws IOException {
FileInputStream f = new FileInputStream(path);
_registerIO(f, path, true);
return f;
}
static int gzInputStream_defaultBufferSize = 65536;
static GZIPInputStream gzInputStream(File f) { try {
return gzInputStream(new FileInputStream(f));
} catch (Exception __e) { throw rethrow(__e); } }
static GZIPInputStream gzInputStream(File f, int bufferSize) { try {
return gzInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) { throw rethrow(__e); } }
static GZIPInputStream gzInputStream(InputStream in) {
return gzInputStream(in, gzInputStream_defaultBufferSize);
}
static GZIPInputStream gzInputStream(InputStream in, int bufferSize) { try {
return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
} catch (Exception __e) { throw rethrow(__e); } }
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 Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
return null;
}
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 void _registerIO(Object object, String path, boolean opened) {
}
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 boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
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 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));
}
// PersistableThrowable doesn't hold GC-disturbing class references in backtrace
static volatile PersistableThrowable lastException_lastException;
static PersistableThrowable lastException() {
return lastException_lastException;
}
static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }
static String hideCredentials(String url) {
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
//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 PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
hideCredentials(str(innerException2(e)))) + "\n");
}
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 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 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 Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return 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 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); }
// 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 DynPrintLog extends DynModule {
transient JTextArea ta;
transient Lock updatePrintLog_lock = lock();
transient StringBuffer actualPrintLog;
JComponent visualize() {
return awtEvery(
jSection("Log", ta = moveCaretToEnd(typeWriterTextArea(getPrintLog()))),
500, new Runnable() { public void run() { try { updatePrintLog();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "updatePrintLog();"; }});
}
void updatePrintLog() {
// TODO: optimize
Lock __81 = updatePrintLog_lock; lock(__81); try {
if (ta != null) setText(ta, getPrintLog());
} finally { unlock(__81); } }
JTextArea myPrintLogComponent() { return ta; }
void enableWordWrap() {
enableWordWrapForTextArea(ta);
}
String getPrintLog() {
if (actualPrintLog == null)
actualPrintLog = liveLocalPrintLog_realMC(this);
return str(actualPrintLog);
}
}static abstract class CloseableIterableIterator extends IterableIterator implements AutoCloseable {
public void close() throws Exception {}
}static class Var implements IVar {
A v; // you can access this directly if you use one thread
Var() {}
Var(A v) {
this.v = v;}
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() { return v; }
public synchronized boolean has() { return v != null; }
public synchronized void clear() { v = null; }
public String toString() { return str(get()); }
}static 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 F0 {
abstract A get();
}// you still need to implement hasNext() and next()
static abstract class IterableIterator implements Iterator , Iterable {
public Iterator iterator() {
return this;
}
public void remove() {
unsupportedOperation();
}
}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 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 interface IVar {
void set(A a);
A get();
boolean has();
void clear();
}
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 F1 {
abstract B get(A a);
}
static List myInnerClasses_list=litlist(
"VF1", null, "Derefable", "JSection", "Var", "TokCondition", "IFieldIndex", "talkToThisVM_IO", "Str", "ReliableSingleThread", "SingleComponentPanel", "DynModule", "FixedRateTimer", "Concept", "FindSections", "Rect", "Pt", "ProgramScan", "F0", "IterableIterator", "F1", "F2", "RemoteDB", "Flag", "unstructure_Receiver", "ScannedBot", "Concepts", "RC", "XRef", "CloseableIterableIterator", "BaseXRef", "getOpt_Map", "Producer", "structure_Data", "IVar", "Cache", "_MethodCache", "talkTo_IO", "Matches", "LiveValue", "Q", "CriticalAction", "DialogHandler", "Pair", "DynPrintLog", "DialogIO", "BetterLabel", "componentPopupMenu_Adapter", "MRUCache", "DynamicObject", "IConceptIndex", "PersistableThrowable", "talkToSubBot_IO", "Android3", "SmartTimerTask", "Responder");
static List myInnerClasses() {
return myInnerClasses_list;
}
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 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 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 A awtEvery(A component, long delay, Object r) {
swingEvery(component, delay, r);
return component;
}
static A awtEvery(A component, long delay, long firstDelay, Object r) {
swingEvery(component, delay, firstDelay, r);
return component;
}
static void awtEvery(RootPaneContainer frame, long delay, Object r) {
swingEvery(frame, delay, r);
}
static A awtEvery(A component, double delaySeconds, Object r) {
return awtEvery(component, toMS(delaySeconds), r);
}
static JPanel jSection(Component c) {
return jSection("", c);
}
static JPanel jSection(final String title, final Component c) {
return swing(new F0() { JPanel get() { try {
Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
border = BorderFactory.createTitledBorder(border, title);
JSection panel = new JSection(c);
panel.setBorder(border);
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n bo..."; }});
}
static JPanel jSection(String title) {
return jSection(title, jpanel());
}
static A moveCaretToEnd(A ta) {
setCaretPosition(ta, textAreaTextLength(ta));
return ta;
}
static JTextArea typeWriterTextArea() {
return newTypeWriterTextArea();
}
static JTextArea typeWriterTextArea(String text) {
return newTypeWriterTextArea(text);
}
static String getPrintLog() {
return str(print_log);
}
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 enableWordWrapForTextArea(final JTextArea ta) {
if (ta != null) { swing(new Runnable() { public void run() { try {
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ta.setLineWrap(true);\r\n ta.setWrapStyleWord(true);"; }}); }
}
static StringBuffer liveLocalPrintLog_realMC(Object o) {
Object realMC = getMainClass(o);
if (realMC != mc())
return (StringBuffer) getOpt(realMC, "local_log");
return liveLocalPrintLog();
}
static Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static UnsupportedOperationException unsupportedOperation() {
throw new UnsupportedOperationException();
}
static int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
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 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 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);
}
}
static WeakReference creator_class;
static Object creator() {
return creator_class == null ? null : creator_class.get();
}
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 boolean addIfNotThere(Collection c, A a) {
return setAdd(c, a);
}
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 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 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 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 Object _onAWTEnter_f;
static AutoCloseable _onAWTEnter() {
return (AutoCloseable) callF(_onAWTEnter_f);
}
static JDesktopPane mainDesktopPane_value;
static JDesktopPane mainDesktopPane() {
return mainDesktopPane_value;
}
static A getWeakRef(WeakReference ref) {
return ref == null ? null : ref.get();
}
static void setOptMC(String field, Object value) {
setOpt(mc(), field, 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 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 void swingEvery(JComponent component, long delay, Object r) {
installTimer(component, delay, r);
}
static void swingEvery(JComponent component, long delay, long firstDelay, Object r) {
installTimer(component, r, delay, firstDelay);
}
static void swingEvery(RootPaneContainer frame, long delay, Object r) {
installTimer(frame, delay, r);
}
static void swingEvery(RootPaneContainer frame, long delay, long firstDelay, Object r) {
installTimer(frame, delay, firstDelay, r);
}
static long toMS(double seconds) {
return (long) (seconds*1000);
}
static JPanel jpanel(LayoutManager layout) {
return swingNu(JPanel.class, layout);
}
static JPanel jpanel() {
return swingNu(JPanel.class);
}
static void setCaretPosition(final JTextComponent c, final int pos) {
if (c != null) { swing(new Runnable() { public void run() { try {
try {
int _pos = max(0, min(l(c.getText()), pos));
c.setCaretPosition(_pos);
} catch (Throwable __e) { _handleException(__e); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall {\r\n int _pos = max(0, min(l(c.getText()), pos));\r\n c.setCaret..."; }}); }
}
static int textAreaTextLength(JTextComponent ta) {
return l(getText(ta));
}
static JTextArea newTypeWriterTextArea() {
return newTypeWriterTextArea("");
}
static JTextArea newTypeWriterTextArea(String text) {
return setFont(jTextArea(text), typeWriterFont());
}
static StringBuffer liveLocalPrintLog() {
return local_log;
}
static Iterator emptyIterator() {
return Collections.emptyIterator();
}
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 void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null) map.put(key, value);
}
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 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 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 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 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 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 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 DynModule dm_current_mandatory() {
return assertNotNull("No module set!", dm_currentModule());
}
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 _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;
}
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 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 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 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 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;
}
}
// first delay = delay
static Timer installTimer(JComponent component, Object r, long delay) {
return installTimer(component, r, delay, delay);
}
// first delay = delay
static Timer installTimer(RootPaneContainer frame, long delay, Object r) {
return installTimer(frame.getRootPane(), r, delay, delay);
}
// first delay = delay
static Timer installTimer(JComponent component, long delay, Object r) {
return installTimer(component, r, delay, delay);
}
static Timer installTimer(JComponent component, long delay, long firstDelay, Object r) {
return installTimer(component, r, delay, firstDelay);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) {
return installTimer(component, r, delay, firstDelay, true);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) {
if (component == null) return null;
return (Timer) swingAndWait(new F0() { Object get() { try {
final Var timer = new Var();
timer.set(new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
AutoCloseable __580 = tempActivity(r); try {
try {
if (!allPaused())
if (isFalse(callF(r)))
cancelTimer(timer.get());
} catch (Throwable __e) { _handleException(__e); }
} finally { _close(__580); }} catch (Throwable __e) { messageBox(__e); }}}));
timer.get().setInitialDelay(toInt(firstDelay));
timer.get().setRepeats(repeats);
bindTimerToComponent(timer.get(), component);
return timer.get();
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final new Var timer;\r\n timer.set(new Timer(toInt(delay), actionList..."; }});
}
static Timer installTimer(RootPaneContainer frame, long delay, long firstDelay, Object r) {
return installTimer(frame.getRootPane(), delay, firstDelay, r);
}
static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x) x = d;
return x;
}
static A setFont(final Font font, final A a) {
if (a != null) { swing(new Runnable() { public void run() { try { a.setFont(font);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setFont(font);"; }}); }
return a;
}
static A setFont(A a, Font font) {
return setFont(font, a);
}
static A setFont(final String fontID, float fontSize, final A a) {
return setFont(loadFont_cached(fontID, fontSize), a);
}
static JTextArea jTextArea() {
return jTextArea("");
}
static JTextArea jTextArea(final String text) {
return swingNu(JTextArea.class, text);
}
static Font typeWriterFont() {
return typeWriterFont(iround(14*getSwingFontScale()));
}
static Font typeWriterFont(int size) {
return new Font("Courier", Font.PLAIN, size);
}
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 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 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 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 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 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 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 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 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 String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder((int) (l(s)*1.5+2));
quote_impl(s, out);
return out.toString();
}
static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static List hotwire_copyOver_after = synchroList();
static void hotwire_copyOver(Class c) {
// TODO: make a mechanism for making such "inheritable" fields
for (String field : ll("print_log", "print_silent", "androidContext", "_userHome"))
setOptIfNotNull(c, field, getOpt(mc(), field));
setOptIfNotNull(c, "mainBot" , getMainBot());
setOpt(c, "creator_class" , new WeakReference(mc()));
pcallFAll(hotwire_copyOver_after, c);
}
static 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 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 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 int toInt(Object o) {
if (o == null) return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt((String) o);
throw fail("woot not int: " + getClassName(o));
}
static int toInt(long l) {
if (l != (int) l) throw fail("Too large for int: " + l);
return (int) l;
}
static AutoCloseable tempActivity(Object r) {
return null;
}
static boolean allPaused() {
return ping_pauseAll;
}
static void messageBox(final String msg) {
if (headless()) print(msg);
else { swing(new Runnable() { public void run() { try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES..."; }}); }
}
static void messageBox(Throwable e) {
//showConsole();
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
static void bindTimerToComponent(final Timer timer, JFrame f) {
bindTimerToComponent(timer, f.getRootPane());
}
static void bindTimerToComponent(final Timer timer, JComponent c) {
if (c.isShowing())
timer.start();
c.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
timer.start();
}
public void ancestorRemoved(AncestorEvent event) {
timer.stop();
}
public void ancestorMoved(AncestorEvent event) {
}
});
}
static A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () { A get() { try { return nuObject(c, args); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret nuObject(c, args);"; }});
}
static Map loadFont_cached_cache = new HashMap();
static synchronized Font loadFont_cached(String snippetID) { try {
snippetID = formatSnippetID(snippetID);
Font f = loadFont_cached_cache.get(snippetID);
if (f == null)
loadFont_cached_cache.put(snippetID, f = loadFont(snippetID, 12f));
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static synchronized Font loadFont_cached(String snippetID, float size) { try {
return loadFont_cached(snippetID).deriveFont(size);
} catch (Exception __e) { throw rethrow(__e); } }
static int iround(double d) {
return (int) Math.round(d);
}
static int iround(Number n) {
return iround(toDouble(n));
}
static float getSwingFontScale() {
return or((Float) vm_generalMap_get("swingFontScale_value"), 1f);
}
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 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 Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static Map syncHashMap() {
return synchroHashMap();
}
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 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 String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
static String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
static Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static Class getClass(Object realm, String name) { try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) { throw rethrow(__e); } }
static String classNameToVM(String name) {
return name.replace(".", "$");
}
static 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 boolean containsSpaces(String s) {
return indexOf(s, ' ') >= 0;
}
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;
}
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 A or(A a, A b) {
return a != null ? a : b;
}
static boolean even(int i) {
return (i & 1) == 0;
}
static boolean even(long i) {
return (i & 1) == 0;
}
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 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 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 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 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 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 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 boolean headless() {
return isHeadless();
}
static Object nuObject(String className, Object... args) { try {
return nuObject(classForName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }
// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
ret nuObject(_getClass(realm, className), args);
}*/
static A nuObject(Class c, Object... args) { try {
if (args.length == 0) return nuObjectWithoutArguments(c); // cached!
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return (A) m.newInstance(args);
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found"
+ (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static Font loadFont(String snippetID) { try {
return loadFont(snippetID, 12f);
} catch (Exception __e) { throw rethrow(__e); } }
static Font loadFont(InputStream in) { try {
return Font.createFont(Font.TRUETYPE_FONT, in);
} catch (Exception __e) { throw rethrow(__e); } }
static Font loadFont(String snippetID, float fontSize) {
return loadFont(loadLibrary(snippetID), fontSize);
}
static Font loadFont(File f, float fontSize) { try {
return Font.createFont(Font.TRUETYPE_FONT, f).deriveFont(fontSize);
} catch (Exception __e) { throw rethrow(__e); } }
static Font loadFont(InputStream in, float fontSize) { try {
return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(fontSize);
} catch (Exception __e) { throw rethrow(__e); } }
static double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o == null) return 0.0;
throw fail(o);
}
static String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
static List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
static boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b)) return false;
m.m = new String[] {dropLast(l(b), a)};
return true;
}
static List getComponents(final Component c) {
return !(c instanceof Container) ? emptyList() : asList(swing(new F0() { Component[] get() { try { return ((Container) c).getComponents(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret ((Container) c).getComponents();"; }}));
}
static Set synchronizedSet() {
return synchroHashSet();
}
static Set synchronizedSet(Set set) {
return Collections.synchronizedSet(set);
}
static Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
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 String strOrNull(Object o) {
return o == null ? null : str(o);
}
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 boolean isUpperCaseLetter(char c) {
return Character.isUpperCase(c);
}
static Object[] asArray(List l) {
return toObjectArray(l);
}
static A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static boolean isMenuSeparatorIndicator(Object o) {
return eqOneOf(o, "***", "---", "===", "");
}
static boolean isRunnableX(Object o) {
if (o == null) return false;
if (o instanceof String) return hasMethod(mc(), (String) o);
return o instanceof Runnable || hasMethod(o, "get");
}
static String unCurlyBracket(String s) {
return tok_unCurlyBracket(s);
}
static A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) {
if (lv != null)
bindToComponent(component,
new Runnable() { public void run() { try {
lv.onChangeAndNow(listener);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindLiveValueListenerToComponent_debug\r\n print(\"bindLiveValueL..."; }},
new Runnable() { public void run() { try { lv.removeOnChangeListener(listener) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lv.removeOnChangeListener(listener)"; }});
return component;
}
static boolean isCurlyBracketed(String s) {
return isCurlyBraced(s);
}
static void setEnabled(final JComponent c, final boolean enable) {
if (c != null) { swing(new Runnable() { public void run() { try { c.setEnabled(enable);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.setEnabled(enable);"; }}); }
}
static A revalidate(final A c) {
if (c == null || !c.isShowing()) return c;
{ swing(new Runnable() { public void run() { try {
// magic combo to actually relayout and repaint
c.revalidate();
c.repaint();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// magic combo to actually relayout and repaint\r\n c.revalidate();\r\n c.r..."; }}); }
return c;
}
static void revalidate(RootPaneContainer c) { revalidate((Component) c); }
static void revalidate(JFrame f) { revalidate((Component) f); }
static void revalidate(JInternalFrame f) { revalidate((Component) f); }
static A componentPopupMenuItem(A c, final String name, final Object action) {
componentPopupMenu(c, 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);"; }});
return c;
}
static void componentPopupMenuItem(JComponent c, final JMenuItem menuItem) {
componentPopupMenu(c, new VF1() { public void get(JPopupMenu menu) { try {
addMenuItem(menu, menuItem);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "addMenuItem(menu, menuItem);"; }});
}
static String copyTextToClipboard(String text) {
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
vmBus_send("newClipboardContents", text);
return text;
}
static Set vm_generalWeakSet(Object name) {
synchronized(get(javax(), "generalMap")) {
Set set = (Set) ( vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = newWeakHashSet());
return set;
}
}
static ThreadLocal addInternalFrame_dontSelect = new ThreadLocal();
static ThreadLocal addInternalFrame_layer = new ThreadLocal();
static ThreadLocal addInternalFrame_toBack = new ThreadLocal();
static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h) {
return addInternalFrame(desktop, title, x, y, w, h, null);
}
static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h, final Component contents) {
return addInternalFrame(desktop, title, rect(x, y, w, h), contents);
}
static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Component contents) {
return addInternalFrame(desktop, title, null, contents);
}
static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Rect r, final Component contents) {
final boolean dontSelect = isTrue(optParam(addInternalFrame_dontSelect));
final boolean toBack = isTrue(optParam(addInternalFrame_toBack));
final Integer layer = optParam(addInternalFrame_layer);
return swing(new F0() { JInternalFrame get() { try {
JInternalFrame frame;
if (contents instanceof JInternalFrame)
frame = (JInternalFrame) contents;
else {
frame = jInternalFrame(title);
setInternalFrameContents(frame, contents);
}
frame.setVisible(true);
desktop.add(frame, layer);
if (r != null)
setBounds(frame, r);
else
internalFrameDefaultPosition(frame);
if (dontSelect)
if (toBack)
frame.toBack();
else
frame.toFront();
else
frame.setSelected(true);
return fixInternalFrame(frame);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JInternalFrame frame;\r\n if (contents instanceof JInternalFrame)\r\n fra..."; }});
}
static JInternalFrame addInternalFrame(JDesktopPane desktop, String title) {
return addInternalFrame(desktop, title, jpanel());
}
static JInternalFrame minInternalFrameWidth(final JInternalFrame frame, final int w) {
{ swing(new Runnable() { public void run() { try {
if (frame != null && frame.getWidth() < w)
frame.setSize(w, frame.getHeight());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (frame != null && frame.getWidth() < w)\r\n frame.setSize(w, frame.getH..."; }}); }
return frame;
}
static JInternalFrame minInternalFrameWidth(int w, JInternalFrame frame) {
return minInternalFrameWidth(frame, w);
}
static A packInternalFrameVertically(A c) {
return packInternalFrameVertically(-1, c);
}
static A packInternalFrameVertically(int width, A c) {
final JInternalFrame win = getInternalFrame(c);
if (win == null) return c;
final int w = width < 0 ? win.getWidth() : width;
{ swing(new Runnable() { public void run() { try {
win.pack();
win.setSize(w, win.getHeight());
fixInternalFrame(win);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "win.pack();\r\n win.setSize(w, win.getHeight());\r\n fixInternalFrame(win);"; }}); }
return c;
}
static JInternalFrame centerInternalFrame(final JInternalFrame f) {
{ swing(new Runnable() { public void run() { try {
Container c = f.getParent();
if (c != null) {
//print("Container type: " + className(c) + ", bounds: " + c.getBounds());
f.setLocation((c.getWidth()-f.getWidth())/2, (c.getHeight()-f.getHeight())/2);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Container c = f.getParent();\r\n if (c != null) {\r\n //print(\"Container ..."; }}); }
return f;
}
static JInternalFrame centerInternalFrame(final int w, final int h, final JInternalFrame f) {
{ swing(new Runnable() { public void run() { try {
f.setSize(w, h);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.setSize(w, h);"; }}); }
return centerInternalFrame(f);
}
static int packFrame_minw = 150, packFrame_minh = 50;
static A packFrame(final A c) {
{ swing(new Runnable() { public void run() { try {
Window w = getWindow(c);
if (w != null) {
w.pack();
int maxW = getScreenWidth()-50, maxH = getScreenHeight()-50;
w.setSize(
min(maxW, max(w.getWidth(), packFrame_minw)),
min(maxH, max(w.getHeight(), packFrame_minh)));
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Window w = getWindow(c);\r\n if (w != null) {\r\n w.pack();\r\n int ma..."; }}); }
return c;
}
static JFrame packFrame(ButtonGroup g) {
return packFrame(getFrame(g));
}
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 Dimension getMinimumSize(final Component c) {
return c == null ? null : swing(new F0() { Dimension get() { try { return c.getMinimumSize(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret c.getMinimumSize();"; }});
}
// c = Component or something implementing swing()
static Component wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
static Component wrap_2(Object swingable) {
if (swingable == null) return null;
Component c;
if (swingable instanceof Component) c = (Component) swingable;
else c = (Component) callOpt(swingable, "swing");
if (c instanceof JTable || c instanceof JList
|| c instanceof JTextArea || c instanceof JEditorPane
|| c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
static A jPreferWidth(int w, A c) {
Dimension size = c.getPreferredSize();
c.setPreferredSize(new Dimension(/*max(w, size.width) ??? */w, size.height));
return c;
}
static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
static JLabel jlabel() {
return jlabel(" ");
}
static boolean newButton_autoToolTip = true;
// action can be Runnable or a function name
static JButton newButton(final String text, final Object action) {
return swing(new F0() { JButton get() { try {
String text2 = dropPrefix("[disabled] ", text);
final JButton btn = new JButton(text2);
if (l(text2) < l(text)) btn.setEnabled(false);
if (newButton_autoToolTip) {
btn.setToolTipText(btn.getText());
//onChangeAndNow(btn, r { btn.setToolTipText(btn.getText()) });
}
// submitButtonOnEnter(btn); // test this first
if (action != null)
btn.addActionListener(actionListener(action, btn));
return btn;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "S text2 = dropPrefix(\"[disabled] \", text);\r\n final JButton btn = new JButt..."; }});
}
static boolean isInstanceOf(Object o, Class type) {
return type.isInstance(o);
}
static void disposeWindow(final Window window) {
if (window != null) { swing(new Runnable() { public void run() { try {
window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); // call listeners
myFrames_list.remove(window);
window.dispose();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //..."; }}); }
}
static void disposeWindow(final Component c) {
disposeWindow(getWindow(c));
}
static void disposeWindow(Object o) {
if (o != null) disposeWindow(((Component) o));
}
static void disposeWindow() {
disposeWindow(heldInstance(Component.class));
}
static List allChildren(Component c) {
return childrenOfType(c, Component.class);
}
static void onEnterIfTextField(Component c, Object action) {
if (action == null) return;
if (c instanceof JTextField)
onEnter((JTextField) c, action);
else if (c instanceof JComboBox)
onEnter((JComboBox) c, action);
}
static Object[] flattenArray2(Object... a) {
List l = new ArrayList();
if (a != null) for (Object x : a)
if (x instanceof Object[])
l.addAll(asList((Object[]) x));
else if (x instanceof Collection)
l.addAll((Collection) x);
else
l.add(x);
return asObjectArray(l);
}
static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static Map myFrames_list = weakHashMap();
static List myFrames() {
return swing(new F0>() { List get() { try { return keysList(myFrames_list); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret keysList(myFrames_list);"; }});
}
static Map weakHashMap() {
return newWeakHashMap();
}
static void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null) tl.set(l = new ArrayList());
l.add(a);
}
static A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null) return null;
A a = popLast(l);
if (empty(l)) tl.set(null);
return a;
}
static 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 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 List getClasses(Object[] array) {
List l = new ArrayList();
for (Object o : array) l.add(_getClass(o));
return l;
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0) throw fail("0 is not a snippet ID");
return id;
}
static File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
static boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static boolean isEmpty(Object[] a) { return a == null || a.length == 0; }
static boolean isEmpty(byte[] a) { return a == null || a.length == 0; }
static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s)-1);
}
static String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[a.length-n];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static List dropLast(List l) {
return subList(l, 0, l(l)-1);
}
static List dropLast(int n, List l) {
return subList(l, 0, l(l)-n);
}
static List dropLast(Iterable l) {
return dropLast(asList(l));
}
static String dropLast(String s) {
return substring(s, 0, l(s)-1);
}
static String dropLast(String s, int n) {
return substring(s, 0, l(s)-n);
}
static String dropLast(int n, String s) {
return dropLast(s, n);
}
static JMenuItem jMenuItem(final String text) {
return jmenuItem(text);
}
static JMenuItem jMenuItem(String text, Object r) {
return jmenuItem(text, r);
}
static Pair jmenu_autoMnemonic(String s) {
int i = indexOf(s, '&');
if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i+1)))
return pair(substring(s, 0, i) + substring(s, i+1), (int) s.charAt(i+1));
return pair(s, 0);
}
static ActionListener actionListenerInNewThread(final Object runnable) {
return actionListenerInNewThread(runnable, null);
}
static ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
startThread("Action Listener", new Runnable() { public void run() { try {
AutoCloseable __259 = holdInstance(instanceToHold); try {
callF(runnable);
} finally { _close(__259); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __259 = holdInstance(instanceToHold); try {\r\n callF(runnab..."; }});
} catch (Throwable __e) { messageBox(__e); }}};
}
static String tok_unCurlyBracket(String s) {
return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
}
static A bindToComponent(final A component, final Runnable onShow, final Runnable onUnShow) {
{ swing(new Runnable() { public void run() { try {
final Var < Boolean > flag = new Var(false);
component.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
if (flag.get()) print("Warning: bindToComponent logic failure");
flag.set(true);
pcallF(onShow);
}
public void ancestorRemoved(AncestorEvent event) {
if (!flag.get()) print("Warning: bindToComponent logic failure");
flag.set(false);
pcallF(onUnShow);
}
public void ancestorMoved(AncestorEvent event) {
}
});
if (component.isShowing()) { // Hopefully this matches the AncestorListener logic
flag.set(true);
pcallF(onShow);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final Var flag = new(false);\r\n component.addAncestorListener(new ..."; }}); }
return component;
}
static A bindToComponent(A component, Runnable onShow) {
return bindToComponent(component, onShow, null);
}
static boolean isCurlyBraced(String s) {
List tok = tok_combineCurlyBrackets_keep(javaTok(s));
return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}");
}
static Rect rect(int x, int y, int w, int h) {
return new Rect(x, y, w, h);
}
static boolean jInternalFrame_iconifiable = true;
static JInternalFrame jInternalFrame() {
return jInternalFrame("");
}
static JInternalFrame jInternalFrame(final String title) {
return swing(new F0() { JInternalFrame get() { try {
JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame_iconifiable);
f.setVisible(true);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame..."; }});
}
static void setInternalFrameContents(final Component c, final Object contents) {
{ swing(new Runnable() { public void run() { try {
JInternalFrame frame = getInternalFrame(c);
if (frame == null) return;
frame.getContentPane().removeAll();
frame.getContentPane().setLayout(new BorderLayout());
if (contents != null) frame.getContentPane().add(wrap(contents));
revalidate(frame);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JInternalFrame frame = getInternalFrame(c);\r\n if (frame == null) return;\r\n..."; }}); }
}
static A setBounds(final int x, final int y, final int w, final int h, final A a) {
if (a != null) { swing(new Runnable() { public void run() { try {
a.setBounds(x, y, w, h);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setBounds(x, y, w, h);"; }}); }
return a;
}
static A setBounds(final A a, final Rect r) {
if (a != null) { swing(new Runnable() { public void run() { try {
a.setBounds(toRectangle(r));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setBounds(toRectangle(r));"; }}); }
return a;
}
static A setBounds(A a, int x, int y, int w, int h) {
return setBounds(x, y, w, h, a);
}
static void internalFrameDefaultPosition(JInternalFrame f) {
f.setSize(500, 300);
centerInternalFrame(f);
}
static int fixInternalFrame_borderTopLeft = 0;
static int fixInternalFrame_borderBottomRight = 40; // for title bar
static JInternalFrame fixInternalFrame(final JInternalFrame f) {
return swing(new F0() { JInternalFrame get() { try {
Container c = f.getParent();
if (c == null) return f;
Rect r = toRect(f.getBounds());
int a = fixInternalFrame_borderTopLeft, b = fixInternalFrame_borderBottomRight;
Rect outer = new Rect(a, a, c.getWidth()-b, c.getHeight()-b);
if (!rectContains(outer, r))
f.setLocation(
max(a, min(r.x, outer.x2())),
max(a, min(r.y, outer.y2())));
if (r.w > c.getWidth() || r.h > c.getHeight())
f.setSize(c.getWidth()-a, c.getHeight()-a);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Container c = f.getParent();\r\n if (c == null) ret f;\r\n Rect r = toRect(..."; }});
}
static Window getWindow(Object o) {
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof Window) return (Window) c;
c = c.getParent();
}
return null;
}
static int getScreenWidth() {
return getScreenSize().width;
}
static int getScreenHeight() {
return getScreenSize().height;
}
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 A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), c);
return c;
}
static JScrollPane jscroll(final Component c) {
return swing(new F0() { JScrollPane get() { try { return new JScrollPane(c); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret new JScrollPane(c);"; }});
}
static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static Object[] asObjectArray(List l) {
return toObjectArray(l);
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static List keysList(Map map) {
return cloneListSynchronizingOn(keys(map), map);
}
static A popLast(List l) {
return liftLast(l);
}
static String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
static File loadBinarySnippet(String snippetID) { try {
long id = parseSnippetID(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile(snippetID);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static boolean isLetterOrDigit(char c) {
return Character.isLetterOrDigit(c);
}
static List dropFirstThreeAndLastThree(List l) {
return dropFirstAndLast(3, l);
}
// TODO: extended multi-line strings
static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;
static List javaTok(String s) {
++javaTok_n;
ArrayList