import java.util.*; import java.util.zip.*; import java.util.List; import java.util.regex.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; import java.util.function.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.table.*; import java.io.*; import java.net.*; import java.lang.reflect.*; import java.lang.ref.*; import java.lang.management.*; import java.security.*; import java.security.spec.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.awt.geom.*; import javax.imageio.*; import java.math.*; import x30_pkg.x30_util; import static x30_pkg.x30_util.VF1; import static x30_pkg.x30_util.l; import static x30_pkg.x30_util.getOpt; import static x30_pkg.x30_util.setOpt; import static x30_pkg.x30_util.callOpt; import static x30_pkg.x30_util.newWeakHashMap; import static x30_pkg.x30_util.newDangerousWeakHashMap; import static x30_pkg.x30_util.get; import static x30_pkg.x30_util.assertTrue; import static x30_pkg.x30_util.isHeadless; import static x30_pkg.x30_util.isAndroid; import static x30_pkg.x30_util.isTrue; import x30_pkg.x30_util.DynamicObject; import loadableUtils.utils; import static loadableUtils.utils._threadInfo; import static loadableUtils.utils._threadInheritInfo; import static loadableUtils.utils.match; import static loadableUtils.utils.setOpt_raw; import static loadableUtils.utils.getField; import static loadableUtils.utils.format3; import static loadableUtils.utils.vm_generalIdentityHashSet; import static loadableUtils.utils.vm_generalHashMap; import static loadableUtils.utils.vm_generalWeakSubMap; import static loadableUtils.utils.bindToComponent; import static loadableUtils.utils.loadPage; import static loadableUtils.utils.loadPageSilently; import static loadableUtils.utils.loadSnippet; import static loadableUtils.utils.componentPopupMenu; import static loadableUtils.utils.dm_current_generic; import static loadableUtils.utils.cset; import static loadableUtils.utils.DynamicObject_loading; import static loadableUtils.utils.concepts_unlisted; import static loadableUtils.utils.dynamicObjectIsLoading; import static loadableUtils.utils.rethrow; import loadableUtils.utils.F0; import loadableUtils.utils.F1; import loadableUtils.utils.IF0; import loadableUtils.utils.IF1; import loadableUtils.utils.IVF1; import loadableUtils.utils.Matches; import loadableUtils.utils.BetterLabel; import loadableUtils.utils.SingleComponentPanel; import loadableUtils.utils.Q; import loadableUtils.utils.ImageSurface; import loadableUtils.utils.RGBImage; import loadableUtils.utils.RGB; import loadableUtils.utils.MakesBufferedImage; import loadableUtils.utils.MultiSet; import loadableUtils.utils.Concept; import loadableUtils.utils.Concepts; import loadableUtils.utils.RC; import loadableUtils.utils.IterableIterator; import loadableUtils.utils.IFieldIndex; import loadableUtils.utils.Swingable; import loadableUtils.utils.PersistableThrowable; import loadableUtils.utils.DynPrintLog; import loadableUtils.utils.GlobalID; import loadableUtils.utils.Rect; import loadableUtils.utils.Pt; import java.awt.geom.*; import org.fife.ui.autocomplete.*; import org.fife.rsta.ui.CollapsibleSectionPanel; import org.fife.rsta.ui.GoToDialog; import org.fife.rsta.ui.SizeGripIcon; import org.fife.rsta.ui.search.FindDialog; import org.fife.rsta.ui.search.ReplaceDialog; import org.fife.rsta.ui.search.ReplaceToolBar; import org.fife.rsta.ui.search.SearchEvent; import org.fife.rsta.ui.search.SearchListener; import org.fife.rsta.ui.search.FindToolBar; import org.fife.ui.rsyntaxtextarea.ErrorStrip; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rtextarea.RTextScrollPane; import org.fife.ui.rtextarea.SearchContext; import org.fife.ui.rtextarea.SearchEngine; import org.fife.ui.rtextarea.SearchResult; import org.fife.ui.rsyntaxtextarea.RSyntaxDocument; import org.fife.ui.rsyntaxtextarea.SyntaxScheme; import javax.swing.border.*; import java.util.jar.*; import java.text.*; import javax.swing.border.TitledBorder; import org.fife.ui.rsyntaxtextarea.*; import java.text.NumberFormat; import javax.swing.event.AncestorListener; import javax.swing.event.AncestorEvent; import javax.swing.Timer; import java.util.TimeZone; import javax.imageio.metadata.*; import javax.imageio.stream.*; import javax.swing.undo.UndoManager; import java.text.SimpleDateFormat; import java.nio.charset.Charset; class main { static public class AModule extends DynPrintLog { public void start() { try { super.start(); startThread("Start", new Runnable() { public void run() { try { AutoCloseable __10 = enter(); try { try { test_LeftArrowScriptAutoCompleter(); } catch (Throwable __e) { printStackTrace(__e); } } finally { _close(__10); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __10 = enter(); try { try {\r\n test_LeftArrowScriptAutoComple..."; } }); } catch (Exception __e) { throw rethrow(__e); } } } static public boolean _moduleClass_AModule = true; static public String programID; static public void _onLoad_initUtils() { utils.__javax = javax(); } static public void _onLoad_defaultClassFinder() { setDefaultClassFinder(new F1() { public Class get(String name) { Class c = findClass_fullName(name); if (c != null) return c; if (name.startsWith("main$")) return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4)); return null; } }); } static public ThreadLocal dynamicObjectIsLoading_threadLocal() { return DynamicObject_loading; } static volatile public Concepts mainConcepts; static public Concepts db_mainConcepts() { if (mainConcepts == null) mainConcepts = newConceptsWithClassFinder(getDBProgramID()); return mainConcepts; } static public void cleanMeUp_concepts() { if (db_mainConcepts() != null) db_mainConcepts().cleanMeUp(); } static public Thread startThread(Object runnable) { return startThread(defaultThreadName(), runnable); } static public Thread startThread(String name, Runnable runnable) { runnable = wrapAsActivity(runnable); return startThread(newThread(runnable, name)); } static public Thread startThread(String name, Object runnable) { runnable = wrapAsActivity(runnable); return startThread(newThread(toRunnable(runnable), name)); } static public Thread startThread(Thread t) { _registerThread(t); t.start(); return t; } static public void test_LeftArrowScriptAutoCompleter() { GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser(); LeftArrowScriptAutoCompleter completer = new LeftArrowScriptAutoCompleter(parser); completer.globalMethodNames = () -> ll("add", "pat", "lol"); completer.parser.importedPackages = () -> null; completer.seek("a", 1); assertEqualsVerbose("a", completer.typedCharacters()); assertEqualsVerbose(ll("add", "pat", "false"), completer.getCompletions()); parser = new GazelleV_LeftArrowScriptParser(); completer = new LeftArrowScriptAutoCompleter(parser); completer.globalMethodNames = () -> ll("add", "pat", "lol"); completer.parser.importedPackages = () -> null; completer.seek("add", 3); assertFalseVerbose(contains(completer.getCompletions(), "add")); parser = new GazelleV_LeftArrowScriptParser(); completer = new LeftArrowScriptAutoCompleter(parser); completer.globalMethodNames = () -> ll("add", "pat", "lol"); completer.parser.importedPackages = () -> null; completer.seek("add ", 4); assertContainsAll(completer.getCompletions(), ll("true", "false", "null")); for (String text : ll("Mat", "Mat ")) { parser = new GazelleV_LeftArrowScriptParser(); completer = new LeftArrowScriptAutoCompleter(parser); completer.seek(printQuoted("text", text), 3); var completions = completer.getCompletions(); pnlReversed(takeFirst(10, completions)); assertEquals(0, indexOf(completions, "Math")); } parser = new GazelleV_LeftArrowScriptParser(); completer = new LeftArrowScriptAutoCompleter(parser); completer.seek(print("new Inte"), 8); var completions = completer.getCompletions(); pnlReversed(takeFirst(10, completions)); assertEquals(0, indexOf(completions, "Integer")); parser = new GazelleV_LeftArrowScriptParser(); parser.allowTheWorld(test_LeftArrowScriptAutoCompleter_FunctionContainer.class); completer = new LeftArrowScriptAutoCompleter(parser); completer.seek(print("MyN"), 3); completions = completer.getCompletions(); pnlReversed(takeFirst(10, completions)); assertEquals(0, indexOf(completions, "MyName")); parser = new GazelleV_LeftArrowScriptParser(); parser.importedPackages = () -> null; completer = new LeftArrowScriptAutoCompleter(parser); completer.seekEnd("a <- 1\n"); assertSetsEqual(listPlus(completer.predefinedExpressions(), "a"), completer.getCompletions()); } static public class test_LeftArrowScriptAutoCompleter_FunctionContainer { public class MyName { } } static public A printStackTrace(A e) { if (e != null) print(getStackTrace(e)); return e; } static public void printStackTrace() { printStackTrace(new Throwable()); } static public void printStackTrace(String msg) { printStackTrace(new Throwable(msg)); } static public void printStackTrace(String msg, Throwable e) { printStackTrace(new Throwable(msg, e)); } static public void _close(AutoCloseable c) { if (c != null) try { c.close(); } catch (Throwable e) { if (c instanceof javax.imageio.stream.ImageOutputStream) return; else throw rethrow(e); } } static public Class javax() { return getJavaX(); } static public void setDefaultClassFinder(Object cf) { _defaultClassFinder_value = cf; } static public HashMap findClass_fullName_cache = new HashMap(); static public Class findClass_fullName(String name) { synchronized (findClass_fullName_cache) { if (findClass_fullName_cache.containsKey(name)) return findClass_fullName_cache.get(name); Class c; try { c = Class.forName(name); } catch (ClassNotFoundException e) { c = null; } findClass_fullName_cache.put(name, c); return c; } } static public Object _defaultClassFinder_value = defaultDefaultClassFinder(); static public Object _defaultClassFinder() { return _defaultClassFinder_value; } static public Concepts newConceptsWithClassFinder(String progID) { Concepts cc = new Concepts(progID); cc.classFinder = _defaultClassFinder(); return cc; } static public Concepts newConceptsWithClassFinder(File conceptsFile) { Concepts cc = new Concepts(assertNotNull(conceptsFile)); cc.classFinder = _defaultClassFinder(); return cc; } static public Concepts newConceptsWithClassFinder(File conceptsFile, IF1 classFinder) { Concepts cc = new Concepts(assertNotNull(conceptsFile)); cc.classFinder = classFinder; return cc; } static public String getDBProgramID_id; static public String getDBProgramID() { return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase(); } static public String defaultThreadName_name; static public String defaultThreadName() { if (defaultThreadName_name == null) defaultThreadName_name = "A thread by " + programID(); return defaultThreadName_name; } static public Runnable wrapAsActivity(Object r) { if (r == null) return null; Runnable r2 = toRunnable(r); Object mod = dm_current_generic(); if (mod == null) return r2; return new Runnable() { public void run() { try { AutoCloseable c = (AutoCloseable) (rcall("enter", mod)); AutoCloseable __1 = c; try { r2.run(); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable c = (AutoCloseable) (rcall enter(mod));\r\n temp c;\r\n r2.r..."; } }; } static public Thread newThread(Object runnable) { return new BetterThread(_topLevelErrorHandling(toRunnable(runnable))); } static public Thread newThread(Object runnable, String name) { if (name == null) name = defaultThreadName(); return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)), name); } static public Thread newThread(String name, Object runnable) { return newThread(runnable, name); } static public Runnable toRunnable(final Object o) { if (o instanceof Runnable) return (Runnable) o; if (o instanceof String) throw fail("callF_legacy"); return new Runnable() { public void run() { try { callF(o); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; } }; } static public Map _registerThread_threads; static public Object _onRegisterThread; static public 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 public void _registerThread() { _registerThread(Thread.currentThread()); } static public List ll(A... a) { ArrayList l = new ArrayList(a.length); if (a != null) for (A x : a) l.add(x); return l; } static public A assertEqualsVerbose(Object x, A y) { assertEqualsVerbose((String) null, x, y); return y; } static public A assertEqualsVerbose(String msg, Object x, A y) { if (!eq(x, y)) { throw fail((nempty(msg) ? msg + ": " : "") + "expected: " + x + ", got: " + y); } else print("OK" + (empty(msg) ? "" : " " + msg) + ": " + (x)); return y; } static public void assertFalseVerbose(Object o) { assertEqualsVerbose(false, o); } static public void assertFalseVerbose(String msg, Object o) { assertEqualsVerbose(msg, false, o); } static public boolean contains(Collection c, Object o) { return c != null && c.contains(o); } static public boolean contains(Iterable it, Object a) { if (it != null) for (Object o : it) if (eq(a, o)) return true; return false; } static public boolean contains(Object[] x, Object o) { if (x != null) for (Object a : x) if (eq(a, o)) return true; return false; } static public boolean contains(String s, char c) { return s != null && s.indexOf(c) >= 0; } static public boolean contains(String s, String b) { return s != null && s.indexOf(b) >= 0; } static public boolean contains(BitSet bs, int i) { return bs != null && bs.get(i); } static public boolean contains(Rect r, Pt p) { return rectContains(r, p); } static public void assertContainsAll(Collection a, Collection b) { for (var x : unnullForIteration(b)) if (!contains(a, x)) throw fail("Collection doesn't contain " + x + ": " + str_shorten(a)); } static public A printQuoted(A a) { return printQuoted("", a); } static public A printQuoted(String prefix, A a) { return printQuote(prefix, a); } static public A pnlReversed(A l) { return pnlReversed("", l); } static public A pnlReversed(String prefix, A l) { int i = l(l); if (l != null) for (Object a : reversed(l)) print(prefix + (i--) + ". " + str(a)); return l; } static public List takeFirst(List l, int n) { return l(l) <= n ? l : newSubListOrSame(l, 0, n); } static public List takeFirst(int n, List l) { return takeFirst(l, n); } static public String takeFirst(int n, String s) { return substring(s, 0, n); } static public String takeFirst(String s, int n) { return substring(s, 0, n); } static public CharSequence takeFirst(int n, CharSequence s) { return subCharSequence(s, 0, n); } static public List takeFirst(int n, Iterator it) { if (it == null) return null; List l = new ArrayList(); for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) { if (it.hasNext()) l.add(it.next()); else break; } return l; } static public List takeFirst(int n, Iterable i) { if (i == null) return null; return i == null ? null : takeFirst(n, i.iterator()); } static public List takeFirst(int n, IterableIterator i) { return takeFirst(n, (Iterator) i); } static public int[] takeFirst(int n, int[] a) { return takeFirstOfIntArray(n, a); } static public short[] takeFirst(int n, short[] a) { return takeFirstOfShortArray(n, a); } static public byte[] takeFirst(int n, byte[] a) { return takeFirstOfByteArray(n, a); } static public byte[] takeFirst(byte[] a, int n) { return takeFirstOfByteArray(n, a); } static public double[] takeFirst(int n, double[] a) { return takeFirstOfDoubleArray(n, a); } static public double[] takeFirst(double[] a, int n) { return takeFirstOfDoubleArray(n, a); } static public A assertEquals(Object x, A y) { return assertEquals("", x, y); } static public A assertEquals(String msg, Object x, A y) { if (assertVerbose()) return assertEqualsVerbose(msg, x, y); if (!(x == null ? y == null : x.equals(y))) throw fail((msg != null ? msg + ": " : "") + y + " != " + x); return y; } static public int indexOf(List l, A a, int startIndex) { if (l == null) return -1; int n = l(l); for (int i = startIndex; i < n; i++) if (eq(l.get(i), a)) return i; return -1; } static public int indexOf(List l, int startIndex, A a) { return indexOf(l, a, startIndex); } static public int indexOf(List l, A a) { if (l == null) return -1; return l.indexOf(a); } static public int indexOf(String a, String b) { return a == null || b == null ? -1 : a.indexOf(b); } static public int indexOf(String a, String b, int i) { return a == null || b == null ? -1 : a.indexOf(b, i); } static public int indexOf(String a, char b) { return a == null ? -1 : a.indexOf(b); } static public int indexOf(String a, int i, char b) { return indexOf(a, b, i); } static public int indexOf(String a, char b, int i) { return a == null ? -1 : a.indexOf(b, i); } static public int indexOf(String a, int i, String b) { return a == null || b == null ? -1 : a.indexOf(b, i); } static public int indexOf(A[] x, A a) { int n = l(x); for (int i = 0; i < n; i++) if (eq(x[i], a)) return i; return -1; } static public int indexOf(Iterable l, A a) { if (l == null) return -1; int i = 0; for (A x : l) { if (eq(x, a)) return i; i++; } return -1; } static volatile public StringBuffer local_log = new StringBuffer(); static public boolean printAlsoToSystemOut = true; static volatile public Appendable print_log = local_log; static volatile public int print_log_max = 1024 * 1024; static volatile public int local_log_max = 100 * 1024; static public boolean print_silent = false; static public Object print_byThread_lock = new Object(); static volatile public ThreadLocal print_byThread; static volatile public Object print_allThreads; static volatile public Object print_preprocess; static public void print() { print(""); } static public A print(String s, A o) { print(combinePrintParameters(s, o)); return o; } static public A print(A o) { ping_okInCleanUp(); if (print_silent) return o; String s = o + "\n"; print_noNewLine(s); return o; } static public void print_noNewLine(String s) { try { Object f = getThreadLocal(print_byThread_dontCreate()); if (f == null) f = print_allThreads; if (f != null) if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s))) return; } catch (Throwable e) { System.out.println(getStackTrace(e)); } print_raw(s); } static public void print_raw(String s) { if (print_preprocess != null) s = (String) callF(print_preprocess, s); s = fixNewLines(s); Appendable loc = local_log; Appendable buf = print_log; int loc_max = print_log_max; if (buf != loc && buf != null) { print_append(buf, s, print_log_max); loc_max = local_log_max; } if (loc != null) print_append(loc, s, loc_max); if (printAlsoToSystemOut) System.out.print(s); vmBus_send("printed", mc(), s); } static public void print_autoRotate() { } static public void assertSetsEqual(Collection l1, Collection l2) { assertSetsEqual("", l1, l2); } static public void assertSetsEqual(String msg, Collection l1, Collection l2) { assertListsEqual(msg, asList(asHashSet(l1)), asList(asHashSet(l2))); } static public List listPlus(Collection l, A... more) { return concatLists(l, asList(more)); } static public String getStackTrace(Throwable throwable) { lastException(throwable); return getStackTrace_noRecord(throwable); } static public String getStackTrace_noRecord(Throwable throwable) { StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); return hideCredentials(writer.toString()); } static public String getStackTrace() { return getStackTrace_noRecord(new Throwable()); } static public String getStackTrace(String msg) { return getStackTrace_noRecord(new Throwable(msg)); } static public Class __javax; static public Class getJavaX() { try { return __javax; } catch (Exception __e) { throw rethrow(__e); } } static public void __setJavaX(Class j) { __javax = j; _onJavaXSet(); } static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) { return print_byThread().get() == null ? tempInterceptPrint(f) : null; } static public Object defaultDefaultClassFinder() { return new F1() { public Class get(String name) { name = replacePrefix("main$main$", "main$", name); Class c = get2(name); return c; } public Class get2(String name) { if (eq(name, "
")) return mc(); { Class c = findClass_fullName(name); if (c != null) return c; } if (startsWithAny(name, "loadableUtils.utils$", "main$", mcDollar())) for (String pkg : ll("loadableUtils.utils$", mcDollar())) { String newName = pkg + afterDollar(name); { Class c = findClass_fullName(newName); if (c != null) return c; } } return null; } }; } static public A assertNotNull(A a) { assertTrue(a != null); return a; } static public A assertNotNull(String msg, A a) { assertTrue(msg, a != null); return a; } static public boolean nempty(Collection c) { return !empty(c); } static public boolean nempty(CharSequence s) { return !empty(s); } static public boolean nempty(Object[] o) { return !empty(o); } static public boolean nempty(byte[] o) { return !empty(o); } static public boolean nempty(int[] o) { return !empty(o); } static public boolean nempty(BitSet bs) { return !empty(bs); } static public boolean nempty(Map m) { return !empty(m); } static public boolean nempty(Iterator i) { return i != null && i.hasNext(); } static public boolean nempty(MultiMap mm) { return mm != null && !mm.isEmpty(); } static public boolean nempty(Object o) { return !empty(o); } static public boolean nempty(IntRange r) { return !empty(r); } static public boolean nempty(Rect r) { return r != null && r.w != 0 && r.h != 0; } static public boolean nempty(MultiSet ms) { return ms != null && !ms.isEmpty(); } static public String programIDWithCase() { return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID(); } static public String programID() { return getProgramID(); } static public String programID(Object o) { return getProgramID(o); } static public Object rcall(String method, Object o, Object... args) { return call_withVarargs(o, method, args); } static public Runnable _topLevelErrorHandling(Runnable r) { if (r == null) return null; Object info = _threadInfo(); Object mod = dm_current_generic(); if (info == null && mod == null) return r; return new Runnable() { public void run() { try { AutoCloseable __1 = (AutoCloseable) (rcall("enter", mod)); try { _threadInheritInfo(info); r.run(); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp (AutoCloseable) rcall enter(mod);\r\n _threadInheritInfo(info);\r\n r...."; } }; } static public RuntimeException fail() { throw new RuntimeException("fail"); } static public RuntimeException fail(Throwable e) { throw asRuntimeException(e); } static public RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); } static public RuntimeException fail(Object... objects) { throw new Fail(objects); } static public RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); } static public RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); } static public Object callF(Object f, Object... args) { try { if (f instanceof String) return callMC((String) f, args); return x30_util.callF(f, args); } catch (Exception __e) { throw rethrow(__e); } } static public A callF(F0 f) { return f == null ? null : f.get(); } static public A callF(IF0 f) { return f == null ? null : f.get(); } static public B callF(F1 f, A a) { return f == null ? null : f.get(a); } static public B callF(IF1 f, A a) { return f == null ? null : f.get(a); } static public void callF(VF1 f, A a) { if (f != null) f.get(a); } static public Object callMC(String method, Object... args) { return call(mc(), method, args); } static public Object call(Object o) { return callF(o); } static public Object call(Object o, String method, Object... args) { return call_withVarargs(o, method, args); } static public WeakReference weakRef(A a) { return newWeakReference(a); } static public Class mc() { return main.class; } static public boolean eq(Object a, Object b) { return a == b || a != null && b != null && a.equals(b); } static public boolean eq(Symbol a, String b) { return eq(str(a), b); } static public boolean empty(Collection c) { return c == null || c.isEmpty(); } static public boolean empty(Iterable c) { return c == null || !c.iterator().hasNext(); } static public boolean empty(CharSequence s) { return s == null || s.length() == 0; } static public boolean empty(Map map) { return map == null || map.isEmpty(); } static public boolean empty(Object[] o) { return o == null || o.length == 0; } static public boolean empty(BitSet bs) { return bs == null || bs.isEmpty(); } static public boolean empty(Object o) { if (o instanceof Collection) return empty((Collection) o); if (o instanceof String) return empty((String) o); if (o instanceof Map) return empty((Map) o); if (o instanceof Object[]) return empty((Object[]) o); if (o instanceof byte[]) return empty((byte[]) o); if (o == null) return true; throw fail("unknown type for 'empty': " + getType(o)); } static public boolean empty(Iterator i) { return i == null || !i.hasNext(); } static public boolean empty(double[] a) { return a == null || a.length == 0; } static public boolean empty(float[] a) { return a == null || a.length == 0; } static public boolean empty(int[] a) { return a == null || a.length == 0; } static public boolean empty(long[] a) { return a == null || a.length == 0; } static public boolean empty(byte[] a) { return a == null || a.length == 0; } static public boolean empty(short[] a) { return a == null || a.length == 0; } static public boolean empty(MultiSet ms) { return ms == null || ms.isEmpty(); } static public boolean empty(MultiMap mm) { return mm == null || mm.isEmpty(); } static public boolean empty(File f) { return getFileSize(f) == 0; } static public boolean empty(IntRange r) { return r == null || r.empty(); } static public boolean empty(Rect r) { return !(r != null && r.w != 0 && r.h != 0); } static public String appendColonIfNempty(String s) { return empty(s) ? "" : s + ": "; } static public boolean rectContains(int x1, int y1, int w, int h, Pt p) { return p.x >= x1 && p.y >= y1 && p.x < x1 + w && p.y < y1 + h; } static public boolean rectContains(Rect a, Rect b) { return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2(); } static public boolean rectContains(Rect a, Rectangle b) { return rectContains(a, toRect(b)); } static public boolean rectContains(Rect a, int x, int y) { return a != null && a.contains(x, y); } static public boolean rectContains(Rect a, Pt p) { return a != null && p != null && a.contains(p); } static public String unnullForIteration(String s) { return s == null ? "" : s; } static public Collection unnullForIteration(Collection l) { return l == null ? immutableEmptyList() : l; } static public List unnullForIteration(List l) { return l == null ? immutableEmptyList() : l; } static public int[] unnullForIteration(int[] l) { return l == null ? emptyIntArray() : l; } static public char[] unnullForIteration(char[] l) { return l == null ? emptyCharArray() : l; } static public double[] unnullForIteration(double[] l) { return l == null ? emptyDoubleArray() : l; } static public short[] unnullForIteration(short[] l) { return l == null ? emptyShortArray() : l; } static public Map unnullForIteration(Map l) { return l == null ? immutableEmptyMap() : l; } static public Iterable unnullForIteration(Iterable i) { return i == null ? immutableEmptyList() : i; } static public A[] unnullForIteration(A[] a) { return a == null ? (A[]) emptyObjectArray() : a; } static public BitSet unnullForIteration(BitSet b) { return b == null ? new BitSet() : b; } static public Pt unnullForIteration(Pt p) { return p == null ? new Pt() : p; } static public Symbol unnullForIteration(Symbol s) { return s == null ? emptySymbol() : s; } static public Pair unnullForIteration(Pair p) { return p != null ? p : new Pair(null, null); } static public long unnullForIteration(Long l) { return l == null ? 0L : l; } static public String str_shorten(Object o) { return shorten_str(o); } static public String str_shorten(Object o, int max) { return shorten_str(o, max); } static public String str_shorten(int max, Object o) { return shorten_str(max, o); } static public A printQuote(A a) { return printQuote("", a); } static public A printQuote(String prefix, A a) { print(prefix, quote(a)); return a; } static public List reversed(Iterable l) { return reversedList(l); } static public List reversed(A[] l) { return reversedList(asList(l)); } static public String reversed(String s) { return reversedString(s); } static public String str(Object o) { return o == null ? "null" : o.toString(); } static public String str(char[] c) { return new String(c); } static public String str(char[] c, int offset, int count) { return new String(c, offset, count); } static public List newSubListOrSame(List l, int startIndex) { return newSubListOrSame(l, startIndex, l(l)); } static public List newSubListOrSame(List l, int startIndex, int endIndex) { if (l == null) return null; int n = l(l); startIndex = max(0, startIndex); endIndex = min(n, endIndex); if (startIndex >= endIndex) return ll(); if (startIndex == 0 && endIndex == n) return l; return cloneList(l.subList(startIndex, endIndex)); } static public List newSubListOrSame(List l, IntRange r) { return newSubListOrSame(l, r.start, r.end); } static public String substring(String s, int x) { return substring(s, x, strL(s)); } static public String substring(String s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; int n = s.length(); if (y < x) y = x; if (y > n) y = n; if (x >= y) return ""; return s.substring(x, y); } static public String substring(String s, IntRange r) { return r == null ? null : substring(s, r.start, r.end); } static public String substring(String s, CharSequence l) { return substring(s, lCharSequence(l)); } static public CharSequence subCharSequence(CharSequence s, int x) { return subCharSequence(s, x, s == null ? 0 : s.length()); } static public CharSequence subCharSequence(CharSequence 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.subSequence(x, y); } static public int[] takeFirstOfIntArray(int[] b, int n) { return subIntArray(b, 0, n); } static public int[] takeFirstOfIntArray(int n, int[] b) { return takeFirstOfIntArray(b, n); } static public short[] takeFirstOfShortArray(short[] b, int n) { return subShortArray(b, 0, n); } static public short[] takeFirstOfShortArray(int n, short[] b) { return takeFirstOfShortArray(b, n); } static public byte[] takeFirstOfByteArray(byte[] b, int n) { return subByteArray(b, 0, n); } static public byte[] takeFirstOfByteArray(int n, byte[] b) { return takeFirstOfByteArray(b, n); } static public double[] takeFirstOfDoubleArray(double[] b, int n) { return subDoubleArray(b, 0, n); } static public double[] takeFirstOfDoubleArray(int n, double[] b) { return takeFirstOfDoubleArray(b, n); } static public ThreadLocal assertVerbose_value = new ThreadLocal(); static public void assertVerbose(boolean b) { assertVerbose_value.set(b); } static public boolean assertVerbose() { return isTrue(assertVerbose_value.get()); } static public String nullIfEmpty(String s) { return isEmpty(s) ? null : s; } static public Map nullIfEmpty(Map map) { return isEmpty(map) ? null : map; } static public List nullIfEmpty(List l) { return isEmpty(l) ? null : l; } static public String combinePrintParameters(String s, Object o) { return (endsWithLetterOrDigit(s) ? s + ": " : s) + o; } static public void ping_okInCleanUp() { if (ping_pauseAll || ping_anyActions) ping_impl(true); } static public Object getThreadLocal(Object o, String name) { ThreadLocal t = (ThreadLocal) (getOpt(o, name)); return t != null ? t.get() : null; } static public A getThreadLocal(ThreadLocal tl) { return tl == null ? null : tl.get(); } static public A getThreadLocal(ThreadLocal tl, A defaultValue) { return or(getThreadLocal(tl), defaultValue); } static public ThreadLocal print_byThread_dontCreate() { return print_byThread; } static public boolean isFalse(Object o) { return eq(false, o); } static public String fixNewLines(String s) { int i = indexOf(s, '\r'); if (i < 0) return s; int l = s.length(); StringBuilder out = new StringBuilder(l); out.append(s, 0, i); for (; i < l; i++) { char c = s.charAt(i); if (c != '\r') out.append(c); else { out.append('\n'); if (i + 1 < l && s.charAt(i + 1) == '\n') ++i; } } return out.toString(); } static public void print_append(Appendable buf, String s, int max) { try { synchronized (buf) { buf.append(s); if (buf instanceof StringBuffer) rotateStringBuffer(((StringBuffer) buf), max); else if (buf instanceof StringBuilder) rotateStringBuilder(((StringBuilder) buf), max); } } catch (Exception __e) { throw rethrow(__e); } } static public void vmBus_send(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg); pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg); } static public void vmBus_send(String msg) { vmBus_send(msg, (Object) null); } static public void assertListsEqual(List l1, List l2) { assertListsEqual("", l1, l2); } static public void assertListsEqual(String msg, List l1, List l2) { if (l(l1) != l(l2)) throw fail("Different size: " + l(l1) + "/" + l(l2)); int iDiff = indexOfDifference(l1, l2); if (iDiff < 0) print(msg, "OK (" + l(l1) + ")"); else throw fail(prependWithColonSpace(msg) + "Error in element " + iDiff + "/" + l(l1) + " (" + get(l1, iDiff) + "/" + get(l2, iDiff) + ")"); } static public ArrayList asList(A[] a) { return a == null ? new ArrayList() : new ArrayList(Arrays.asList(a)); } static public ArrayList asList(int[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (int i : a) l.add(i); return l; } static public ArrayList asList(long[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (long i : a) l.add(i); return l; } static public ArrayList asList(float[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (float i : a) l.add(i); return l; } static public ArrayList asList(double[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (double i : a) l.add(i); return l; } static public ArrayList asList(short[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (short i : a) l.add(i); return l; } static public ArrayList asList(Iterator it) { ArrayList l = new ArrayList(); if (it != null) while (it.hasNext()) l.add(it.next()); return l; } static public ArrayList asList(IterableIterator s) { return asList((Iterator) s); } static public 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 public ArrayList asList(Enumeration e) { ArrayList l = new ArrayList(); if (e != null) while (e.hasMoreElements()) l.add(e.nextElement()); return l; } static public List asList(Pair p) { return p == null ? null : ll(p.a, p.b); } static public HashSet asHashSet(Collection c) { synchronized (collectionMutex(c)) { return new HashSet(c); } } static public HashSet asHashSet(A[] a) { return a == null ? null : new HashSet(Arrays.asList(a)); } static public List concatLists(Iterable... lists) { List l = new ArrayList(); if (lists != null) for (Iterable list : lists) addAll(l, list); return l; } static public List concatLists(Collection> lists) { List l = new ArrayList(); if (lists != null) for (Iterable list : lists) addAll(l, list); return l; } static volatile public PersistableThrowable lastException_lastException; static public PersistableThrowable lastException() { return lastException_lastException; } static public void lastException(Throwable e) { lastException_lastException = persistableThrowable(e); } static public String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); } static public String hideCredentials(String url) { try { if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url))) return url; } catch (Throwable e) { print("HideCredentials", e); } return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2="); } static public String hideCredentials(Object o) { return hideCredentials(str(o)); } static public void _onJavaXSet() { } static public ThreadLocal print_byThread() { synchronized (print_byThread_lock) { if (print_byThread == null) print_byThread = new ThreadLocal(); } return print_byThread; } static public AutoCloseable tempInterceptPrint(F1 f) { return tempSetThreadLocal(print_byThread(), f); } static public String replacePrefix(String prefix, String replacement, String s) { if (!startsWith(s, prefix)) return s; return replacement + substring(s, l(prefix)); } static public Object get2(Object o, String field1, String field2) { return get(get(o, field1), field2); } static public boolean startsWithAny(String a, Collection b) { for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix)) return true; return false; } static public boolean startsWithAny(String a, String... b) { if (b != null) for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix)) return true; return false; } static public boolean startsWithAny(String a, Collection b, Matches m) { for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix, m)) return true; return false; } static public String mcDollar() { return mcName() + "$"; } static public String afterDollar(String s) { return substring(s, smartIndexOf(s, '$') + 1); } static volatile public String caseID_caseID; static public String caseID() { return caseID_caseID; } static public void caseID(String id) { caseID_caseID = id; } static public String quoteUnlessIdentifierOrInteger(String s) { return quoteIfNotIdentifierOrInteger(s); } static public String getProgramID() { return nempty(programID) ? formatSnippetIDOpt(programID) : "?"; } static public String getProgramID(Class c) { String id = (String) getOpt(c, "programID"); if (nempty(id)) return formatSnippetID(id); return "?"; } static public String getProgramID(Object o) { return getProgramID(getMainClass(o)); } static public Object call_withVarargs(Object o, String methodName, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findStaticMethod(methodName, args); if (me != null) return invokeMethod(me, null, args); List methods = cache.cache.get(methodName); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } { if (!(isStaticMethod(m))) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, null, newArgs); } throw fail("Method " + c.getName() + "." + methodName + "(" + joinWithComma(classNames(args)) + ") not found"); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me != null) return invokeMethod(me, o, args); List methods = cache.cache.get(methodName); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, o, newArgs); } throw fail("Method " + c.getName() + "." + methodName + "(" + joinWithComma(classNames(args)) + ") not found"); } } catch (Exception __e) { throw rethrow(__e); } } static public RuntimeException asRuntimeException(Throwable t) { if (t instanceof Error) _handleError((Error) t); return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } static public WeakReference newWeakReference(A a) { return a == null ? null : new WeakReference(a); } static public String getType(Object o) { return getClassName(o); } static public long getFileSize(String path) { return path == null ? 0 : new File(path).length(); } static public long getFileSize(File f) { return f == null ? 0 : f.length(); } static public Rect toRect(Rectangle r) { return r == null ? null : new Rect(r); } static public Rect toRect(RectangularShape r) { return r == null ? null : toRect(r.getBounds()); } static public Rect toRect(DoubleRect r) { if (r == null) return null; int x = iround(r.x), y = iround(r.y); return new Rect(x, y, iround(r.x2()) - x, iround(r.y2()) - y); } static public Rect toRect(Rect r) { return r; } static public List immutableEmptyList() { return Collections.emptyList(); } static public int[] emptyIntArray_a = new int[0]; static public int[] emptyIntArray() { return emptyIntArray_a; } static public char[] emptyCharArray = new char[0]; static public char[] emptyCharArray() { return emptyCharArray; } static public double[] emptyDoubleArray = new double[0]; static public double[] emptyDoubleArray() { return emptyDoubleArray; } static public short[] emptyShortArray = new short[0]; static public short[] emptyShortArray() { return emptyShortArray; } static public Map immutableEmptyMap() { return Collections.emptyMap(); } static public Object[] emptyObjectArray_a = new Object[0]; static public Object[] emptyObjectArray() { return emptyObjectArray_a; } static public Symbol emptySymbol_value; static public Symbol emptySymbol() { if (emptySymbol_value == null) emptySymbol_value = symbol(""); return emptySymbol_value; } static public String shorten_str(Object o) { return shorten(str(o)); } static public String shorten_str(Object o, int max) { return shorten(str(o), max); } static public String shorten_str(int max, Object o) { return shorten_str(o, max); } static public String quote(Object o) { if (o == null) return "null"; return quote(str(o)); } static public 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 public 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 == '\t') out.append("\\t"); else if (c == '\0') out.append("\\0"); else out.append(c); } out.append('"'); } static public List reversedList(Iterable l) { List x = cloneList(l); Collections.reverse(x); return x; } static public String reversedString(String s) { return reverseString(s); } static public int max(int a, int b) { return Math.max(a, b); } static public int max(int a, int b, int c) { return max(max(a, b), c); } static public long max(int a, long b) { return Math.max((long) a, b); } static public long max(long a, long b) { return Math.max(a, b); } static public double max(int a, double b) { return Math.max((double) a, b); } static public float max(float a, float b) { return Math.max(a, b); } static public double max(double a, double b) { return Math.max(a, b); } static public int max(Collection c) { int x = Integer.MIN_VALUE; for (int i : c) x = max(x, i); return x; } static public 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 public 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 public byte max(byte[] c) { byte x = -128; for (byte d : c) if (d > x) x = d; return x; } static public short max(short[] c) { short x = -0x8000; for (short d : c) if (d > x) x = d; return x; } static public int max(int[] c) { int x = Integer.MIN_VALUE; for (int d : c) if (d > x) x = d; return x; } static public > A max(A a, A b) { return cmp(a, b) >= 0 ? a : b; } static public int min(int a, int b) { return Math.min(a, b); } static public long min(long a, long b) { return Math.min(a, b); } static public float min(float a, float b) { return Math.min(a, b); } static public float min(float a, float b, float c) { return min(min(a, b), c); } static public double min(double a, double b) { return Math.min(a, b); } static public double min(double[] c) { double x = Double.MAX_VALUE; for (double d : c) x = Math.min(x, d); return x; } static public float min(float[] c) { float x = Float.MAX_VALUE; for (float d : c) x = Math.min(x, d); return x; } static public byte min(byte[] c) { byte x = 127; for (byte d : c) if (d < x) x = d; return x; } static public short min(short[] c) { short x = 0x7FFF; for (short d : c) if (d < x) x = d; return x; } static public int min(int[] c) { int x = Integer.MAX_VALUE; for (int d : c) if (d < x) x = d; return x; } static public ArrayList cloneList(Iterable l) { return l instanceof Collection ? cloneList((Collection) l) : asList(l); } static public ArrayList cloneList(Collection l) { if (l == null) return new ArrayList(); synchronized (collectionMutex(l)) { return new ArrayList(l); } } static public int strL(String s) { return s == null ? 0 : s.length(); } static public int lCharSequence(CharSequence s) { return s == null ? 0 : s.length(); } static public int[] subIntArray(int[] b, int start) { return subIntArray(b, start, l(b)); } static public int[] subIntArray(int[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new int[0]; int[] x = new int[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public int[] subIntArray(int[] a, IntRange r) { return r == null ? null : subIntArray(a, r.start, r.end); } static public short[] subShortArray(short[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new short[0]; short[] x = new short[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public byte[] subByteArray(byte[] b, int start) { return subByteArray(b, start, l(b)); } static public byte[] subByteArray(byte[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new byte[0]; byte[] x = new byte[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public byte[] subByteArray(byte[] b, IntRange r) { return r == null ? null : subByteArray(b, r.start, r.end); } static public double[] subDoubleArray(double[] b, int start) { return subDoubleArray(b, start, l(b)); } static public double[] subDoubleArray(double[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new double[0]; double[] x = new double[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public boolean isEmpty(Collection c) { return c == null || c.isEmpty(); } static public boolean isEmpty(CharSequence s) { return s == null || s.length() == 0; } static public boolean isEmpty(Object[] a) { return a == null || a.length == 0; } static public boolean isEmpty(byte[] a) { return a == null || a.length == 0; } static public boolean isEmpty(Map map) { return map == null || map.isEmpty(); } static public boolean endsWithLetterOrDigit(String s) { return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1)); } static volatile public boolean ping_pauseAll = false; static public int ping_sleep = 100; static volatile public boolean ping_anyActions = false; static public Map ping_actions = newWeakHashMap(); static public ThreadLocal ping_isCleanUpThread = new ThreadLocal(); static public boolean ping() { newPing(); if (ping_pauseAll || ping_anyActions) ping_impl(true); return true; } static public boolean ping_impl(boolean okInCleanUp) { try { if (ping_pauseAll && !isAWTThread()) { do Thread.sleep(ping_sleep); while (ping_pauseAll); return true; } if (ping_anyActions) { if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get())) failIfUnlicensed(); Object action = null; synchronized (ping_actions) { if (!ping_actions.isEmpty()) { action = ping_actions.get(currentThread()); if (action instanceof Runnable) ping_actions.remove(currentThread()); if (ping_actions.isEmpty()) ping_anyActions = false; } } if (action instanceof Runnable) ((Runnable) action).run(); else if (eq(action, "cancelled")) throw fail("Thread cancelled."); } return false; } catch (Exception __e) { throw rethrow(__e); } } static public A or(A a, A b) { return a != null ? a : b; } static public void rotateStringBuffer(StringBuffer buf, int max) { try { if (buf == null) return; synchronized (buf) { if (buf.length() <= max) return; try { int newLength = max / 2; int ofs = buf.length() - newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } buf.trimToSize(); } } catch (Exception __e) { throw rethrow(__e); } } static public void rotateStringBuilder(StringBuilder buf, int max) { try { if (buf == null) return; synchronized (buf) { if (buf.length() <= max) return; try { int newLength = max / 2; int ofs = buf.length() - newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } buf.trimToSize(); } } catch (Exception __e) { throw rethrow(__e); } } static public Object vmBus_wrapArgs(Object... args) { return empty(args) ? null : l(args) == 1 ? args[0] : args; } static public void pcallFAll_minimalExceptionHandling(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) { ping(); pcallF_minimalExceptionHandling(f, args); } } static public void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) { while (it.hasNext()) { ping(); pcallF_minimalExceptionHandling(it.next(), args); } } static public Set vm_busListeners_live_cache; static public Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache; } static public Set vm_busListeners_live_load() { return vm_generalIdentityHashSet("busListeners"); } static public Map vm_busListenersByMessage_live_cache; static public Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache; } static public Map vm_busListenersByMessage_live_load() { return vm_generalHashMap("busListenersByMessage"); } static public int indexOfDifference(Iterable i1, Iterable i2) { var it1 = iterator(i1); var it2 = iterator(i2); int i = 0; while (true) { ping(); boolean a = it1.hasNext(), b = it2.hasNext(); if (a != b) return i; if (!a) return -1; A el1 = it1.next(); A el2 = it2.next(); if (!eq(el1, el2)) return i; ++i; } } static public String prependWithColonSpace(String s) { return appendColonIfNempty(s); } static public ArrayList emptyList() { return new ArrayList(); } static public ArrayList emptyList(int capacity) { return new ArrayList(max(0, capacity)); } static public ArrayList emptyList(Iterable l) { return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList(); } static public ArrayList emptyList(Object[] l) { return emptyList(l(l)); } static public ArrayList emptyList(Class c) { return new ArrayList(); } static public Object collectionMutex(List l) { return l; } static public Object collectionMutex(Object o) { if (o instanceof List) return o; String c = className(o); return o; } static public void addAll(Collection c, Iterable b) { if (c != null && b != null) for (A a : b) c.add(a); } static public boolean addAll(Collection c, Collection b) { return c != null && b != null && c.addAll(b); } static public boolean addAll(Collection c, B... b) { return c != null && b != null && c.addAll(Arrays.asList(b)); } static public Map addAll(Map a, Map b) { if (a != null && b != null) a.putAll(b); return a; } static public A addAll(A c, Collection components) { return addComponents(c, components); } static public A addAll(A c, Component... components) { return addComponents(c, components); } static public PersistableThrowable persistableThrowable(Throwable e) { return e == null ? null : new PersistableThrowable(e); } static public boolean startsWithOneOf(String s, String... l) { for (String x : l) if (startsWith(s, x)) return true; return false; } static public boolean startsWithOneOf(String s, Matches m, String... l) { for (String x : l) if (startsWith(s, x, m)) return true; return false; } static public boolean isAGIBlueDomain(String domain) { return domainIsUnder(domain, theAGIBlueDomain()); } static public String hostNameFromURL(String url) { try { return empty(url) ? null : new URL(url).getHost(); } catch (Exception __e) { throw rethrow(__e); } } static public 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 public boolean startsWith(String a, String b) { return a != null && a.startsWith(unnull(b)); } static public boolean startsWith(String a, char c) { return nemptyString(a) && a.charAt(0) == c; } static public boolean startsWith(String a, String b, Matches m) { if (!startsWith(a, b)) return false; if (m != null) m.m = new String[] { substring(a, strL(b)) }; return true; } static public boolean startsWith(List a, List b) { if (a == null || listL(b) > listL(a)) return false; for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i))) return false; return true; } static public String mcName() { return mc().getName(); } static public int smartIndexOf(String s, String sub, int i) { if (s == null) return 0; i = s.indexOf(sub, min(i, l(s))); return i >= 0 ? i : l(s); } static public int smartIndexOf(String s, int i, char c) { return smartIndexOf(s, c, i); } static public int smartIndexOf(String s, char c, int i) { if (s == null) return 0; i = s.indexOf(c, min(i, l(s))); return i >= 0 ? i : l(s); } static public int smartIndexOf(String s, String sub) { return smartIndexOf(s, sub, 0); } static public int smartIndexOf(String s, char c) { return smartIndexOf(s, c, 0); } static public int smartIndexOf(List l, A sub) { return smartIndexOf(l, sub, 0); } static public int smartIndexOf(List l, int start, A sub) { return smartIndexOf(l, sub, start); } static public int smartIndexOf(List l, A sub, int start) { int i = indexOf(l, sub, start); return i < 0 ? l(l) : i; } static public String quoteIfNotIdentifierOrInteger(String s) { if (s == null) return null; return isJavaIdentifier(s) || isInteger(s) ? s : quote(s); } static public String formatSnippetIDOpt(String s) { return isSnippetID(s) ? formatSnippetID(s) : s; } static public String formatSnippetID(String id) { return "#" + parseSnippetID(id); } static public String formatSnippetID(long id) { return "#" + id; } static public Class getMainClass() { return mc(); } static public Class getMainClass(Object o) { try { if (o == null) return null; if (o instanceof Class && eq(((Class) o).getName(), "x30")) return (Class) o; ClassLoader cl = (o instanceof Class ? (Class) o : o.getClass()).getClassLoader(); if (cl == null) return null; String name = mainClassNameForClassLoader(cl); return loadClassFromClassLoader_orNull(cl, name); } catch (Exception __e) { throw rethrow(__e); } } static final public Map callOpt_cache = newDangerousWeakHashMap(); static public Object callOpt_cached(Object o, String methodName, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me == null || (me.getModifiers() & Modifier.STATIC) == 0) return null; return invokeMethod(me, null, args); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me == null) return null; return invokeMethod(me, o, args); } } catch (Exception __e) { throw rethrow(__e); } } static public _MethodCache callOpt_getCache(Class c) { _MethodCache cache = callOpt_cache.get(c); if (cache == null) callOpt_cache.put(c, cache = new _MethodCache(c)); return cache; } static public Object invokeMethod(Method m, Object o, Object... args) { try { try { return m.invoke(o, args); } catch (InvocationTargetException e) { throw rethrow(getExceptionCause(e)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args))); } } catch (Exception __e) { throw rethrow(__e); } } static public boolean isStaticMethod(Method m) { return methodIsStatic(m); } static public Object[] massageArgsForVarArgsCall(Executable m, Object[] args) { Class[] types = m.getParameterTypes(); int n = types.length - 1, nArgs = args.length; if (nArgs < n) return null; for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i])) return null; Class varArgType = types[n].getComponentType(); for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType)) return null; Object[] newArgs = new Object[n + 1]; arraycopy(args, 0, newArgs, 0, n); int nVarArgs = nArgs - n; Object varArgs = Array.newInstance(varArgType, nVarArgs); for (int i = 0; i < nVarArgs; i++) Array.set(varArgs, i, args[n + i]); newArgs[n] = varArgs; return newArgs; } static public String joinWithComma(Collection c) { return join(", ", c); } static public String joinWithComma(Object... c) { return join(", ", c); } static public String joinWithComma(String... c) { return join(", ", c); } static public String joinWithComma(Pair p) { return p == null ? "" : joinWithComma(str(p.a), str(p.b)); } static public List classNames(Collection l) { return getClassNames(l); } static public List classNames(Object[] l) { return getClassNames(Arrays.asList(l)); } static public void _handleError(Error e) { call(javax(), "_handleError", e); } static public String getClassName(Object o) { return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName(); } static public int iround(double d) { return (int) Math.round(d); } static public int iround(Number n) { return iround(toDouble(n)); } static public WeakHasherMap symbol_map = new WeakHasherMap(new Hasher() { public int hashCode(Symbol symbol) { return symbol.text.hashCode(); } public boolean equals(Symbol a, Symbol b) { if (a == null) return b == null; return b != null && eq(a.text, b.text); } }); static public Symbol symbol(String s) { if (s == null) return null; synchronized (symbol_map) { Symbol symbol = new Symbol(s, true); Symbol existingSymbol = symbol_map.findKey(symbol); if (existingSymbol == null) symbol_map.put(existingSymbol = symbol, true); return existingSymbol; } } static public Symbol symbol(CharSequence s) { if (s == null) return null; if (s instanceof Symbol) return (Symbol) s; if (s instanceof String) return symbol((String) s); return symbol(str(s)); } static public Symbol symbol(Object o) { return symbol((CharSequence) o); } static public int shorten_default = 100; static public String shorten(CharSequence s) { return shorten(s, shorten_default); } static public String shorten(CharSequence s, int max) { return shorten(s, max, "..."); } static public String shorten(CharSequence s, int max, String shortener) { if (s == null) return ""; if (max < 0) return str(s); return s.length() <= max ? str(s) : subCharSequence(s, 0, min(s.length(), max - l(shortener))) + shortener; } static public String shorten(int max, CharSequence s) { return shorten(s, max); } static public String reverseString(String s) { return empty(s) ? s : new StringBuilder(s).reverse().toString(); } static public int cmp(Number a, Number b) { return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue()); } static public int cmp(double a, double b) { return a < b ? -1 : a == b ? 0 : 1; } static public int cmp(int a, int b) { return a < b ? -1 : a == b ? 0 : 1; } static public int cmp(long a, long b) { return a < b ? -1 : a == b ? 0 : 1; } static public int cmp(Object a, Object b) { if (a == null) return b == null ? 0 : -1; if (b == null) return 1; return ((Comparable) a).compareTo(b); } static public void newPing() { var tl = newPing_actionTL(); Runnable action = tl == null ? null : tl.get(); { if (action != null) action.run(); } } static public boolean isAWTThread() { if (isAndroid()) return false; if (isHeadless()) return false; return isAWTThread_awt(); } static public boolean isAWTThread_awt() { return SwingUtilities.isEventDispatchThread(); } static public void failIfUnlicensed() { assertTrue("license off", licensed()); } static public Thread currentThread() { return Thread.currentThread(); } static public Object pcallF_minimalExceptionHandling(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable e) { System.out.println(getStackTrace(e)); _storeException(e); } return null; } static public Iterator iterator(Iterable c) { return c == null ? emptyIterator() : c.iterator(); } static public String className(Object o) { return getClassName(o); } static public A addComponents(A c, Collection components) { if (nempty(components)) { swing(() -> { for (Component comp : components) c.add(comp); revalidate(c); }); } return c; } static public A addComponents(A c, Component... components) { return addComponents(c, asList(components)); } static public boolean domainIsUnder(String domain, String mainDomain) { return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain); } static public String theAGIBlueDomain() { return "agi.blue"; } static public A setThreadLocal(ThreadLocal tl, A value) { if (tl == null) return null; A old = tl.get(); tl.set(value); return old; } static public String unnull(String s) { return s == null ? "" : s; } static public Collection unnull(Collection l) { return l == null ? emptyList() : l; } static public List unnull(List l) { return l == null ? emptyList() : l; } static public int[] unnull(int[] l) { return l == null ? emptyIntArray() : l; } static public char[] unnull(char[] l) { return l == null ? emptyCharArray() : l; } static public double[] unnull(double[] l) { return l == null ? emptyDoubleArray() : l; } static public Map unnull(Map l) { return l == null ? emptyMap() : l; } static public Iterable unnull(Iterable i) { return i == null ? emptyList() : i; } static public A[] unnull(A[] a) { return a == null ? (A[]) emptyObjectArray() : a; } static public BitSet unnull(BitSet b) { return b == null ? new BitSet() : b; } static public Pt unnull(Pt p) { return p == null ? new Pt() : p; } static public Symbol unnull(Symbol s) { return s == null ? emptySymbol() : s; } static public Pair unnull(Pair p) { return p != null ? p : new Pair(null, null); } static public int unnull(Integer i) { return i == null ? 0 : i; } static public long unnull(Long l) { return l == null ? 0L : l; } static public double unnull(Double l) { return l == null ? 0.0 : l; } static public boolean nemptyString(String s) { return s != null && s.length() > 0; } static public int listL(Collection l) { return l == null ? 0 : l.size(); } static public boolean neq(Object a, Object b) { return !eq(a, b); } static public boolean isJavaIdentifier(String s) { if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0))) return false; for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i))) return false; return true; } static public boolean isInteger(String s) { int n = l(s); if (n == 0) return false; int i = 0; if (s.charAt(0) == '-') if (++i >= n) return false; while (i < n) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } public static boolean isSnippetID(String s) { try { parseSnippetID(s); return true; } catch (RuntimeException e) { return false; } } public static long parseSnippetID(String snippetID) { long id = Long.parseLong(shortenSnippetID(snippetID)); if (id == 0) throw fail("0 is not a snippet ID"); return id; } static public String mainClassNameForClassLoader(ClassLoader cl) { return or((String) callOpt(cl, "mainClassName"), "main"); } static public Class loadClassFromClassLoader_orNull(ClassLoader cl, String name) { try { return cl == null ? null : cl.loadClass(name); } catch (ClassNotFoundException e) { return null; } } static public Throwable getExceptionCause(Throwable e) { Throwable c = e.getCause(); return c != null ? c : e; } static public String joinWithSpace(Iterable c) { return join(" ", c); } static public String joinWithSpace(String... c) { return join(" ", c); } static public boolean methodIsStatic(Method m) { return (m.getModifiers() & Modifier.STATIC) != 0; } static public boolean argumentCompatibleWithType(Object arg, Class type) { return arg == null ? !type.isPrimitive() : isInstanceX(type, arg); } static public void arraycopy(Object[] a, Object[] b) { if (a != null && b != null) arraycopy(a, 0, b, 0, Math.min(a.length, b.length)); } static public void arraycopy(Object src, int srcPos, int destPos, int n) { arraycopy(src, srcPos, src, destPos, n); } static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) { if (n != 0) System.arraycopy(src, srcPos, dest, destPos, n); } public static String join(String glue, Iterable strings) { if (strings == null) return ""; if (strings instanceof Collection) { if (((Collection) strings).size() == 1) return str(first((Collection) strings)); } StringBuilder buf = new StringBuilder(); Iterator i = strings.iterator(); if (i.hasNext()) { buf.append(i.next()); while (i.hasNext()) buf.append(glue).append(i.next()); } return buf.toString(); } public static String join(String glue, String... strings) { return join(glue, Arrays.asList(strings)); } public static String join(String glue, Object... strings) { return join(glue, Arrays.asList(strings)); } static public String join(Iterable strings) { return join("", strings); } static public String join(Iterable strings, String glue) { return join(glue, strings); } public static String join(String[] strings) { return join("", strings); } static public String join(String glue, Pair p) { return p == null ? "" : str(p.a) + glue + str(p.b); } static public List getClassNames(Collection l) { List out = new ArrayList(); if (l != null) for (Object o : l) out.add(o == null ? null : getClassName(o)); return out; } static public double toDouble(Object o) { if (o instanceof Number) return ((Number) o).doubleValue(); if (o instanceof BigInteger) return ((BigInteger) o).doubleValue(); if (o instanceof String) return parseDouble((String) o); if (o == null) return 0.0; throw fail(o); } static public x30_pkg.x30_util.BetterThreadLocal newPing_actionTL; static public x30_pkg.x30_util.BetterThreadLocal newPing_actionTL() { if (newPing_actionTL == null) newPing_actionTL = vm_generalMap_getOrCreate("newPing_actionTL", () -> { Runnable value = (Runnable) (callF_gen(vm_generalMap_get("newPing_valueForNewThread"))); var tl = new x30_pkg.x30_util.BetterThreadLocal(); tl.set(value); return tl; }); return newPing_actionTL; } static volatile public boolean licensed_yes = true; static public boolean licensed() { if (!licensed_yes) return false; ping_okInCleanUp(); return true; } static public void licensed_off() { licensed_yes = false; } static public Object callFunction(Object f, Object... args) { return callF(f, args); } static public Throwable _storeException_value; static public void _storeException(Throwable e) { _storeException_value = e; } static public Iterator emptyIterator() { return Collections.emptyIterator(); } static public Object swing(Object f) { return swingAndWait(f); } static public void swing(Runnable f) { swingAndWait(f); } static public A swing(F0 f) { return (A) swingAndWait(f); } static public A swing(IF0 f) { return (A) swingAndWait(f); } static public A revalidate(final A c) { if (c == null || !c.isShowing()) return c; { swing(() -> { c.revalidate(); c.repaint(); }); } return c; } static public void revalidate(JFrame f) { revalidate((Component) f); } static public void revalidate(JInternalFrame f) { revalidate((Component) f); } static public boolean eqic(String a, String b) { if ((a == null) != (b == null)) return false; if (a == null) return true; return a.equalsIgnoreCase(b); } static public boolean eqic(Symbol a, Symbol b) { return eq(a, b); } static public boolean eqic(Symbol a, String b) { return eqic(asString(a), b); } static public boolean eqic(char a, char b) { if (a == b) return true; char u1 = Character.toUpperCase(a); char u2 = Character.toUpperCase(b); if (u1 == u2) return true; return Character.toLowerCase(u1) == Character.toLowerCase(u2); } static public boolean ewic(String a, String b) { return endsWithIgnoreCase(a, b); } static public boolean ewic(String a, String b, Matches m) { return endsWithIgnoreCase(a, b, m); } static public Map emptyMap() { return new HashMap(); } static public 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 public boolean isInstanceX(Class type, Object arg) { if (type == boolean.class) return arg instanceof Boolean; if (type == int.class) return arg instanceof Integer; if (type == long.class) return arg instanceof Long; if (type == float.class) return arg instanceof Float; if (type == short.class) return arg instanceof Short; if (type == char.class) return arg instanceof Character; if (type == byte.class) return arg instanceof Byte; if (type == double.class) return arg instanceof Double; return type.isInstance(arg); } static public Object first(Object list) { return first((Iterable) list); } static public A first(List list) { return empty(list) ? null : list.get(0); } static public A first(A[] bla) { return bla == null || bla.length == 0 ? null : bla[0]; } static public Pair first(Map map) { return mapEntryToPair(first(entrySet(map))); } static public Pair first(MultiMap mm) { if (mm == null) return null; var e = first(mm.data.entrySet()); if (e == null) return null; return pair(e.getKey(), first(e.getValue())); } static public A first(IterableIterator i) { return first((Iterator) i); } static public A first(Iterator i) { return i == null || !i.hasNext() ? null : i.next(); } static public A first(Iterable i) { if (i == null) return null; Iterator it = i.iterator(); return it.hasNext() ? it.next() : null; } static public Character first(String s) { return empty(s) ? null : s.charAt(0); } static public Character first(CharSequence s) { return empty(s) ? null : s.charAt(0); } static public A first(Pair p) { return p == null ? null : p.a; } static public A first(T3 t) { return t == null ? null : t.a; } static public Byte first(byte[] l) { return empty(l) ? null : l[0]; } static public A first(A[] l, IF1 pred) { return firstThat(l, pred); } static public A first(Iterable l, IF1 pred) { return firstThat(l, pred); } static public A first(IF1 pred, Iterable l) { return firstThat(pred, l); } static public double parseDouble(String s) { return empty(s) ? 0.0 : Double.parseDouble(s); } static public A vm_generalMap_getOrCreate(Object key, F0 create) { return vm_generalMap_getOrCreate(key, f0ToIF0(create)); } static public A vm_generalMap_getOrCreate(Object key, IF0 create) { Map generalMap = vm_generalMap(); if (generalMap == null) return null; synchronized (generalMap) { A a = (A) (vm_generalMap_get(key)); if (a == null) vm_generalMap_put(key, a = create == null ? null : create.get()); return a; } } static public A callF_gen(F0 f) { return f == null ? null : f.get(); } static public B callF_gen(F1 f, A a) { return f == null ? null : f.get(a); } static public A callF_gen(IF0 f) { return f == null ? null : f.get(); } static public B callF_gen(IF1 f, A a) { return f == null ? null : f.get(a); } static public B callF_gen(A a, IF1 f) { return f == null ? null : f.get(a); } static public C callF_gen(IF2 f, A a, B b) { return f == null ? null : f.get(a, b); } static public void callF_gen(VF1 f, A a) { { if (f != null) f.get(a); } } static public void callF_gen(A a, IVF1 f) { { if (f != null) f.get(a); } } static public void callF_gen(IVF1 f, A a) { { if (f != null) f.get(a); } } static public Object callF_gen(Runnable r) { { if (r != null) r.run(); } return null; } static public Object callF_gen(Object f, Object... args) { return callF(f, args); } static public Object vm_generalMap_get(Object key) { return vm_generalMap().get(key); } static public void swingAndWait(Runnable r) { try { if (isAWTThread()) r.run(); else EventQueue.invokeAndWait(addThreadInfoToRunnable(r)); } catch (Exception __e) { throw rethrow(__e); } } static public Object swingAndWait(final Object f) { if (isAWTThread()) return callF(f); else { final Var result = new Var(); swingAndWait(new Runnable() { public void run() { try { result.set(callF(f)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; } }); return result.get(); } } static public String asString(Object o) { return o == null ? null : o.toString(); } static public boolean endsWithIgnoreCase(String a, String b) { int la = l(a), lb = l(b); return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb); } static public boolean endsWithIgnoreCase(String a, String b, Matches m) { if (!endsWithIgnoreCase(a, b)) return false; if (m != null) m.m = new String[] { substring(a, 0, l(a) - l(b)) }; return true; } static public long parseLong(String s) { if (empty(s)) return 0; return Long.parseLong(dropSuffix("L", s)); } static public long parseLong(Object s) { return Long.parseLong((String) s); } static public Pair mapEntryToPair(Map.Entry e) { return e == null ? null : pair(e.getKey(), e.getValue()); } static public Set> entrySet(Map map) { return _entrySet(map); } static public Pair pair(A a, B b) { return new Pair(a, b); } static public Pair pair(A a) { return new Pair(a, a); } static public A firstThat(Iterable l, IF1 pred) { for (A a : unnullForIteration(l)) if (pred.get(a)) return a; return null; } static public A firstThat(A[] l, IF1 pred) { for (A a : unnullForIteration(l)) if (pred.get(a)) return a; return null; } static public A firstThat(IF1 pred, Iterable l) { return firstThat(l, pred); } static public A firstThat(IF1 pred, A[] l) { return firstThat(l, pred); } static public IF0 f0ToIF0(F0 f) { return f == null ? null : () -> f.get(); } static public Map vm_generalMap_map; static public Map vm_generalMap() { if (vm_generalMap_map == null) vm_generalMap_map = (Map) get(javax(), "generalMap"); return vm_generalMap_map; } static public Object vm_generalMap_put(Object key, Object value) { return mapPutOrRemove(vm_generalMap(), key, value); } static public Runnable addThreadInfoToRunnable(final Object r) { final Object info = _threadInfo(); return info == null ? asRunnable(r) : new Runnable() { public void run() { try { _inheritThreadInfo(info); callF(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_inheritThreadInfo(info); callF(r);"; } }; } static public boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) { return a != null && a.regionMatches(true, offsetA, b, offsetB, len); } static public String dropSuffix(String suffix, String s) { return nempty(suffix) && endsWith(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } static public Set> _entrySet(Map map) { return map == null ? Collections.EMPTY_SET : map.entrySet(); } static public 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 public Runnable asRunnable(Object o) { return toRunnable(o); } static public void _inheritThreadInfo(Object info) { _threadInheritInfo(info); } static public boolean endsWith(String a, String b) { return a != null && a.endsWith(b); } static public boolean endsWith(String a, char c) { return nempty(a) && lastChar(a) == c; } static public 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 public char lastChar(String s) { return empty(s) ? '\0' : s.charAt(l(s) - 1); } static public A[] dropLast(A[] a) { return dropLast(a, 1); } static public A[] dropLast(A[] a, int n) { if (a == null) return null; n = Math.min(n, a.length); A[] b = arrayOfSameType(a, a.length - n); System.arraycopy(a, 0, b, 0, b.length); return b; } static public List dropLast(List l) { return subList(l, 0, l(l) - 1); } static public List dropLast(int n, List l) { return subList(l, 0, l(l) - n); } static public List dropLast(Iterable l) { return dropLast(asList(l)); } static public String dropLast(String s) { return substring(s, 0, l(s) - 1); } static public String dropLast(String s, int n) { return substring(s, 0, l(s) - n); } static public String dropLast(int n, String s) { return dropLast(s, n); } static public A[] arrayOfSameType(A[] a, int n) { return newObjectArrayOfSameType(a, n); } static public List subList(List l, int startIndex) { return subList(l, startIndex, l(l)); } static public List subList(int startIndex, List l) { return subList(l, startIndex); } static public List subList(int startIndex, int endIndex, List l) { return subList(l, startIndex, endIndex); } static public List subList(List l, int startIndex, int endIndex) { if (l == null) return null; int n = l(l); startIndex = Math.max(0, startIndex); endIndex = Math.min(n, endIndex); if (startIndex > endIndex) return ll(); if (startIndex == 0 && endIndex == n) return l; return l.subList(startIndex, endIndex); } static public List subList(List l, IntRange r) { return subList(l, r.start, r.end); } static public A[] newObjectArrayOfSameType(A[] a) { return newObjectArrayOfSameType(a, a.length); } static public A[] newObjectArrayOfSameType(A[] a, int n) { return (A[]) Array.newInstance(a.getClass().getComponentType(), n); } final static public class _MethodCache { final public Class c; final public HashMap> cache = new HashMap(); public _MethodCache(Class c) { this.c = c; _init(); } public void _init() { Class _c = c; java.lang.Module myModule = getClass().getModule(); boolean anyHiddenClasses = false; while (_c != null) { boolean exported = classIsExportedTo(_c, myModule); if (!exported) anyHiddenClasses = true; else for (Method m : _c.getDeclaredMethods()) if ((anyHiddenClasses || !isAbstract(m)) && !reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); _c = _c.getSuperclass(); } for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if ((anyHiddenClasses || m.isDefault()) && !reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); } public 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); } } public Method findStaticMethod(String method, Object[] args) { try { List m = cache.get(method); if (m == null) return null; int n = m.size(); for (int i = 0; i < n; i++) { Method me = m.get(i); if (isStaticMethod(me) && call_checkArgs(me, args, false)) return me; } return null; } catch (Exception __e) { throw rethrow(__e); } } } static public class MultiMap { public Map> data = new HashMap>(); public int fullSize; public MultiMap() { } public MultiMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); } public MultiMap(MultiMap map) { putAll(map); } public MultiMap(Map> data) { this.data = data; } public void put(A key, B value) { synchronized (data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); list.add(value); ++fullSize; } } public void add(A key, B value) { put(key, value); } public void addAll(A key, Collection values) { putAll(key, values); } public void addAllIfNotThere(A key, Collection values) { synchronized (data) { for (B value : values) setPut(key, value); } } public void setPut(A key, B value) { synchronized (data) { if (!containsPair(key, value)) put(key, value); } } public boolean containsPair(A key, B value) { synchronized (data) { return get(key).contains(value); } } public void putAll(Collection keys, B value) { synchronized (data) { for (A key : unnullForIteration(keys)) put(key, value); } } public void putAll(A key, Collection values) { synchronized (data) { if (nempty(values)) getActual(key).addAll(values); } } public void putAll(Iterable> pairs) { synchronized (data) { for (Pair p : unnullForIteration(pairs)) put(p.a, p.b); } } public void removeAll(A key, Collection values) { synchronized (data) { for (B value : values) remove(key, value); } } public List get(A key) { synchronized (data) { List list = data.get(key); return list == null ? Collections.emptyList() : list; } } public List getOpt(A key) { synchronized (data) { return data.get(key); } } public List getAndClear(A key) { synchronized (data) { List l = cloneList(data.get(key)); remove(key); return l; } } public List getActual(A key) { synchronized (data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); return list; } } public void clean(A key) { synchronized (data) { List list = data.get(key); if (list != null && list.isEmpty()) { fullSize -= l(list); data.remove(key); } } } public Set keySet() { synchronized (data) { return data.keySet(); } } public Set keys() { synchronized (data) { return data.keySet(); } } public void remove(A key) { synchronized (data) { fullSize -= l(this.getOpt(key)); data.remove(key); } } final public void remove(Pair p) { removePair(p); } public void removePair(Pair p) { if (p != null) remove(p.a, p.b); } public void remove(A key, B value) { synchronized (data) { List list = data.get(key); if (list != null) { if (list.remove(value)) fullSize--; if (list.isEmpty()) data.remove(key); } } } public void clear() { synchronized (data) { data.clear(); } } public boolean containsKey(A key) { synchronized (data) { return data.containsKey(key); } } public B getFirst(A key) { synchronized (data) { List list = get(key); return list.isEmpty() ? null : list.get(0); } } public void addAll(MultiMap map) { putAll(map); } public void putAll(MultiMap map) { synchronized (data) { for (A key : map.keySet()) putAll(key, map.get(key)); } } public void putAll(Map map) { synchronized (data) { if (map != null) for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue()); } } final public int keyCount() { return keysSize(); } public int keysSize() { synchronized (data) { return l(data); } } final public int fullSize() { return size(); } public int size() { synchronized (data) { return fullSize; } } public List reverseGet(B b) { synchronized (data) { List l = new ArrayList(); for (A key : data.keySet()) if (data.get(key).contains(b)) l.add(key); return l; } } public Map> asMap() { synchronized (data) { return cloneMap(data); } } public boolean isEmpty() { synchronized (data) { return data.isEmpty(); } } public List _makeEmptyList() { return new ArrayList(); } public Collection> allLists() { synchronized (data) { return new ArrayList(data.values()); } } public Collection> values() { return allLists(); } public List allValues() { return concatLists(data.values()); } public Object mutex() { return data; } public String toString() { return "mm" + str(data); } } static public interface Hasher { public int hashCode(A a); public boolean equals(A a, A b); } static public class LeftArrowScriptAutoCompleter extends Meta implements IFieldsToList { public GazelleV_LeftArrowScriptParser parser; public LeftArrowScriptAutoCompleter() { } public LeftArrowScriptAutoCompleter(GazelleV_LeftArrowScriptParser parser) { this.parser = parser; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + parser + ")"; } public Object[] _fieldsToList() { return new Object[] { parser }; } public List tok; public CharInToken cursor; public String typedCharacters; public ScoredStringSearcher searcher; final public LeftArrowScriptAutoCompleter setG22utils(G22Utils g22utils) { return g22utils(g22utils); } public LeftArrowScriptAutoCompleter g22utils(G22Utils g22utils) { this.g22utils = g22utils; return this; } final public G22Utils getG22utils() { return g22utils(); } public G22Utils g22utils() { return g22utils; } public G22Utils g22utils; public TreeMap> knowVarsByTokenIdx = new TreeMap(); public LeftArrowScriptAutoCompleter(G22Utils g22utils, GazelleV_LeftArrowScriptParser parser) { this.parser = parser; this.g22utils = g22utils; } public void seekEnd(String text) { seek(text, l(text)); } public void seek(String text, int iChar) { if (tok != null) throw fail("Don't reuse instance"); parser.setText(text); parser.init(); tok = parser.tok; cursor = charIndexToCharInToken(tok, iChar); if (even(cursor.iTok) && cursor.iTok > 0 && cursor.iChar == 0) { cursor.iTok--; cursor.iChar = l(token()); } if (cursor.iTok > 1 && cursor.iChar == 0 && empty(space())) { cursor.iTok -= 2; cursor.iChar = l(token()); } typedCharacters = takeFirst(cursor.token(), cursor.iChar); parser.onKnownVarsSnapshot(knownVars -> knowVarsByTokenIdx.put(parser.tokIdx(), cloneKeys(knownVars))); try { parser.parse(); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } public String typedCharacters() { return typedCharacters; } public String space() { return get(tok, cursor.iTok - 1); } public String token() { return get(tok, cursor.iTok); } public String prevToken() { return get(tok, cursor.iTok - 2); } public boolean beginningOfCmd() { return eqOneOf(prevToken(), ";", "{", "}") || containsNewLine(space()); } public Collection getCompletions() { return searcher().get_transformListWithinScore(__1 -> stringsSortedByLength(__1)); } public ScoredStringSearcher searcher() { searcher = new ScoredStringSearcher(typedCharacters); searcher.uniquify(true); if (empty(typedCharacters)) searcher.returnAll = true; String prev = prevToken(); if (scaffoldingEnabled(this)) printVars("LeftArrowScriptAutoCompleter", "beginningOfCmd", beginningOfCmd(), "prev", prev, "cursor", cursor, "typedCharacters", typedCharacters, "globalClassNames", l(parser.globalClassNames())); if (beginningOfCmd() || !isIdentifier(prev) || eq(prev, "new")) addToSearcher(globalMethodNames()); addToSearcher(keys(parser.globalClassNames())); addToSearcher(predefinedExpressions()); Collection knownVars = floorValue(knowVarsByTokenIdx, cursor.iTok); addToSearcher(knownVars); return searcher; } public Collection predefinedExpressions() { return ll("true", "false", "null"); } transient public IF0> globalMethodNames; public Collection globalMethodNames() { return globalMethodNames != null ? globalMethodNames.get() : globalMethodNames_base(); } final public Collection globalMethodNames_fallback(IF0> _f) { return _f != null ? _f.get() : globalMethodNames_base(); } public Collection globalMethodNames_base() { return concatMap(__58 -> methodNames(__58), parser.functionContainers); } public void addToSearcher(String... l) { addToSearcher(asList(l)); } public void addToSearcher(Iterable l) { for (var s : unnullForIteration(l)) if (!eq(s, typedCharacters)) searcher.add(s); } } static public class Symbol implements CharSequence { public String text; public Symbol() { } public Symbol(String text, boolean dummy) { this.text = text; } public int hashCode() { return _hashCode(text); } public String toString() { return text; } public boolean equals(Object o) { return this == o; } public int length() { return text.length(); } public char charAt(int index) { return text.charAt(index); } public CharSequence subSequence(int start, int end) { return text.substring(start, end); } } static public class Var implements IVar, ISetter { public Var() { } public Var(A v) { this.v = v; } public A 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 void clear() { set(null); } public String toString() { return str(this.get()); } } static final public class WeakHasherMap extends AbstractMap implements Map { public Hasher hasher = null; final public boolean keyEquals(Object k1, Object k2) { return (hasher == null ? k1.equals(k2) : hasher.equals(k1, k2)); } final public int keyHashCode(Object k1) { return (hasher == null ? k1.hashCode() : hasher.hashCode(k1)); } final public WeakKey WeakKeyCreate(K k) { if (k == null) return null; else return new WeakKey(k); } final public WeakKey WeakKeyCreate(K k, ReferenceQueue q) { if (k == null) return null; else return new WeakKey(k, q); } final public class WeakKey extends WeakReference { public int hash; public WeakKey(K k) { super(k); hash = keyHashCode(k); } final public WeakKey create(K k) { if (k == null) return null; else return new WeakKey(k); } public WeakKey(K k, ReferenceQueue q) { super(k, q); hash = keyHashCode(k); } final public WeakKey create(K k, ReferenceQueue q) { if (k == null) return null; else return new WeakKey(k, q); } @Override public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; if (!(o.getClass().equals(WeakKey.class))) return false; Object t = this.get(); @SuppressWarnings("unchecked") Object u = ((WeakKey) o).get(); if ((t == null) || (u == null)) return false; if (t == u) return true; return keyEquals(t, u); } @Override public int hashCode() { return hash; } } public HashMap hash; public ReferenceQueue queue = new ReferenceQueue(); @SuppressWarnings("unchecked") final public void processQueue() { WeakKey wk; while ((wk = (WeakKey) queue.poll()) != null) { hash.remove(wk); } } public WeakHasherMap(int initialCapacity, float loadFactor) { hash = new HashMap(initialCapacity, loadFactor); } public WeakHasherMap(int initialCapacity) { hash = new HashMap(initialCapacity); } public WeakHasherMap() { hash = new HashMap(); } public WeakHasherMap(Hasher h) { hash = new HashMap(); hasher = h; } @Override public int size() { return entrySet().size(); } @Override public boolean isEmpty() { return entrySet().isEmpty(); } @Override public boolean containsKey(Object key) { @SuppressWarnings("unchecked") K kkey = (K) key; return hash.containsKey(WeakKeyCreate(kkey)); } @Override public V get(Object key) { @SuppressWarnings("unchecked") K kkey = (K) key; return hash.get(WeakKeyCreate(kkey)); } @Override public V put(K key, V value) { processQueue(); return hash.put(WeakKeyCreate(key, queue), value); } @Override public V remove(Object key) { processQueue(); @SuppressWarnings("unchecked") K kkey = (K) key; return hash.remove(WeakKeyCreate(kkey)); } @Override public void clear() { processQueue(); hash.clear(); } @SuppressWarnings("TypeParameterShadowing") final public class Entry implements Map.Entry { public Map.Entry ent; public K key; public Entry(Map.Entry ent, K key) { this.ent = ent; this.key = key; } @Override public K getKey() { return key; } @Override public V getValue() { return ent.getValue(); } @Override public V setValue(V value) { return ent.setValue(value); } final public boolean keyvalEquals(K o1, K o2) { return (o1 == null) ? (o2 == null) : keyEquals(o1, o2); } final public boolean valEquals(V o1, V o2) { return (o1 == null) ? (o2 == null) : o1.equals(o2); } @SuppressWarnings("NonOverridingEquals") public boolean equals(Map.Entry e) { return (keyvalEquals(key, e.getKey()) && valEquals(getValue(), e.getValue())); } @Override public int hashCode() { V v; return (((key == null) ? 0 : keyHashCode(key)) ^ (((v = getValue()) == null) ? 0 : v.hashCode())); } } final public class EntrySet extends AbstractSet> { public Set> hashEntrySet = hash.entrySet(); @Override public Iterator> iterator() { return new Iterator>() { public Iterator> hashIterator = hashEntrySet.iterator(); public Map.Entry next = null; @Override public boolean hasNext() { while (hashIterator.hasNext()) { Map.Entry ent = hashIterator.next(); WeakKey wk = ent.getKey(); K k = null; if ((wk != null) && ((k = wk.get()) == null)) { continue; } next = new Entry(ent, k); return true; } return false; } @Override public Map.Entry next() { if ((next == null) && !hasNext()) throw new NoSuchElementException(); Map.Entry e = next; next = null; return e; } @Override public void remove() { hashIterator.remove(); } }; } @Override public boolean isEmpty() { return !(iterator().hasNext()); } @Override public int size() { int j = 0; for (Iterator> i = iterator(); i.hasNext(); i.next()) j++; return j; } @Override public boolean remove(Object o) { processQueue(); if (!(o instanceof Map.Entry)) return false; @SuppressWarnings("unchecked") Map.Entry e = (Map.Entry) o; Object ev = e.getValue(); WeakKey wk = WeakKeyCreate(e.getKey()); Object hv = hash.get(wk); if ((hv == null) ? ((ev == null) && hash.containsKey(wk)) : hv.equals(ev)) { hash.remove(wk); return true; } return false; } @Override public int hashCode() { int h = 0; for (Iterator> i = hashEntrySet.iterator(); i.hasNext(); ) { Map.Entry ent = i.next(); WeakKey wk = ent.getKey(); Object v; if (wk == null) continue; h += (wk.hashCode() ^ (((v = ent.getValue()) == null) ? 0 : v.hashCode())); } return h; } } public Set> entrySet = null; @Override public Set> entrySet() { if (entrySet == null) entrySet = new EntrySet(); return entrySet; } public K findKey(Object key) { processQueue(); K kkey = (K) key; WeakKey wkey = WeakKeyCreate(kkey); WeakKey found = hashMap_findKey(hash, wkey); return found == null ? null : found.get(); } } static public class BetterThread extends Thread { public Runnable target; public BetterThread(Runnable target) { this.target = target; _created(); } public BetterThread(Runnable target, String name) { super(name); this.target = target; _created(); } public void _created() { vmBus_send("threadCreated", this); } public void run() { try { try { vmBus_send("threadStarted", this); if (target != null) target.run(); } finally { vmBus_send("threadEnded", this); } } catch (Exception __e) { throw rethrow(__e); } } public Runnable getTarget() { return target; } } static public class GazelleV_LeftArrowScriptParser extends SimpleLeftToRightParser { final public GazelleV_LeftArrowScriptParser setG22utils(G22Utils g22utils) { return g22utils(g22utils); } public GazelleV_LeftArrowScriptParser g22utils(G22Utils g22utils) { this.g22utils = g22utils; return this; } final public G22Utils getG22utils() { return g22utils(); } public G22Utils g22utils() { return g22utils; } public G22Utils g22utils = new G22Utils(); public List functionContainers = new ArrayList(); public LinkedHashMap knownVars = new LinkedHashMap(); public BuildingScript currentReturnableScript; public boolean inParens = false; public int idCounter; transient public Set>> onKnownVarsSnapshot; public GazelleV_LeftArrowScriptParser onKnownVarsSnapshot(IVF1> f) { onKnownVarsSnapshot = createOrAddToSyncLinkedHashSet(onKnownVarsSnapshot, f); return this; } public GazelleV_LeftArrowScriptParser removeKnownVarsSnapshotListener(IVF1> f) { main.remove(onKnownVarsSnapshot, f); return this; } public void knownVarsSnapshot(Map knownVars) { pcallFAll(onKnownVarsSnapshot, knownVars); } static public class MethodOnObject implements IFieldsToList { static final public String _fieldOrder = "object method"; public Object object; public String method; public MethodOnObject() { } public MethodOnObject(Object object, String method) { this.method = method; this.object = object; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + object + ", " + method + ")"; } public boolean equals(Object o) { if (!(o instanceof MethodOnObject)) return false; MethodOnObject __3 = (MethodOnObject) o; return eq(object, __3.object) && eq(method, __3.method); } public int hashCode() { int h = 791808543; h = boostHashCombine(h, _hashCode(object)); h = boostHashCombine(h, _hashCode(method)); return h; } public Object[] _fieldsToList() { return new Object[] { object, method }; } } public class BuildingScript { public int id = ++idCounter; public boolean returnable = false; public BuildingScript returnableParent; public GazelleV_LeftArrowScript.Script script = new GazelleV_LeftArrowScript.Script(); public List steps = new ArrayList(); public Map functionDefs = new HashMap(); public BuildingScript(boolean returnable) { this.returnable = returnable; } public void add(GazelleV_LeftArrowScript.Evaluable step) { if (step != null) steps.add(step); } public GazelleV_LeftArrowScript.Evaluable get() { var lastStep = last(steps); if (lastStep instanceof GazelleV_LeftArrowScript.ReturnFromScript) if (((GazelleV_LeftArrowScript.ReturnFromScript) lastStep).script == script) replaceLast(steps, ((GazelleV_LeftArrowScript.ReturnFromScript) lastStep).value); if (!returnable && l(steps) == 1 && empty(functionDefs)) return first(steps); script.functionDefs = functionDefs; script.steps = toTypedArray(GazelleV_LeftArrowScript.Evaluable.class, steps); return script; } public String toStringLong() { return pnlToLines(steps); } public String toString() { return formatRecordVars("BuildingScript", "id", id, "returnable", returnable, "returnableParent", returnableParent, "script", script); } } public GazelleV_LeftArrowScript.Script parse(String text) { setText(text); return parse(); } public GazelleV_LeftArrowScript.Script parse() { return (GazelleV_LeftArrowScript.Script) parseScript(true); } public GazelleV_LeftArrowScript.Evaluable parseScript(boolean returnable) { BuildingScript script = new BuildingScript(returnable); var lastReturnableScript = currentReturnableScript; if (returnable) { script.returnableParent = currentReturnableScript; currentReturnableScript = script; } try { parseScript_2(script); var builtScript = script.get(); currentReturnableScript = lastReturnableScript; return builtScript; } catch (Throwable e) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Parsed so far:\n" + script); throw rethrowAndAppendToMessage(e, squareBracketed(str(lineAndColumn()))); } } public void parseScript_2(BuildingScript script) { while (mainLoop()) { knownVarsSnapshot(knownVars); if (is(";")) { next(); continue; } if (is("}")) break; if (is("def")) { parseFunctionDefinition(); continue; } if (is("param")) { consume(); String var = assertIdentifier(tpp()); knownVars.put(var, new LASValueDescriptor()); continue; } if (is("return")) { consume(); var expr = parseAssignmentOrExpr(); { script.add(new GazelleV_LeftArrowScript.ReturnFromScript(currentReturnableScript.script, expr)); continue; } } script.add(parseAssignmentOrExpr()); } } public GazelleV_LeftArrowScript.Evaluable parseAssignmentOrExpr() { String t = token(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("next tokens: " + quote(token(1)) + " " + quote(token(2))); if (isIdentifier(t) && eq(token(1), "<") && eq(token(2), "-")) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Found assignment"); next(3); knownVars.put(t, new LASValueDescriptor()); return new GazelleV_LeftArrowScript.Assignment(t, parseExpr()); } else return parseExpr(); } public GazelleV_LeftArrowScript.Evaluable parseOptionalInnerExpression() { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("parseOptionalInnerExpression", "token", token()); if (atCmdEnd() || is("{")) return null; return parseInnerExpr(); } public GazelleV_LeftArrowScript.Evaluable _const(Object o) { return new GazelleV_LeftArrowScript.Const(o); } public GazelleV_LeftArrowScript.Evaluable parseInnerExpr() { return parseExpr(true); } public GazelleV_LeftArrowScript.Evaluable parseExpr() { return parseExpr(false); } public GazelleV_LeftArrowScript.Evaluable parseExpr(boolean inner) { if (atEnd()) return null; String t = token(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("parseExpr", "token", t); if (is(";")) return null; if (is("-") && empty(nextSpace()) && startsWithDigit(token(1)) || startsWithDigit(t)) { t = consumeMultiTokenLiteral(); if (isInteger(t)) return _const(parseInt(t)); if (endsWith(t, "f")) return _const(parseFloat(t)); return _const(parseDouble(t)); } if (isQuoted(t)) { consume(); return _const(unquote(t)); } if (isIdentifier(t)) { if (is("while")) return parseWhileLoop(); if (is("for")) return parseForEach(); if (is("if")) return parseIfStatement(); consume(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Consumed identifier " + t + ", next token: " + token() + ", inner: " + inner); return parseExprStartingWithIdentifier(t, inner); } if (eq(t, "(")) { boolean inParensOld = inParens; inParens = true; consume(); var e = parseExpr(); consume(")"); inParens = inParensOld; return inner ? e : parseCall(e); } throw fail("Identifier, literal or opening parentheses expected (got: " + quote(t)); } public GazelleV_LeftArrowScript.Evaluable parseExprStartingWithIdentifier(String t, boolean inner) { if (eq(t, "true")) return _const(true); if (eq(t, "false")) return _const(false); if (eq(t, "null")) return _const(null); if (eq(t, "new")) { String className = assertIdentifier(tpp()); Object o = findExternalObject(className); if (o instanceof Class) return new GazelleV_LeftArrowScript.NewObject(((Class) o), parseArguments()); throw fail("Class not found: " + className); } var type = knownVars.get(t); if (type != null) { var e = new GazelleV_LeftArrowScript.GetVar(t).returnType(type); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Found var acccess: " + e + ", " + (!inner ? "Checking for call" : "Returning expression")); return inner ? e : parseCall(e); } if (!inner) { var fdef = lookupFunction(t); if (fdef != null) return new GazelleV_LeftArrowScript.CallFunction(fdef, parseArguments()); } if (eq(t, "_context")) return new GazelleV_LeftArrowScript.GetVarContext(); Object o = findExternalObject(t); if (o == null) throw new UnknownObject(t); else if (inner) return _const(o); else if (o instanceof Class) { Class c = (Class) o; if (isIdentifier()) { String name = tpp(); if (hasMethodNamed(c, name)) return new GazelleV_LeftArrowScript.CallMethod(_const(c), name, parseArguments()); if (isInterface(c)) return parseLambdaMethodRef(c, name); var field = getField(((Class) o), name); if (field != null) { assertCmdEnd(); return new GazelleV_LeftArrowScript.GetStaticField(field); } throw fail(name + " not found in " + ((Class) o) + " (looked for method or field)"); } else throw fail("Method name expected: " + token()); } else if (o instanceof MethodOnObject) { if (inner) throw fail("Can't call methods in arguments"); return new GazelleV_LeftArrowScript.CallMethod(_const(((MethodOnObject) o).object), ((MethodOnObject) o).method, parseArguments()); } else return parseCall(_const(o)); } public GazelleV_LeftArrowScript.Evaluable parseLambdaMethodRef(Class c, String name) { var fdef = lookupFunction(name); if (fdef != null) { GazelleV_LeftArrowScript.Evaluable[] curriedArguments = parseArguments(); return new GazelleV_LeftArrowScript.CurriedScriptFunctionLambda(c, fdef, curriedArguments); } Object function = findExternalObject(name); if (function == null) throw new UnknownObject(name); if (!(function instanceof MethodOnObject)) throw fail(function + " is not a callable method"); Object target = ((MethodOnObject) function).object; String targetMethod = ((MethodOnObject) function).method; GazelleV_LeftArrowScript.Evaluable[] curriedArguments = parseArguments(); return new GazelleV_LeftArrowScript.CurriedMethodLambda(c, target, targetMethod, curriedArguments); } public GazelleV_LeftArrowScript.FunctionDef lookupFunction(String name) { var script = currentReturnableScript; while (script != null) { var f = script.functionDefs.get(name); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("lookupFunction", "script", script, "name", name, "f", f); if (f != null) return f; script = script.returnableParent; } return null; } public GazelleV_LeftArrowScript.Evaluable[] parseArguments() { return toArrayOrNull(GazelleV_LeftArrowScript.Evaluable.class, parseArgumentsAsList()); } public List parseArgumentsAsList() { List l = new ArrayList(); try { while (true) { GazelleV_LeftArrowScript.Evaluable a = parseOptionalInnerExpression(); if (a == null) break; l.add(a); } return l; } catch (Throwable _e) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Arguments parsed so far: " + l); throw rethrow(_e); } } public String consumeMultiTokenLiteral() { return consumeUntilSpaceOr(() -> atCmdEnd()); } public boolean atCmdEnd() { return !inParens && atEndOrLineBreak() || is(";") || is("}") || is(")"); } public void assertCmdEnd() { if (!atCmdEnd()) throw fail("Expected end of command"); } public GazelleV_LeftArrowScript.Evaluable parseCall(GazelleV_LeftArrowScript.Evaluable target) { if (atCmdEnd() || !isIdentifier()) return target; var start = ptr(); String methodName = tpp(); var args = parseArguments(); if (nempty(args)) return new GazelleV_LeftArrowScript.CallMethod(target, methodName, args); else return src(start, new GazelleV_LeftArrowScript.CallMethodOrGetField(target, methodName)); } public A src(ListAndIndex start, A a) { if (a instanceof IHasTokenRangeWithSrc) ((IHasTokenRangeWithSrc) a).setTokenRangeWithSrc(new TokenRangeWithSrc(start, ptr())); return a; } transient public IF1 findExternalObject; public Object findExternalObject(String name) { return findExternalObject != null ? findExternalObject.get(name) : findExternalObject_base(name); } final public Object findExternalObject_fallback(IF1 _f, String name) { return _f != null ? _f.get(name) : findExternalObject_base(name); } public Object findExternalObject_base(String name) { try { String fullName = globalClassNames().get(name); if (fullName != null) return Class.forName(fullName); for (var container : unnullForIteration(functionContainers)) if (hasMethodNamed(container, name)) return new MethodOnObject(container, name); return null; } catch (Exception __e) { throw rethrow(__e); } } public GazelleV_LeftArrowScriptParser allowTheWorld() { return allowTheWorld(mc()); } public GazelleV_LeftArrowScriptParser allowTheWorld(Object... functionContainers) { for (Object o : unnullForIteration(reversed(functionContainers))) if (!contains(this.functionContainers, o)) { this.functionContainers.add(0, o); globalClassNames_cache = null; } return this; } public void printFunctionDefs(GazelleV_LeftArrowScript.Script script) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print(values(script.functionDefs)); } public AutoCloseable tempAddKnownVars(String... vars) { return tempAddKnownVars(asList(vars)); } public AutoCloseable tempAddKnownVars(Iterable vars) { return tempMapPutAll(knownVars, mapWithSingleValue(vars, new LASValueDescriptor())); } public void parseFunctionDefinition() { consume("def"); String functionName = assertIdentifier(tpp()); List args = new ArrayList(); while (isIdentifier()) args.add(tpp()); AutoCloseable __1 = tempAddKnownVars(args); try { var functionBody = parseCurlyBlock(true); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Defined function " + functionName + " in " + currentReturnableScript); currentReturnableScript.functionDefs.put(functionName, new GazelleV_LeftArrowScript.FunctionDef(functionName, args, functionBody)); } finally { _close(__1); } } public GazelleV_LeftArrowScript.Evaluable parseCurlyBlock(boolean returnable) { consume("{"); boolean inParensOld = inParens; inParens = false; var script = parseScript(returnable); consume("}"); inParens = inParensOld; return script; } public GazelleV_LeftArrowScript.Evaluable parseWhileLoop() { consume("while"); var condition = parseExpr(); var body = parseCurlyBlock(false); return new GazelleV_LeftArrowScript.While(condition, body); } public GazelleV_LeftArrowScript.Evaluable parseForEach() { return new ParseForEach().get(); } public class ParseForEach { public GazelleV_LeftArrowScript.Evaluable collection, body; public IF0 finish; public IF0 enterBody; public GazelleV_LeftArrowScript.Evaluable get() { consume("for"); int iIn = relativeIndexOf("in"); if (iIn < 0) throw fail("for without in"); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("iIn", iIn); if (iIn == 1) { String var = consumeIdentifier(); enterBody = () -> tempAddKnownVars(var); finish = () -> new GazelleV_LeftArrowScript.ForEach(collection, var, body); } else if (iIn == 3) { if (isOneOf("pair", "Pair")) { consume(); String varA = consumeIdentifier(); String varB = consumeIdentifier(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("varA", varA, "varB", varB); enterBody = () -> tempAddKnownVars(varA, varB); finish = () -> new GazelleV_LeftArrowScript.ForPairs(collection, body, varA, varB); } else { String varA = consumeIdentifier(); consume(","); String varB = consumeIdentifier(); enterBody = () -> tempAddKnownVars(varA, varB); finish = () -> new GazelleV_LeftArrowScript.ForKeyValue(collection, body, varA, varB); } } else throw fail("Unknown pattern for 'for' loop"); consume("in"); collection = parseExpr(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("collection", collection); AutoCloseable __2 = enterBody.get(); try { body = parseCurlyBlock(false); return finish.get(); } finally { _close(__2); } } } public GazelleV_LeftArrowScript.Evaluable parseIfStatement() { consume("if"); var condition = parseExpr(); var body = parseCurlyBlock(false); GazelleV_LeftArrowScript.Evaluable elseBranch = null; if (is("else")) { consume(); if (is("if")) elseBranch = parseIfStatement(); else elseBranch = parseCurlyBlock(false); } return new GazelleV_LeftArrowScript.IfThen(condition, body, elseBranch); } public void addVar(String var) { addVar(var, new LASValueDescriptor()); } public void addVar(String var, LASValueDescriptor type) { knownVars.put(var, type); } public void addVar(String var, Class type, boolean canBeNull) { addVar(var, new LASValueDescriptor.NonExact(type, canBeNull)); } public Map globalClassNames_cache; public Map globalClassNames() { if (globalClassNames_cache == null) globalClassNames_cache = globalClassNames_load(); return globalClassNames_cache; } public Map globalClassNames_load() { var packages = mapToTreeSet(importedPackages(), pkg -> pkg + "."); var classContainers = classContainerPrefixes(); Map out = new HashMap(); for (var className : g22utils.classNameResolver().allFullyQualifiedClassNames()) { if (isAnonymousClassName(className)) continue; if (!contains(className, '$')) { String pkg = longestPrefixInTreeSet(className, packages); if (pkg != null) { String shortName = dropPrefix(pkg, className); if (!shortName.contains(".")) out.put(shortName, className); } } String container = longestPrefixInTreeSet(className, classContainers); if (container != null) out.put(dropPrefix(container, className), className); } return out; } transient public IF0> importedPackages; public Collection importedPackages() { return importedPackages != null ? importedPackages.get() : importedPackages_base(); } final public Collection importedPackages_fallback(IF0> _f) { return _f != null ? _f.get() : importedPackages_base(); } public Collection importedPackages_base() { return itemPlus("java.lang", standardImports_fullyImportedPackages()); } public TreeSet classContainerPrefixes() { return mapToTreeSet(functionContainers, fc -> className(fc) + "$"); } static public class UnknownObject extends RuntimeException implements IFieldsToList { public String name; public UnknownObject() { } public UnknownObject(String name) { this.name = name; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + name + ")"; } public Object[] _fieldsToList() { return new Object[] { name }; } public String getMessage() { return "Unknown object: " + name; } } } static public class Fail extends RuntimeException implements IFieldsToList { public Object[] objects; public Fail() { } public Fail(Object... objects) { this.objects = objects; } public Object[] _fieldsToList() { return new Object[] { objects }; } public Fail(Throwable cause, Object... objects) { super(cause); this.objects = objects; } public String toString() { return joinNemptiesWithColon("Fail", commaCombine(getCause(), objects)); } } static public class Pair implements Comparable> { public A a; public B b; public Pair() { } public 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 public class LASValueDescriptor { public LASValueDescriptor() { } public boolean knownValue() { return false; } public Object value() { return null; } public Class javaClass() { return null; } public boolean javaClassIsExact() { return false; } public boolean canBeNull() { return true; } public boolean canFail() { return false; } public boolean willFail() { return false; } static public class Exact extends LASValueDescriptor implements IFieldsToList { public Class c; public boolean canBeNull = false; public Exact() { } public Exact(Class c, boolean canBeNull) { this.canBeNull = canBeNull; this.c = c; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + c + ", " + canBeNull + ")"; } public boolean equals(Object o) { if (!(o instanceof Exact)) return false; Exact __1 = (Exact) o; return eq(c, __1.c) && eq(canBeNull, __1.canBeNull); } public int hashCode() { int h = 67394271; h = boostHashCombine(h, _hashCode(c)); h = boostHashCombine(h, _hashCode(canBeNull)); return h; } public Object[] _fieldsToList() { return new Object[] { c, canBeNull }; } public Class javaClass() { return c; } public boolean javaClassIsExact() { return true; } public boolean canBeNull() { return canBeNull; } } static public class NonExact extends LASValueDescriptor implements IFieldsToList { public Class c; public boolean canBeNull = false; public NonExact() { } public NonExact(Class c, boolean canBeNull) { this.canBeNull = canBeNull; this.c = c; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + c + ", " + canBeNull + ")"; } public boolean equals(Object o) { if (!(o instanceof NonExact)) return false; NonExact __2 = (NonExact) o; return eq(c, __2.c) && eq(canBeNull, __2.canBeNull); } public int hashCode() { int h = 1445514322; h = boostHashCombine(h, _hashCode(c)); h = boostHashCombine(h, _hashCode(canBeNull)); return h; } public Object[] _fieldsToList() { return new Object[] { c, canBeNull }; } public Class javaClass() { return c; } public boolean javaClassIsExact() { return false; } public boolean canBeNull() { return canBeNull; } } static public class KnownValue extends LASValueDescriptor implements IFieldsToList { public Object value; public KnownValue() { } public KnownValue(Object value) { this.value = value; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + value + ")"; } public boolean equals(Object o) { if (!(o instanceof KnownValue)) return false; KnownValue __3 = (KnownValue) o; return eq(value, __3.value); } public int hashCode() { int h = -1456305138; h = boostHashCombine(h, _hashCode(value)); return h; } public Object[] _fieldsToList() { return new Object[] { value }; } public boolean knownValue() { return true; } public Object value() { return value; } public Class javaClass() { return value == null ? null : value.getClass(); } public boolean javaClassIsExact() { return value != null; } public boolean canBeNull() { return value == null; } } static public class WillFail extends LASValueDescriptor { public boolean canFail() { return true; } public boolean willFail() { return true; } } static public LASValueDescriptor fromClass(Class c) { return new NonExact(c, true); } } static public class Meta implements IMeta { volatile public Object meta; public void _setMeta(Object meta) { this.meta = meta; } public Object _getMeta() { return meta; } final public boolean scaffolding() { return scaffoldingEnabled(); } public boolean scaffoldingEnabled() { return main.scaffoldingEnabled(this); } public boolean scaffoldingEnabled(Object o) { return main.scaffoldingEnabled(o); } } static public class TokenRangeWithSrc extends TokenRange { public List tok; public TokenRangeWithSrc() { } public TokenRangeWithSrc(List tok, int start) { this.start = start; end = start; } public TokenRangeWithSrc(List tok, int start, int end) { this.end = end; this.start = start; } public TokenRangeWithSrc(ListAndIndex startPtr, ListAndIndex endPtr) { assertSame(tok = startPtr.list(), endPtr.list()); start = startPtr.idx(); end = endPtr.idx(); } public ListAndIndex startPtr() { return new ListAndIndex(tok, start); } public ListAndIndex endPtr() { return new ListAndIndex(tok, end); } public LineAndColumn startLineAndCol() { return tokenToLineAndColumn(startPtr()); } public LineAndColumn endLineAndCol() { return tokenToLineAndColumn(endPtr()); } public String toString() { var start = startLineAndCol(); if (eq(start, end)) return str(start); return start + " to " + endLineAndCol(); } } static public class ScoredStringSearcher extends ScoredSearcher_stable { public Set seen; public ScoredStringSearcher() { } public ScoredStringSearcher(String query, Object... __) { super(query); } public ScoredStringSearcher uniquify(boolean b) { seen = b ? new HashSet() : null; return this; } final public void add(String s) { put(s); } public void put(String s) { if (seen == null || seen.add(s)) put(s, s); } public void addAll(Iterable l) { for (var s : unnullForIteration(l)) add(s); } public void addAll(String... l) { addAll(asList(l)); } } static public interface ISetter { public void set(A a); } static public class CharInToken implements IFieldsToList { static final public String _fieldOrder = "tok iTok iChar"; public List tok; public int iTok; public int iChar; public CharInToken() { } public CharInToken(List tok, int iTok, int iChar) { this.iChar = iChar; this.iTok = iTok; this.tok = tok; } public boolean equals(Object o) { if (!(o instanceof CharInToken)) return false; CharInToken __1 = (CharInToken) o; return eq(tok, __1.tok) && iTok == __1.iTok && iChar == __1.iChar; } public int hashCode() { int h = 2081721214; h = boostHashCombine(h, _hashCode(tok)); h = boostHashCombine(h, _hashCode(iTok)); h = boostHashCombine(h, _hashCode(iChar)); return h; } public Object[] _fieldsToList() { return new Object[] { tok, iTok, iChar }; } public String token() { return get(tok, iTok); } public String toString() { return renderRecordVars("CharInToken", "iTok", iTok, "iChar", iChar, "token", token()); } } static public class G22Utils implements AutoCloseable { final public G22Utils setBackgroundProcessesUI(BackgroundProcessesUI backgroundProcessesUI) { return backgroundProcessesUI(backgroundProcessesUI); } public G22Utils backgroundProcessesUI(BackgroundProcessesUI backgroundProcessesUI) { this.backgroundProcessesUI = backgroundProcessesUI; return this; } final public BackgroundProcessesUI getBackgroundProcessesUI() { return backgroundProcessesUI(); } public BackgroundProcessesUI backgroundProcessesUI() { return backgroundProcessesUI; } public BackgroundProcessesUI backgroundProcessesUI; final public G22Utils setModule(Enterable module) { return module(module); } public G22Utils module(Enterable module) { this.module = module; return this; } final public Enterable getModule() { return module(); } public Enterable module() { return module; } public Enterable module; final public G22Utils setMasterStuff(G22MasterStuff masterStuff) { return masterStuff(masterStuff); } public G22Utils masterStuff(G22MasterStuff masterStuff) { this.masterStuff = masterStuff; return this; } final public G22MasterStuff getMasterStuff() { return masterStuff(); } public G22MasterStuff masterStuff() { return masterStuff; } public G22MasterStuff masterStuff; final public G22Utils setConcepts(Concepts concepts) { return concepts(concepts); } public G22Utils concepts(Concepts concepts) { this.concepts = concepts; return this; } final public Concepts getConcepts() { return concepts(); } public Concepts concepts() { return concepts; } public Concepts concepts; final public G22Utils setProjectActions(G22ProjectActions projectActions) { return projectActions(projectActions); } public G22Utils projectActions(G22ProjectActions projectActions) { this.projectActions = projectActions; return this; } final public G22ProjectActions getProjectActions() { return projectActions(); } public G22ProjectActions projectActions() { return projectActions; } public G22ProjectActions projectActions; final public G22AutoStarter getAutoStarter() { return autoStarter(); } public G22AutoStarter autoStarter() { return autoStarter; } public G22AutoStarter autoStarter = new G22AutoStarter(this); final public CombinedStringifier getStringifier() { return stringifier(); } public CombinedStringifier stringifier() { return stringifier; } public CombinedStringifier stringifier = new CombinedStringifier(o -> o instanceof BufferedImage ? "Image (" + ((BufferedImage) o).getWidth() + "*" + ((BufferedImage) o).getHeight() + " px)" : null); public ImageSurface stdImageSurface() { var is = pixelatedImageSurface().setAutoZoomToDisplay(true).repaintInThread(false); is.defaultImageDir = () -> dbDir(); is.specialPurposed = true; new ImageSurface_PositionToolTip(is); return is; } public ImageSurface stdImageSurface(MakesBufferedImage img) { return stdImageSurface(toBufferedImage(img)); } public ImageSurface stdImageSurface(BufferedImage img) { var is = stdImageSurface(); is.setImage(img); return is; } public String stringify(Object o) { return stringifier.toString(o); } transient public Set> onSettingUpParser; public G22Utils onSettingUpParser(IVF1 f) { onSettingUpParser = createOrAddToSyncLinkedHashSet(onSettingUpParser, f); return this; } public G22Utils removeSettingUpParserListener(IVF1 f) { main.remove(onSettingUpParser, f); return this; } public void settingUpParser(GazelleV_LeftArrowScriptParser parser) { pcallFAll(onSettingUpParser, parser); } transient public Set> onSettingUpScriptIDE; public G22Utils onSettingUpScriptIDE(IVF1 f) { onSettingUpScriptIDE = createOrAddToSyncLinkedHashSet(onSettingUpScriptIDE, f); return this; } public G22Utils removeSettingUpScriptIDEListener(IVF1 f) { main.remove(onSettingUpScriptIDE, f); return this; } public void settingUpScriptIDE(JLeftArrowScriptIDE ide) { pcallFAll(onSettingUpScriptIDE, ide); } public GazelleV_LeftArrowScriptParser leftArrowParser() { GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser(); parser.g22utils(this); settingUpParser(parser); return parser; } public void basicParserTest() { var parser = leftArrowParser(); print("classContainerPrefixes", parser.classContainerPrefixes()); assertEquals(pair(1, 2), parser.parse("new Pair 1 2").get()); } public JLeftArrowScriptIDE leftArrowIDE() { JLeftArrowScriptIDE ide = new JLeftArrowScriptIDE(); ide.g22utils(this); settingUpScriptIDE(ide); return ide; } public File byteCodePath() { return assertNotNull(getBytecodePathForClass(this)); } public ClassNameResolver classNameResolver_cache; public ClassNameResolver classNameResolver() { if (classNameResolver_cache == null) classNameResolver_cache = classNameResolver_load(); return classNameResolver_cache; } public ClassNameResolver classNameResolver_load() { return new ClassNameResolver().byteCodePath(byteCodePath()).init(); } public File databasesMotherDir() { return javaxDataDir("Gazelle-22"); } public AutoCloseable enter() { return module == null ? null : module.enter(); } public String defaultDBName() { return "Default"; } public File lastOpenedDBsFile() { return newFile(databasesMotherDir(), "Last Opened"); } public File autoUpdateFile() { return newFile(databasesMotherDir(), "Auto-Update"); } public boolean autoUpdateEnabled() { return fileExists(autoUpdateFile()); } public void setAutoUpdate(boolean b) { createOrRemoveFile(autoUpdateFile(), b); } public List dbsToOpen() { List dbNames = new ArrayList(); for (String name : tlft(loadTextFile(lastOpenedDBsFile()))) if (fileExists(newFile(databasesMotherDir(), name))) dbNames.add(name); if (empty(dbNames)) dbNames.add(defaultDBName()); return dbNames; } public void setOpenDBs(Collection dbDirs) { List dbNames = new ArrayList(); for (File dbDir : dbDirs) if (sameFile(databasesMotherDir(), dirOfFile(dbDir))) dbNames.add(fileName(dbDir)); saveTextFile(lastOpenedDBsFile(), lines(dbNames)); } public Map scriptToMap(G22LeftArrowScript c) { return scriptToMap(c, false); } public Map scriptToMap(G22LeftArrowScript c, boolean allowRunOnProjectOpen) { return litorderedmap("Description", str(c), "Status", renderScriptStatus(c), "LoC", renderScriptLoC(c), "Run on project open", allowRunOnProjectOpen && c.runOnProjectOpen ? "Yes" + appendBracketed("prio " + c.runOrder) : null); } public String renderScriptStatus(G22LeftArrowScript c) { return or2_rev("Empty", joinNemptiesWithSpacedPlus(c.isClearForAutoRun() ? "Clear for auto-run" : null, c.isSavedDistinctFromAutoRunVersion() ? "Saved (not cleared)" : null, c.isEditing() ? "Editing" : null)); } public String renderScriptLoC(G22LeftArrowScript c) { return n2(intMax(mapLL(__59 -> linesOfCode_javaTok(__59), c.editingText, c.text, c.codeForAutoRun()))); } public List labelsForFile(File file) { if (file == null) return null; File labelsFile = appendToFileName(file, ".labels"); List labels = tlft(loadTextFile(labelsFile)); return map(__60 -> getLabel(__60), labels); } public File labelsFile(File file) { if (file == null) return null; return appendToFileName(file, ".labels"); } public void setLabelsForFile(File file, List labels) { List list = map(labels, label -> label.name); File f = labelsFile(file); saveTextFile(f, lines(list)); print("Saved " + nLabels(list) + " (" + joinWithComma(list) + ") to " + f); } public G22Label getLabel(String name) { if (empty(name)) return null; if (containsNewLine(name)) throw fail("No newlines in label names allowed: " + name); return uniqCI(concepts, G22Label.class, "name", name); } public File dbDir() { return conceptsDir(concepts); } public File fileInDbDir(String name) { return newFile(dbDir(), name); } public class GazelleDB implements IFieldsToList { public String name; public File dir; public GazelleDB() { } public GazelleDB(String name, File dir) { this.dir = dir; this.name = name; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + name + ", " + dir + ")"; } public boolean equals(Object o) { if (!(o instanceof GazelleDB)) return false; GazelleDB __0 = (GazelleDB) o; return eq(name, __0.name) && eq(dir, __0.dir); } public int hashCode() { int h = 1669530526; h = boostHashCombine(h, _hashCode(name)); h = boostHashCombine(h, _hashCode(dir)); return h; } public Object[] _fieldsToList() { return new Object[] { name, dir }; } public Boolean loaded_cache; public boolean loaded() { if (loaded_cache == null) loaded_cache = loaded_load(); return loaded_cache; } public Boolean loaded_load() { return containsFile(masterStuff.openConceptDirs(), dir); } public File conceptsFile() { return conceptsFileIn(dir); } } public List gazelleDBs() { List dbs = new ArrayList(); for (File dir : listDirsContainingFileNamed(databasesMotherDir(), "concepts.structure.gz")) dbs.add(new GazelleDB(fileName(dir), dir)); return dbs; } public RSyntaxTextAreaWithSearch newSyntaxTextArea() { return newSyntaxTextArea(null); } public RSyntaxTextAreaWithSearch newSyntaxTextArea(IF1 wrapStatusLabel) { RSyntaxTextAreaWithSearch ta = new RSyntaxTextAreaWithSearch(wrapStatusLabel); ta.textArea().setHighlightCurrentLine(false); ta.menuLessOperation(); return ta; } public File projectStoryTextFile() { return newFile(dbDir(), "story.txt"); } public String projectName() { return fileName(dbDir()); } public void close() { try { autoStarter.close(); } catch (Exception __e) { throw rethrow(__e); } } } static public interface IFieldsToList { public Object[] _fieldsToList(); } public interface IHasTokenRangeWithSrc { public void setTokenRangeWithSrc(TokenRangeWithSrc src); public TokenRangeWithSrc tokenRangeWithSrc(); } static public class GazelleV_LeftArrowScript { abstract static public class Base implements IHasTokenRangeWithSrc { public TokenRangeWithSrc src; public void setTokenRangeWithSrc(TokenRangeWithSrc src) { this.src = src; } public TokenRangeWithSrc tokenRangeWithSrc() { return src; } public RuntimeException rethrowWithSrc(Throwable e) { if (src != null) throw rethrowAndAppendToMessage(e, squareBracketed(str(src))); else throw rethrow(e); } } public interface Evaluable extends IF0 { public default Object get() { return get(new VarContext()); } public Object get(VarContext ctx); public default LASValueDescriptor returnType() { return null; } public default Evaluable optimize() { return this; } } abstract static public class BaseEvaluable extends Base implements Evaluable { final public BaseEvaluable setReturnType(LASValueDescriptor returnType) { return returnType(returnType); } public BaseEvaluable returnType(LASValueDescriptor returnType) { this.returnType = returnType; return this; } final public LASValueDescriptor getReturnType() { return returnType(); } public LASValueDescriptor returnType() { return returnType; } public LASValueDescriptor returnType; } static public AtomicLong scriptIDCounter = new AtomicLong(); static public long scriptID() { return incAtomicLong(scriptIDCounter); } static public class Script extends Base implements Evaluable { public long id = scriptID(); public Map functionDefs; public Evaluable[] steps; public Object get(VarContext ctx) { Object result = null; for (var step : steps) { ping(); result = step.get(ctx); var exiting = ctx.exitFromScript; if (exiting != null) { if (exiting == this) ctx.exitFromScript = null; break; } } return result; } public String toStringLong() { return pnlToLines(steps); } public String toString() { return "Script " + n2(id); } public FunctionDef getFunction(String name) { return mapGet(functionDefs, name); } } static public class FunctionDef extends Base implements IFieldsToList { public String name; public List args; public Evaluable body; public FunctionDef() { } public FunctionDef(String name, List args, Evaluable body) { this.body = body; this.args = args; this.name = name; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + name + ", " + args + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { name, args, body }; } public Object call(VarContext ctx, Object... args) { var ctx2 = new VarContext(ctx); int n = min(l(args), l(this.args)); for (int i = 0; i < n; i++) ctx2.put(this.args.get(i), args[i]); return body.get(ctx2); } } static public class Assignment extends Base implements Evaluable, IFieldsToList { public String var; public Evaluable expression; public Assignment() { } public Assignment(String var, Evaluable expression) { this.expression = expression; this.var = var; } public Object[] _fieldsToList() { return new Object[] { var, expression }; } public Object get(VarContext ctx) { Object o = expression.get(ctx); ctx.set(var, o); return o; } public String toString() { return var + " <- " + expression; } } static public class NewObject extends Base implements Evaluable { public NewObject() { } public Class c; public Evaluable[] args; public NewObject(Class c) { this.c = c; } public NewObject(Class c, Evaluable[] args) { this.args = args; this.c = c; } public Object get(VarContext ctx) { return preciseNuObject(c, mapToArrayOrNull(args, arg -> arg.get(ctx))); } public String toString() { return "new " + formatFunctionCall(className(c), args); } } static public class CallFunction extends Base implements Evaluable, IFieldsToList { public FunctionDef f; public Evaluable[] args; public CallFunction() { } public CallFunction(FunctionDef f, Evaluable[] args) { this.args = args; this.f = f; } public Object[] _fieldsToList() { return new Object[] { f, args }; } public Object get(VarContext ctx) { return f.call(ctx, mapToArrayOrNull(args, a -> a.get(ctx))); } public String toString() { return formatFunctionCall(f.name, args); } } static public class GetVar extends BaseEvaluable implements IFieldsToList { public String var; public GetVar() { } public GetVar(String var) { this.var = var; } public Object[] _fieldsToList() { return new Object[] { var }; } public Object get(VarContext ctx) { return ctx.get(var); } public String toString() { return var; } } static public class Const extends Base implements Evaluable, IFieldsToList { public Object value; public Const() { } public Const(Object value) { this.value = value; } public Object[] _fieldsToList() { return new Object[] { value }; } public Object get(VarContext ctx) { return value; } public String toString() { return strOrClassName(value); } public LASValueDescriptor returnType() { return new LASValueDescriptor.KnownValue(value); } } static public class GetStaticField extends Base implements Evaluable, IFieldsToList { public Field field; public GetStaticField() { } public GetStaticField(Field field) { this.field = field; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + field + ")"; } public Object[] _fieldsToList() { return new Object[] { field }; } public Object get(VarContext ctx) { try { return field.get(null); } catch (Exception __e) { throw rethrow(__e); } } } static public class CallMethodOrGetField extends Base implements Evaluable, IFieldsToList { public Evaluable target; public String name; public CallMethodOrGetField() { } public CallMethodOrGetField(Evaluable target, String name) { this.name = name; this.target = target; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + target + ", " + name + ")"; } public Object[] _fieldsToList() { return new Object[] { target, name }; } public Object get(VarContext ctx) { try { Object object = target.get(ctx); if (object == null) return null; if (canCallWithVarargs(object, name)) return call(object, name); return _get(object, name); } catch (Throwable e) { throw rethrowWithSrc(e); } } } static public class GetVarContext extends Base implements Evaluable { public Object get(VarContext ctx) { return ctx; } } static public class ThrowMethodNotFoundException extends Base implements Evaluable, IFieldsToList { public CallMethod instruction; public ThrowMethodNotFoundException() { } public ThrowMethodNotFoundException(CallMethod instruction) { this.instruction = instruction; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + instruction + ")"; } public Object[] _fieldsToList() { return new Object[] { instruction }; } public Object get(VarContext ctx) { throw fail("Method not found: " + instruction); } } static public class ThrowNullPointerException extends Base implements Evaluable, IFieldsToList { public CallMethod instruction; public ThrowNullPointerException() { } public ThrowNullPointerException(CallMethod instruction) { this.instruction = instruction; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + instruction + ")"; } public Object[] _fieldsToList() { return new Object[] { instruction }; } public Object get(VarContext ctx) { throw fail("Null pointer exception: " + instruction); } } static public class CallMethod extends Base implements Evaluable, IFieldsToList { public Evaluable target; public String methodName; public Evaluable[] args; public CallMethod() { } public CallMethod(Evaluable target, String methodName, Evaluable[] args) { this.args = args; this.methodName = methodName; this.target = target; } public Object[] _fieldsToList() { return new Object[] { target, methodName, args }; } public Object get(VarContext ctx) { return newPreciseCall(target.get(ctx), methodName, mapToArrayOrNull(args, arg -> arg.get(ctx))); } public String toString() { return target + "." + formatFunctionCall(methodName, args); } public Evaluable optimize() { var targetType = target.returnType(); if (targetType.knownValue()) { Object o = targetType.value(); if (o == null) return new ThrowNullPointerException(this); Class[] argTypes = new Class[l(args)]; for (int i = 0; i < l(args); i++) { var type = args[i].returnType(); if (!type.javaClassIsExact()) return this; argTypes[i] = type.javaClass(); } var method = findMethod_precise_onTypes(o, methodName, argTypes); if (method == null) return new ThrowMethodNotFoundException(this); return new DirectMethodCallOnKnownTarget(o instanceof Class ? null : o, method, args); } return this; } } abstract static public class CurriedLambdaBase extends Base implements Evaluable, IFieldsToList { public Class intrface; public Evaluable[] curriedArgs; public CurriedLambdaBase() { } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + intrface + ", " + curriedArgs + ")"; } public Object[] _fieldsToList() { return new Object[] { intrface, curriedArgs }; } public Class declaringClass; public Method implementedMethod; public CurriedLambdaBase(Class intrface, Evaluable[] curriedArgs) { this.curriedArgs = curriedArgs; this.intrface = intrface; implementedMethod = findSingleInterfaceMethod(intrface); if (implementedMethod == null) throw fail(intrface + " is not a single method interface"); declaringClass = implementedMethod.getDeclaringClass(); } public Object get(VarContext ctx) { Object[] curriedArguments = mapToArrayOrNull(curriedArgs, arg -> arg.get(ctx)); return proxyFromInvocationHandler(intrface, (proxy, method, args) -> { if (method.getDeclaringClass() != declaringClass) throw fail("No handler for method " + method + " (only have " + implementedMethod + ")"); return forwardCall(ctx, concatMethodArgs(curriedArguments, args)); }); } abstract public Object forwardCall(VarContext ctx, Object[] args); } static public class CurriedMethodLambda extends CurriedLambdaBase { public Object target; public String targetMethod; public CurriedMethodLambda(Class intrface, Object target, String targetMethod, Evaluable[] curriedArgs) { super(intrface, curriedArgs); this.targetMethod = targetMethod; this.target = target; } public Object forwardCall(VarContext ctx, Object[] args) { return call(target, targetMethod, args); } } static public class CurriedScriptFunctionLambda extends CurriedLambdaBase { public FunctionDef f; public CurriedScriptFunctionLambda(Class intrface, FunctionDef f, Evaluable[] curriedArgs) { super(intrface, curriedArgs); this.f = f; } public Object forwardCall(VarContext ctx, Object[] args) { return f.call(ctx, args); } } static public class DirectMethodCallOnKnownTarget extends Base implements Evaluable, IFieldsToList { public Object target; public Method method; public Evaluable[] args; public DirectMethodCallOnKnownTarget() { } public DirectMethodCallOnKnownTarget(Object target, Method method, Evaluable[] args) { this.args = args; this.method = method; this.target = target; } public Object[] _fieldsToList() { return new Object[] { target, method, args }; } public Object get(VarContext ctx) { return invokeMethod(method, target, mapToArrayOrNull(args, arg -> arg.get(ctx))); } public String toString() { return (target == null ? "" : target + ".") + formatFunctionCall(str(method), args); } public LASValueDescriptor returnType() { return LASValueDescriptor.fromClass(method.getReturnType()); } } static public class While extends Base implements Evaluable, IFieldsToList { public Evaluable condition; public Evaluable body; public While() { } public While(Evaluable condition, Evaluable body) { this.body = body; this.condition = condition; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + condition + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { condition, body }; } public Object get(VarContext ctx) { while (ping() && (Boolean) condition.get(ctx)) { body.get(ctx); } return null; } } abstract static public class ForEachBase extends Base implements Evaluable, IFieldsToList { public Evaluable collection; public Evaluable body; public ForEachBase() { } public ForEachBase(Evaluable collection, Evaluable body) { this.body = body; this.collection = collection; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + collection + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { collection, body }; } public Object get(VarContext ctx) { var coll = collection.get(ctx); Iterator iterator; List out; if (coll instanceof Object[]) { out = emptyList(((Object[]) coll).length); for (var element : ((Object[]) coll)) { ping(); processElement(ctx, out, element); } } else if (coll instanceof Iterable) { out = emptyList((Iterable) coll); for (var element : ((Iterable) coll)) { ping(); processElement(ctx, out, element); } } else if (coll == null) out = new ArrayList(); else throw fail("Not iterable: " + className(coll)); loopDone(ctx); return out; } abstract public void processElement(VarContext ctx, List out, Object o); abstract public void loopDone(VarContext ctx); } static public class ForEach extends ForEachBase { public ForEach() { } public String var; public ForEach(Evaluable collection, String var, Evaluable body) { this.body = body; this.var = var; this.collection = collection; } public void processElement(VarContext ctx, List out, Object o) { ctx.set(var, o); out.add(body.get(ctx)); } public void loopDone(VarContext ctx) { ctx.unset(var); } } static public class ForPairs extends ForEachBase { public ForPairs() { } public String varA, varB; public ForPairs(Evaluable collection, Evaluable body, String varA, String varB) { this.varB = varB; this.varA = varA; this.body = body; this.collection = collection; } public void processElement(VarContext ctx, List out, Object o) { Pair p = (Pair) o; ctx.set(varA, p.a); ctx.set(varB, p.b); out.add(body.get(ctx)); } public void loopDone(VarContext ctx) { ctx.unset(varA); ctx.unset(varB); } } static public class ForKeyValue extends Base implements Evaluable, IFieldsToList { public Evaluable map; public Evaluable body; public String varA; public String varB; public ForKeyValue() { } public ForKeyValue(Evaluable map, Evaluable body, String varA, String varB) { this.varB = varB; this.varA = varA; this.body = body; this.map = map; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + map + ", " + body + ", " + varA + ", " + varB + ")"; } public Object[] _fieldsToList() { return new Object[] { map, body, varA, varB }; } public Object get(VarContext ctx) { Map theMap = (Map) map.get(ctx); List out; if (theMap != null) { out = emptyList(theMap.size()); for (var entry : theMap.entrySet()) { ping(); ctx.set(varA, entry.getKey()); ctx.set(varB, entry.getValue()); out.add(body.get(ctx)); } } else out = new ArrayList(); ctx.unset(varA); ctx.unset(varB); return out; } } static public class IfThen extends Base implements Evaluable, IFieldsToList { public Evaluable condition; public Evaluable body; public Evaluable elseBranch; public IfThen() { } public IfThen(Evaluable condition, Evaluable body, Evaluable elseBranch) { this.elseBranch = elseBranch; this.body = body; this.condition = condition; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + condition + ", " + body + ", " + elseBranch + ")"; } public Object[] _fieldsToList() { return new Object[] { condition, body, elseBranch }; } public IfThen(Evaluable condition, Evaluable body) { this.condition = condition; this.body = body; } public Object get(VarContext ctx) { if ((Boolean) condition.get(ctx)) return body.get(ctx); else if (elseBranch != null) return elseBranch.get(ctx); else return null; } } static public class ReturnFromScript extends Base implements Evaluable, IFieldsToList { public Script script; public Evaluable value; public ReturnFromScript() { } public ReturnFromScript(Script script, Evaluable value) { this.value = value; this.script = script; } public Object[] _fieldsToList() { return new Object[] { script, value }; } public Object get(VarContext ctx) { Object result = value.get(ctx); ctx.exitFromScript(script); return result; } public String toString() { return formatFunctionCall("ReturnFromScript", script, value); } } } static public class SimpleLeftToRightParser extends Meta { public String text; public List tok; final public ListAndIndex getPtr() { return ptr(); } public ListAndIndex ptr() { return ptr; } public ListAndIndex ptr; public ListAndIndex mainLoopPtr; public String currentToken; public boolean caseInsensitive = false; public List warnings = new ArrayList(); public SimpleLeftToRightParser() { } public SimpleLeftToRightParser(String text) { this.text = text; } public SimpleLeftToRightParser(List tok) { this.tok = tok; } transient public IF1> tokenize; public List tokenize(String text) { return tokenize != null ? tokenize.get(text) : tokenize_base(text); } final public List tokenize_fallback(IF1> _f, String text) { return _f != null ? _f.get(text) : tokenize_base(text); } public List tokenize_base(String text) { return javaTok(text); } final public String token() { return t(); } public String t() { return currentToken; } public String token(int i) { return get(tok, ptr.idx() + i * 2); } final public String consume() { return next(); } final public String tpp() { return next(); } public String next() { var t = t(); next(1); return t; } public String lastSpace() { return get(tok, ptr.idx() - 1); } public String nextSpace() { return get(tok, ptr.idx() + 1); } final public boolean eqTok(String a, String b) { return tokEq(a, b); } public boolean tokEq(String a, String b) { return eqOrEqic(caseInsensitive, a, b); } public boolean tokEqOneOf(String a, String... l) { return any(l, b -> tokEq(a, b)); } public boolean is(String t) { return tokEq(currentToken, t); } public boolean was(String t) { return tokEq(token(-1), t); } public boolean isOneOf(String... tokens) { return tokEqOneOf(currentToken, tokens); } public boolean isInteger() { return isInteger(t()); } public boolean isInteger(String s) { return main.isInteger(s); } public boolean isIdentifier() { return isIdentifier(t()); } public boolean isIdentifier(String s) { return main.isIdentifier(s); } public String consumeIdentifier() { return assertIdentifier(consume()); } public void consume(String token) { if (!is(token)) throw fail("Expected " + quote(token) + ", got " + quote(token())); consume(); } public String consumeOneOf(String... tokens) { if (!isOneOf(tokens)) throw fail("Expected one of " + asList(tokens)); return consume(); } public void ptr(ListAndIndex ptr) { this.ptr = ptr; fetch(); } final public int tokIdx() { return idx(); } public int idx() { return ptr.idx(); } public int lTok() { return l(tok); } public int nRemainingTokens() { return (lTok() - idx()) / 2; } final public boolean endOfText() { return atEnd(); } public boolean atEnd() { return ptr.atEnd(); } public void fetch() { currentToken = ptr.get(); } public boolean lineBreak() { return containsLineBreak(get(tok, ptr.idx() - 1)); } public boolean atEndOrLineBreak() { return atEnd() || lineBreak(); } public void init() { if (tok == null) tok = tokenize(text); if (ptr == null) ptr(new ListAndIndex(tok, 1)); } public boolean mainLoop() { init(); if (atEnd()) return false; if (eq(mainLoopPtr, ptr)) throw fail("main loop didn't advance (current token: " + quote(token()) + ")"); mainLoopPtr = ptr; return true; } public void unknownToken() { warn("Unknown token: " + t()); } public void warn(String msg) { warnings.add(print(msg)); } public void next(int n) { ptr(min(lTok(), ptr.idx() + n * 2)); } public void ptr(int i) { ptr(new ListAndIndex(tok, min(i | 1, l(tok)))); } public LineAndColumn lineAndColumn() { return tokenToLineAndColumn(ptr); } public String consumeUntilSpaceOr(IF0 pred) { int i = idx(); do next(); while (!atEnd() && empty(lastSpace()) && !pred.get()); return joinSubList(tok, i, idx() - 1); } public void setText(String text) { this.text = text; tok = null; ptr = null; } public int relativeIndexOf(String token) { int n = nRemainingTokens(); for (int i = 0; i < n; i++) if (eqTok(token(i), token)) return i; return -1; } } static public interface IVar extends IF0 { public void set(A a); public A get(); default public Class getType() { return null; } default public boolean has() { return get() != null; } default public void clear() { set(null); } } static public class ScoredSearcher_stable { public int maxResults = 1000; public boolean returnAll = false; public List preparedTerms; public MultiMap byScore = descTreeMultiMap(); public ScoredSearcher_stable() { } public ScoredSearcher_stable(String query, Object... __) { maxResults = optPar("maxResults", __, maxResults); setQuery(query); } public void setQuery(String query) { preparedTerms = scoredSearch_prepare(query); } public void put(A object, String s) { putScored(object, score(s)); } public void putScored(A object, double score) { if (score != 0) byScore.add(score, object); } public void put(A object, Collection fields) { add(object, scoreFields(fields)); } public void putWithWeights(A object, Collection> fields) { scoredSearch_scoreWeighted2(fields, preparedTerms); } public int scoreFields(Collection fields) { return scoredSearch_score(fields, preparedTerms); } public int score(String text) { return returnAll ? 1 : scoredSearch_score(text, preparedTerms); } public void add(A object) { put(object, str(object)); } public void add(A object, Collection fields) { put(object, fields); } public void put(A object, double score) { add(object, score); } public void add(A object, double score) { putScored(object, score); } public List get() { return pairsB(takeFirst(maxResults, multiMapPairIterator(byScore))); } public List get_transformListWithinScore(IF1, List> f) { return pairsB(takeFirst(maxResults, multiMapPairIterator_transformValueList(byScore, f))); } public List> withScores() { return map(takeFirst(maxResults, multiMapPairIterator(byScore)), p -> new Scored(p.b, p.a)); } public A best() { return firstValue(byScore); } } public interface Enterable { public AutoCloseable enter(); } static public class BackgroundProcessesUI { public Set processes = setWithNotify(syncLinkedHashSet(), () -> updateCount()); public SimpleLiveValue lvCount = new SimpleLiveValue(Integer.class, 0); public class Entry implements AutoCloseable, IFieldsToList { public String name; public Entry() { } public Entry(String name) { this.name = name; } public boolean equals(Object o) { if (!(o instanceof Entry)) return false; Entry __0 = (Entry) o; return eq(name, __0.name); } public int hashCode() { int h = 67115090; h = boostHashCombine(h, _hashCode(name)); return h; } public Object[] _fieldsToList() { return new Object[] { name }; } final public Entry setMenuItem(JMenuItem menuItem) { return menuItem(menuItem); } public Entry menuItem(JMenuItem menuItem) { this.menuItem = menuItem; return this; } final public JMenuItem getMenuItem() { return menuItem(); } public JMenuItem menuItem() { return menuItem; } public JMenuItem menuItem; public String toString() { return name; } public void close() { try { processes.remove(this); } catch (Exception __e) { throw rethrow(__e); } } } public JLabel shortLabel() { var lbl = bindToolTipToTransformedLiveValue(n -> makeToolTip(), lvCount, simpleTransformedLiveValueLabel(n -> n2(n), lvCount)); onMouseDown_anyButton(lbl, e -> { var l = cloneList(processes); JPopupMenu menu = new JPopupMenu(); int n = componentCount(menu); for (Entry a : l) addMenuItem(menu, processToMenuItem(a)); if (componentCount(menu) != n) { var border = jRaisedSectionBorder("Background Processes"); setBorder(menu, border); showPopupMenu(menu, e); var size = menu.getSize(); var borderSize = dimensionPlus(10, 0, border.getMinimumSize(menu)); printVars("size", size, "borderSize", borderSize); menu.setPopupSize(maxDimension(size, borderSize)); } }); return lbl; } public void add(Entry process) { processes.add(process); } public void remove(Entry process) { processes.remove(process); } public void addOrRemove(boolean add, Entry process) { if (add) add(process); else remove(process); } public Entry tempAdd(String name) { return tempAdd(new Entry(or2(name, "Unnamed process"))); } public Entry tempAdd(Entry process) { if (process == null) return null; processes.add(process); return process; } public void updateCount() { lvCount.set(l(processes)); } public String makeToolTip() { var l = cloneList(processes); return empty(l) ? "No background processes" : n2(l, "background process", "background processes") + ": " + joinWithComma(processes); } transient public IF1 processToMenuItem; public JMenuItem processToMenuItem(Entry process) { return processToMenuItem != null ? processToMenuItem.get(process) : processToMenuItem_base(process); } final public JMenuItem processToMenuItem_fallback(IF1 _f, Entry process) { return _f != null ? _f.get(process) : processToMenuItem_base(process); } public JMenuItem processToMenuItem_base(Entry process) { return process.getMenuItem(); } } static public class ClassNameResolver { final public ClassNameResolver setByteCodePath(File byteCodePath) { return byteCodePath(byteCodePath); } public ClassNameResolver byteCodePath(File byteCodePath) { this.byteCodePath = byteCodePath; return this; } final public File getByteCodePath() { return byteCodePath(); } public File byteCodePath() { return byteCodePath; } public File byteCodePath = byteCodePathForClass(getClass()); public List importedPackages = itemPlusList("java.lang", endingWith_dropSuffix(standardImports(), ".*")); public Set allFullyQualifiedClassNames_cache; public Set allFullyQualifiedClassNames() { if (allFullyQualifiedClassNames_cache == null) allFullyQualifiedClassNames_cache = allFullyQualifiedClassNames_load(); return allFullyQualifiedClassNames_cache; } public Set allFullyQualifiedClassNames_load() { Set set = new HashSet(); assertNotNull(byteCodePath); set.addAll(classNamesInJarOrDir(byteCodePath)); printVars("ClassNameResolver", "byteCodePath", byteCodePath, "classesFound", l(set)); set.addAll(classNamesInLoadedJigsawModules()); return set; } public ClassNameResolver init() { allFullyQualifiedClassNames(); return this; } public String findClass(String name) { for (String pkg : importedPackages) { String fullName = pkg + "." + name; if (allFullyQualifiedClassNames().contains(fullName)) return fullName; } return null; } public void printMe() { printVars("ClassNameResolver", "byteCodePath", byteCodePath); print("importedPackages", importedPackages); } } static public class VarContext { public VarContext parent; public Map vars; public VarContext() { } public VarContext(VarContext parent) { this.parent = parent; } public Object get(String name) { if (containsKey(vars, name)) return mapGet(vars, name); if (parent != null) return parent.get(name); return null; } final public void put(String name, Object value) { set(name, value); } public void set(String name, Object value) { vars = putOrCreate(vars, name, value); } public void unset(String name) { remove(vars, name); } public void printMe() { pnl(vars); print("parent", parent); } final public VarContext setExitFromScript(Object exitFromScript) { return exitFromScript(exitFromScript); } public VarContext exitFromScript(Object exitFromScript) { this.exitFromScript = exitFromScript; return this; } final public Object getExitFromScript() { return exitFromScript(); } public Object exitFromScript() { return exitFromScript; } public Object exitFromScript; } static public interface IMeta { public void _setMeta(Object meta); public Object _getMeta(); default public IAutoCloseableF0 _tempMetaMutex() { return new IAutoCloseableF0() { public Object get() { return IMeta.this; } public void close() { } }; } default public Object getMeta(Object obj, Object key) { return metaGet(obj, key); } default public Object metaGet(Object obj, Object key) { return metaMapGet(obj, key); } default public Object metaGet(String key, Object obj) { return metaMapGet(obj, key); } default public Object getMeta(Object key) { return metaGet(key); } default public Object metaGet(Object key) { if (key == null) return null; Object meta = _getMeta(); if (meta instanceof Map) return ((Map) meta).get(key); return null; } default public void metaSet(IMeta obj, Object key, Object value) { metaPut(obj, key, value); } default public void metaPut(IMeta obj, Object key, Object value) { metaMapPut(obj, key, value); } default public void metaSet(Object key, Object value) { metaPut(key, value); } default public void metaPut(Object key, Object value) { if (key == null) return; Map map = convertObjectMetaToMap(this); syncMapPutOrRemove(map, key, value); } } public interface G22ProjectActions { public void openObjectInProject(long id); public void openPathInProject(String path); public void editProjectStory(); public void editScripts(); } static public class LineAndColumn { public int line, col; public LineAndColumn(int line, int col) { this.col = col; this.line = line; } transient public IF1 getLineText; public String getLineText(int line) { return getLineText != null ? getLineText.get(line) : getLineText_base(line); } final public String getLineText_fallback(IF1 _f, int line) { return _f != null ? _f.get(line) : getLineText_base(line); } public String getLineText_base(int line) { return null; } public String toString() { return "Line " + n2(line) + ", col " + n2(col); } } static public class FailedRule extends RuleWithParams { public List satisfiedConditions; public Exp remainingCondition; public FailedRule() { } public FailedRule(IfThen rule, VarMatches matches, Exp remainingCondition) { this.remainingCondition = remainingCondition; this.matches = matches; this.rule = rule; } public FailedRule(IfThen rule, VarMatches matches, List satisfiedConditions, Exp remainingCondition) { this.remainingCondition = remainingCondition; this.satisfiedConditions = satisfiedConditions; this.matches = matches; this.rule = rule; } } static public class RuleWithParams implements IFieldsToList { static final public String _fieldOrder = "rule matches"; public IfThen rule; public VarMatches matches; public RuleWithParams() { } public RuleWithParams(IfThen rule, VarMatches matches) { this.matches = matches; this.rule = rule; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + rule + ", " + matches + ")"; } public boolean equals(Object o) { if (!(o instanceof RuleWithParams)) return false; RuleWithParams __7 = (RuleWithParams) o; return eq(rule, __7.rule) && eq(matches, __7.matches); } public int hashCode() { int h = 1254104616; h = boostHashCombine(h, _hashCode(rule)); h = boostHashCombine(h, _hashCode(matches)); return h; } public Object[] _fieldsToList() { return new Object[] { rule, matches }; } public String ruleID() { return rule.globalID; } } static public class IfThen implements IFieldsToList { static final public String _fieldOrder = "in out globalID options originalText"; public Exp in; public Exp out; public IfThen() { } public IfThen(Exp in, Exp out) { this.out = out; this.in = in; } public boolean equals(Object o) { if (!(o instanceof IfThen)) return false; IfThen __8 = (IfThen) o; return eq(in, __8.in) && eq(out, __8.out); } public int hashCode() { int h = -2108234502; h = boostHashCombine(h, _hashCode(in)); h = boostHashCombine(h, _hashCode(out)); return h; } public Object[] _fieldsToList() { return new Object[] { in, out }; } public String globalID; public Set options; public String originalText; public String text() { Collection opt = options; if (nempty(globalID)) opt = concatLists(ll("id: " + globalID), opt); return (nempty(opt) ? "[" + joinWithComma(opt) + "] " : "") + (in == null ? "" : in.text() + "\n => ") + nlLogic_text(out); } public String toString() { return text(); } } abstract static public class Exp { abstract public String text(); public String toString() { return text(); } } static public class Func extends Exp implements IFieldsToList { public String name; public Exp arg; public Func() { } public Func(String name, Exp arg) { this.arg = arg; this.name = name; } public boolean equals(Object o) { if (!(o instanceof Func)) return false; Func __0 = (Func) o; return eq(name, __0.name) && eq(arg, __0.arg); } public int hashCode() { int h = 2201316; h = boostHashCombine(h, _hashCode(name)); h = boostHashCombine(h, _hashCode(arg)); return h; } public Object[] _fieldsToList() { return new Object[] { name, arg }; } public List options; public Func(String name, List options, Exp arg) { this.arg = arg; this.options = options; this.name = name; } public String text() { return name + (empty(options) ? "" : "[" + joinWithComma(options) + "]") + "(" + arg.text() + ")"; } public String argText() { return nlLogic_text(arg); } } static public class And extends Exp implements IFieldsToList { public Exp a; public Exp b; public And() { } public And(Exp a, Exp b) { this.b = b; this.a = a; } public boolean equals(Object o) { if (!(o instanceof And)) return false; And __1 = (And) o; return eq(a, __1.a) && eq(b, __1.b); } public int hashCode() { int h = 65975; h = boostHashCombine(h, _hashCode(a)); h = boostHashCombine(h, _hashCode(b)); return h; } public Object[] _fieldsToList() { return new Object[] { a, b }; } public String text() { return a.text() + "\n && " + b.text(); } } static public class ExpNot extends Exp implements IFieldsToList { public Exp a; public ExpNot() { } public ExpNot(Exp a) { this.a = a; } public boolean equals(Object o) { if (!(o instanceof ExpNot)) return false; ExpNot __2 = (ExpNot) o; return eq(a, __2.a); } public int hashCode() { int h = 2089649046; h = boostHashCombine(h, _hashCode(a)); return h; } public Object[] _fieldsToList() { return new Object[] { a }; } public String text() { return "!" + a.text(); } } abstract static public class Literal extends Exp { } static public class Sentence extends Literal implements IFieldsToList { public List tok; public Sentence() { } public Sentence(List tok) { this.tok = tok; } public boolean equals(Object o) { if (!(o instanceof Sentence)) return false; Sentence __3 = (Sentence) o; return eq(tok, __3.tok); } public int hashCode() { int h = 1327381123; h = boostHashCombine(h, _hashCode(tok)); return h; } public Object[] _fieldsToList() { return new Object[] { tok }; } public String text() { return join(tok); } } static public class Sentence2 extends Literal implements IFieldsToList { public String text; public Sentence2() { } public Sentence2(String text) { this.text = text; } public boolean equals(Object o) { if (!(o instanceof Sentence2)) return false; Sentence2 __4 = (Sentence2) o; return eq(text, __4.text); } public int hashCode() { int h = -1800858097; h = boostHashCombine(h, _hashCode(text)); return h; } public Object[] _fieldsToList() { return new Object[] { text }; } public String text() { return text; } } static public class Eq extends Exp implements IFieldsToList { public Exp left; public Exp right; public Eq() { } public Eq(Exp left, Exp right) { this.right = right; this.left = left; } public boolean equals(Object o) { if (!(o instanceof Eq)) return false; Eq __5 = (Eq) o; return eq(left, __5.left) && eq(right, __5.right); } public int hashCode() { int h = 2252; h = boostHashCombine(h, _hashCode(left)); h = boostHashCombine(h, _hashCode(right)); return h; } public Object[] _fieldsToList() { return new Object[] { left, right }; } public String text() { return left.text() + " = " + right.text(); } } static public class CombinedStringifier implements IStringifier { public CopyOnWriteArrayList> stringifiers = new CopyOnWriteArrayList(); public IStringifier defaultStringifier = new Stringifier_ToString(); public CombinedStringifier(IPartialStringifier... stringifiers) { addAll(this.stringifiers, stringifiers); } public String toString(A o) { for (var stringifier : stringifiers) { String s = stringifier.toStringOpt(o); if (s != null) return s; } return defaultStringifier.toString(o); } public String toString() { return formatFunctionCall("CombinedStringifier", listPlus((List) stringifiers, defaultStringifier)); } } static public class G22AutoStarter extends MetaWithChangeListeners implements AutoCloseable, IFieldsToList { public G22Utils g22utils; public G22AutoStarter() { } public G22AutoStarter(G22Utils g22utils) { this.g22utils = g22utils; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + g22utils + ")"; } public Object[] _fieldsToList() { return new Object[] { g22utils }; } public transient FieldVar varEnabled_cache; public FieldVar varEnabled() { if (varEnabled_cache == null) varEnabled_cache = varEnabled_load(); return varEnabled_cache; } public FieldVar varEnabled_load() { return new FieldVar(this, "enabled", () -> enabled(), enabled -> enabled(enabled)); } final public G22AutoStarter setEnabled(boolean enabled) { return enabled(enabled); } public G22AutoStarter enabled(boolean enabled) { if (!eq(this.enabled, enabled)) { this.enabled = enabled; change(); } return this; } final public boolean getEnabled() { return enabled(); } public boolean enabled() { return enabled; } volatile public boolean enabled = true; public transient FieldVar varInitialDelay_cache; public FieldVar varInitialDelay() { if (varInitialDelay_cache == null) varInitialDelay_cache = varInitialDelay_load(); return varInitialDelay_cache; } public FieldVar varInitialDelay_load() { return new FieldVar(this, "initialDelay", () -> initialDelay(), initialDelay -> initialDelay(initialDelay)); } final public G22AutoStarter setInitialDelay(int initialDelay) { return initialDelay(initialDelay); } public G22AutoStarter initialDelay(int initialDelay) { if (!eq(this.initialDelay, initialDelay)) { this.initialDelay = initialDelay; change(); } return this; } final public int getInitialDelay() { return initialDelay(); } public int initialDelay() { return initialDelay; } volatile public int initialDelay = 3; public transient FieldVar varNScriptsRun_cache; public FieldVar varNScriptsRun() { if (varNScriptsRun_cache == null) varNScriptsRun_cache = varNScriptsRun_load(); return varNScriptsRun_cache; } public FieldVar varNScriptsRun_load() { return new FieldVar(this, "nScriptsRun", () -> nScriptsRun(), nScriptsRun -> nScriptsRun(nScriptsRun)); } final public G22AutoStarter setNScriptsRun(int nScriptsRun) { return nScriptsRun(nScriptsRun); } public G22AutoStarter nScriptsRun(int nScriptsRun) { if (!eq(this.nScriptsRun, nScriptsRun)) { this.nScriptsRun = nScriptsRun; change(); } return this; } final public int getNScriptsRun() { return nScriptsRun(); } public int nScriptsRun() { return nScriptsRun; } volatile public int nScriptsRun; public transient FieldVar varCurrentScript_cache; public FieldVar varCurrentScript() { if (varCurrentScript_cache == null) varCurrentScript_cache = varCurrentScript_load(); return varCurrentScript_cache; } public FieldVar varCurrentScript_load() { return new FieldVar(this, "currentScript", () -> currentScript(), currentScript -> currentScript(currentScript)); } final public G22AutoStarter setCurrentScript(AutoStartScript currentScript) { return currentScript(currentScript); } public G22AutoStarter currentScript(AutoStartScript currentScript) { if (!eq(this.currentScript, currentScript)) { this.currentScript = currentScript; change(); } return this; } final public AutoStartScript getCurrentScript() { return currentScript(); } public AutoStartScript currentScript() { return currentScript; } volatile public AutoStartScript currentScript; public Flag started = new Flag(); public Flag waited = new Flag(); public Flag ctrlPressed = new Flag(); public List scripts = syncL(); public AutoCloseable ctrlListener; public ReliableSingleThread rst = rst(() -> _run()); public class AutoStartScript extends RunResultWithTimestamps implements IFieldsToList { public G22LeftArrowScript script; public AutoStartScript() { } public AutoStartScript(G22LeftArrowScript script) { this.script = script; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + script + ")"; } public Object[] _fieldsToList() { return new Object[] { script }; } public void run() { try { LASCompileResult cr = script.compileForAutoRun(); if (cr == null) cr = script.compileSaved(); var _cr_2 = cr; run(() -> { G22AutoStarter.this.change(); if (_cr_2 == null) throw fail("Script is not saved: " + script); var parsed = _cr_2.parsedScriptMandatory(); return parsed.get(); }); } catch (Exception __e) { throw rethrow(__e); } } } public void init() { if (ctrlListener != null) return; scripts.clear(); var scripts = conceptsWhere(g22utils.concepts, G22LeftArrowScript.class, "runOnProjectOpen", true); var sorted = sortByCalculatedFieldAlphaNumIC(scripts, s -> s.runOrder); for (var script : sorted) this.scripts.add(new AutoStartScript(script)); change(); ctrlListener = tempAddGlobalCtrlKeyListener(b -> { if (b) { ctrlPressed.raise(); cancel(); } }); } public void start() { print("G22AutoStarter: Start"); if (enabled) rst.get(); } public void _run() { if (!enabled) return; AutoCloseable __1 = g22utils.backgroundProcessesUI.tempAdd("Auto-Start Scripts"); try { if (started.raise()) change(); if (!waited.get()) { print("G22AutoStarter: Sleeping"); while (initialDelay > 0) { sleepSeconds(1); initialDelay(initialDelay - 1); } waited.raise(); change(); print("G22AutoStarter: Slept"); } while (enabled && !done()) { var script = scripts.get(nScriptsRun); currentScript(script); change(); script.run(); nScriptsRun(nScriptsRun + 1); currentScript(null); change(); } change(); close(); } finally { _close(__1); } } public boolean done() { return nScriptsRun >= l(scripts); } public void cancel() { setEnabled(false); } public boolean canResume() { return !done() && !enabled; } public void resume() { if (done()) { infoBox("Nothing to resume - auto-start is done"); return; } if (enabled) { infoBox("Already running"); return; } infoBox("Resuming auto-start"); setEnabled(true); rst.get(); } public String status() { return !enabled ? ctrlPressed.get() ? "Cancelled due to ctrl key" : "Cancelled" : done() ? "Done" : waited.get() ? "Started" : started.get() ? "Pre-start wait (" + formatDouble1(initialDelay) + "s)" : "Not started"; } public String stats() { return status() + ". " + scriptsRunStats(); } public String scriptsRunStats() { return "Scripts run: " + nScriptsRun() + "/" + l(scripts); } public String currentScriptStats() { var s = currentScript; if (s == null) return ""; return "Running: " + s.script; } public void close() { try { if (ctrlListener != null) { { cleanUp(ctrlListener); ctrlListener = null; } change(); } } catch (Exception __e) { throw rethrow(__e); } } public void waitUntilDone() { waitForVarPredicate(varNScriptsRun(), () -> done()); } public boolean ctrlEnabled() { return ctrlListener != null; } } static public class G22LeftArrowScript extends ConceptWithChangeListeners { static final public String _fieldOrder = "description text clearedForAutoRun editingText runOnProjectOpen runOrder runCount lastResultByMode compileResultForAutoRun compileResultForSaved"; public transient FieldVar varDescription_cache; public FieldVar varDescription() { if (varDescription_cache == null) varDescription_cache = varDescription_load(); return varDescription_cache; } public FieldVar varDescription_load() { return new FieldVar(this, "description", () -> description(), description -> description(description)); } final public G22LeftArrowScript setDescription(String description) { return description(description); } public G22LeftArrowScript description(String description) { if (!eq(this.description, description)) { this.description = description; change(); } return this; } final public String getDescription() { return description(); } public String description() { return description; } public String description; public transient FieldVar varText_cache; public FieldVar varText() { if (varText_cache == null) varText_cache = varText_load(); return varText_cache; } public FieldVar varText_load() { return new FieldVar(this, "text", () -> text(), text -> text(text)); } final public G22LeftArrowScript setText(String text) { return text(text); } public G22LeftArrowScript text(String text) { if (!eq(this.text, text)) { this.text = text; change(); } return this; } final public String getText() { return text(); } public String text() { return text; } public String text; public transient FieldVar> varClearedForAutoRun_cache; public FieldVar> varClearedForAutoRun() { if (varClearedForAutoRun_cache == null) varClearedForAutoRun_cache = varClearedForAutoRun_load(); return varClearedForAutoRun_cache; } public FieldVar> varClearedForAutoRun_load() { return new FieldVar>(this, "clearedForAutoRun", () -> clearedForAutoRun(), clearedForAutoRun -> clearedForAutoRun(clearedForAutoRun)); } final public G22LeftArrowScript setClearedForAutoRun(ClearForAutoRun clearedForAutoRun) { return clearedForAutoRun(clearedForAutoRun); } public G22LeftArrowScript clearedForAutoRun(ClearForAutoRun clearedForAutoRun) { if (!eq(this.clearedForAutoRun, clearedForAutoRun)) { this.clearedForAutoRun = clearedForAutoRun; change(); } return this; } final public ClearForAutoRun getClearedForAutoRun() { return clearedForAutoRun(); } public ClearForAutoRun clearedForAutoRun() { return clearedForAutoRun; } public ClearForAutoRun clearedForAutoRun; public transient FieldVar varEditingText_cache; public FieldVar varEditingText() { if (varEditingText_cache == null) varEditingText_cache = varEditingText_load(); return varEditingText_cache; } public FieldVar varEditingText_load() { return new FieldVar(this, "editingText", () -> editingText(), editingText -> editingText(editingText)); } final public G22LeftArrowScript setEditingText(String editingText) { return editingText(editingText); } public G22LeftArrowScript editingText(String editingText) { if (!eq(this.editingText, editingText)) { this.editingText = editingText; change(); } return this; } final public String getEditingText() { return editingText(); } public String editingText() { return editingText; } public String editingText; public boolean runOnProjectOpen = false; public String runOrder; public long runCount; public Map>> lastResultByMode; @Override public void _doneLoading2() { cMigrateField(this, "code", "text"); } public String myType() { return dropPrefix("G22", shortClassName(this)); } public String toString() { return or2(description, myType() + " " + id); } public void initEditingText() { editingText(unnull(or(editingText, text))); } public void receiveEditingText(String text) { printVars_shorten("receiveEditingText", "text", text); editingText(text); } public String stableText() { return text; } final public void save() { completeEdit(); } public void completeEdit() { String t = editingText; printVars_shorten("completeEdit", "t", t); if (t != null) { setTextWithHistory(t); printVars_shorten("completeEdit", "editingText", editingText); } } public void setTextWithHistory(String text) { if (eq(this.text, text)) return; text(text); saveTextToHistory(); } public String textForEditing() { initEditingText(); return editingText; } public File historyFile() { return fileInConceptsDir("History/" + shortDynName(this) + id + ".history"); } public void saveTextToHistory() { saveFieldToHistory("text", text); } public void saveFieldToHistory(String field, String value) { File historyFile = historyFile(); if (historyFile == null) return; String contents = value == null ? " empty" : " (" + nLines(value) + ", " + nChars(value) + "):\n" + indentx(value) + "\n" + "\n"; appendToTextFile(historyFile, "\n===\n" + "Concept ID: " + id + "\n" + "Date: " + dateWithMSUTC() + "\n" + firstToUpper(field) + contents + "===" + "\n"); } public boolean isSaved() { return text != null; } public boolean isSavedDistinctFromAutoRunVersion() { return isSaved() && !eq(text, codeForAutoRun()); } public boolean isEditing() { return editedText() != null; } public boolean isClearForAutoRun() { return clearedForAutoRun != null; } public String editedText() { return eq(editingText, text) ? null : editingText; } public String codeForAutoRun() { return getVar(clearedForAutoRun()); } public String safestCode() { return or(codeForAutoRun(), stableText()); } public void clearForAutoRun() { if (!isSaved()) return; String text = text(); saveFieldToHistory("Auto-runnable code", text); clearedForAutoRun(new ClearForAutoRun(text)); } public void forgetAutoRunCode() { if (!isClearForAutoRun()) return; saveFieldToHistory("Auto-runnable code", null); clearedForAutoRun(null); compileResultForAutoRun = null; } public GazelleV_LeftArrowScriptParser makeParser() { return g22utils(_concepts).leftArrowParser(); } public LASCompileResult newCompileResult() { return new LASCompileResult(); } transient public LASCompileResult compileResultForAutoRun; public LASCompileResult compileForAutoRun() { String code = codeForAutoRun(); if (code == null) return null; var cr = compileResultForAutoRun; if (cr != null && eq(cr.script, code)) return cr; cr = newCompileResult(); cr.script(code); var g22utils = assertNotNull("g22utils", g22utils(_concepts())); var parser = makeParser(); cr.parser(parser); cr.compile(); return compileResultForAutoRun = cr; } transient public LASCompileResult compileResultForSaved; public LASCompileResult compileSaved() { String code = stableText(); if (code == null) return null; var cr = compileResultForSaved; if (cr != null && eq(cr.script, code)) return cr; cr = newCompileResult(); cr.script(code); var g22utils = assertNotNull("g22utils", g22utils(_concepts())); var parser = makeParser(); cr.parser(parser); cr.compile(); return compileResultForSaved = cr; } } static public class JLeftArrowScriptIDE extends MetaWithChangeListeners implements Swingable { final public JLeftArrowScriptIDE setLvScript(SimpleLiveValue lvScript) { return lvScript(lvScript); } public JLeftArrowScriptIDE lvScript(SimpleLiveValue lvScript) { this.lvScript = lvScript; return this; } final public SimpleLiveValue getLvScript() { return lvScript(); } public SimpleLiveValue lvScript() { return lvScript; } public SimpleLiveValue lvScript = stringLiveValue(); final public JLeftArrowScriptIDE setSectionTitle(String sectionTitle) { return sectionTitle(sectionTitle); } public JLeftArrowScriptIDE sectionTitle(String sectionTitle) { this.sectionTitle = sectionTitle; return this; } final public String getSectionTitle() { return sectionTitle(); } public String sectionTitle() { return sectionTitle; } public String sectionTitle = "Left arrow script"; final public JLeftArrowScriptIDE setWithResultPanel(boolean withResultPanel) { return withResultPanel(withResultPanel); } public JLeftArrowScriptIDE withResultPanel(boolean withResultPanel) { this.withResultPanel = withResultPanel; return this; } final public boolean getWithResultPanel() { return withResultPanel(); } public boolean withResultPanel() { return withResultPanel; } public boolean withResultPanel = true; static public String helpText = "Gazelle 22 \"Left Arrow Script\"\r\n------------------------------\r\n\r\n\"Left arrow script\" is one of Gazelle 22's two scripting languages. It is the powerful one of the two. It can do anything Java can do except for defining classes or lambdas.\r\n\r\n-Usually, you write one command per line\r\n-Each command contains at most one action and at most one assignment\r\n-The language is case-sensitive\r\n-You can add comments like in Java with /* */ or //\r\n-You can write multiple commands in one line by separating them with a semicolon\r\n-Arguments to functions are separated by spaces\r\n-You can use integer and string literals like in Java\r\n-You can use true, false and null\r\n\r\nIt's called \"left arrow script\" because the left arrow (variable assignment) is its only actual operator (not counting ; and {}).\r\n\r\n\r\nOperations\r\n----------\r\n\r\nYou can call any global function defined in Gazelle. Example:\r\n\r\n infoBox \"hello\" // show a popup with the text \"hello\"\r\n \r\nYou can assign the result of a function call to a variable:\r\n\r\n time <- tsNow // get current time as a Timestamp object\r\n infoBox time // show as popup\r\n \r\nNote that this script requires 2 lines because only one operation is allowed per command.\r\n \r\nVariables can be overwritten and don't have to be declared.\r\n\r\n\r\nCreating objects\r\n----------------\r\n\r\nYou can create an instance of any Java class and call methods on the object:\r\n\r\n list <- new ArrayList\r\n list add \"hello\"\r\n list add \"world\"\r\n infoBox list // shows [hello, world]\r\n \r\n(Currently you can also say \"list <- ArrayList\", but this is ambiguous and may be removed in a future version.)\r\n \r\nYou can pass parameters to the constructor:\r\n\r\n pair <- new Pair \"hello\" \"world\"\r\n infoBox pair // shows \r\n \r\n\r\nJava operators (+, * etc)\r\n-------------------------\r\n \r\nJava operators can't be used directly but we have functions that do the same thing (if we don't, we'll add them):\r\n\r\n x <- plus 1 2\r\n infoBox x\r\n\r\n\r\nFunction definitions\r\n--------------------\r\n\r\nYou can define functions in your script, with arguments. The function can return a value (which is the result of the last command in the function).\r\n\r\n def doubleMe x { mul x 2 }\r\n\r\n x <- doubleMe 5\r\n infoBox x // shows 10\r\n"; public transient FieldVar varCompileResult_cache; public FieldVar varCompileResult() { if (varCompileResult_cache == null) varCompileResult_cache = varCompileResult_load(); return varCompileResult_cache; } public FieldVar varCompileResult_load() { return new FieldVar(this, "compileResult", () -> compileResult(), compileResult -> compileResult(compileResult)); } final public JLeftArrowScriptIDE setCompileResult(LASCompileResult compileResult) { return compileResult(compileResult); } public JLeftArrowScriptIDE compileResult(LASCompileResult compileResult) { if (!eq(this.compileResult, compileResult)) { this.compileResult = compileResult; change(); } return this; } final public LASCompileResult getCompileResult() { return compileResult(); } public LASCompileResult compileResult() { return compileResult; } transient public LASCompileResult compileResult; transient public RSyntaxTextAreaWithSearch taScript; transient public Q compileQ = new Q(); final public JPanel getButtons() { return buttons(); } public JPanel buttons() { return buttons; } transient public JPanel buttons = jline(); transient public JButton btnRun; transient public CollapsibleLeftPanel collapsibleResultPanel; transient public SingleComponentPanel scpResult = singleComponentPanel(); transient public JPopDownButton popDownButton; transient public LeftArrowCompletionProvider completionProvider; final public JLeftArrowScriptIDE setG22utils(G22Utils g22utils) { return g22utils(g22utils); } public JLeftArrowScriptIDE g22utils(G22Utils g22utils) { this.g22utils = g22utils; return this; } final public G22Utils getG22utils() { return g22utils(); } public G22Utils g22utils() { return g22utils; } transient public G22Utils g22utils; final public JLeftArrowScriptIDE setScriptTimeout(double scriptTimeout) { return scriptTimeout(scriptTimeout); } public JLeftArrowScriptIDE scriptTimeout(double scriptTimeout) { this.scriptTimeout = scriptTimeout; return this; } final public double getScriptTimeout() { return scriptTimeout(); } public double scriptTimeout() { return scriptTimeout; } public double scriptTimeout = 10.0; final public JLeftArrowScriptIDE setShowTitle(boolean showTitle) { return showTitle(showTitle); } public JLeftArrowScriptIDE showTitle(boolean showTitle) { this.showTitle = showTitle; return this; } final public boolean getShowTitle() { return showTitle(); } public boolean showTitle() { return showTitle; } transient public boolean showTitle = true; transient public IF0 makeParser; public GazelleV_LeftArrowScriptParser makeParser() { return makeParser != null ? makeParser.get() : makeParser_base(); } final public GazelleV_LeftArrowScriptParser makeParser_fallback(IF0 _f) { return _f != null ? _f.get() : makeParser_base(); } public GazelleV_LeftArrowScriptParser makeParser_base() { return g22utils.leftArrowParser(); } public class LeftArrowCompletionProvider extends DefaultCompletionProvider { @Override public List getCompletionsImpl(JTextComponent comp) { try { String text = getText(comp); GazelleV_LeftArrowScriptParser parser = makeParser2(); LeftArrowScriptAutoCompleter completer = new LeftArrowScriptAutoCompleter(g22utils, parser); enableScaffolding(completer); completer.seek(text, getCaretPosition(comp)); return map(completer.searcher().withScores(), completion -> { BasicCompletion c = new BasicCompletion(this, completion.get()); c.setRelevance((int) completion.score()); return c; }); } catch (Throwable e) { printStackTrace(e); return ll(); } } } public JComponent wrapStatusLabel(JComponent lbl) { popDownButton = swing(() -> new JPopDownButton("Help")); popDownButton.onFillingMenu(menu -> { addMenuItems(menu, "Show Scripting Help", runnableThread(new Runnable() { public void run() { try { showTextWordWrapped("Gazelle 'Left arrow script' Help", helpText); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showTextWordWrapped(\"Gazelle 'Left arrow script' Help\", helpText)"; } }), "Show Global Class Names", runnableThread(new Runnable() { public void run() { try { showGlobalClassNames(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showGlobalClassNames();"; } })); }); return centerAndEastWithMargin(jBorderlessHigherScrollPane(lbl), jfullcenter(buttons)); } public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { return swing(() -> { taScript = g22utils.newSyntaxTextArea(__1 -> wrapStatusLabel(__1)); bindTextComponentToLiveValue_bothWays(textArea(), lvScript); onCtrlEnter(textArea(), runnableThread(new Runnable() { public void run() { try { runScript(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "runScript();"; } })); awtCalcEvery(textArea(), 1.0, () -> compileQ.add(new Runnable() { public void run() { try { compile(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "compile();"; } })); installCompletionProvider(completionProvider = new LeftArrowCompletionProvider(), textArea()); JComponent vis = taScript.visualize(); if (showTitle) vis = jCenteredSection(sectionTitle, vis); vis = wrapSection(vis); addAll(buttons, btnRun = jbutton("Run", runnableThread(new Runnable() { public void run() { try { runScript(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "runScript();"; } })), popDownButton); if (withResultPanel) { collapsibleResultPanel = new CollapsibleLeftPanel(false, "Result", scpResult, vis); collapsibleResultPanel.sidePanelMargins = c -> withTopAndLeftMargin(c); return collapsibleResultPanel.visualize(); } else return vis; }); } transient public IF1 wrapSection; public JComponent wrapSection(JComponent c) { return wrapSection != null ? wrapSection.get(c) : wrapSection_base(c); } final public JComponent wrapSection_fallback(IF1 _f, JComponent c) { return _f != null ? _f.get(c) : wrapSection_base(c); } public JComponent wrapSection_base(JComponent c) { return c; } public RSyntaxTextArea textArea() { if (taScript == null) visualize(); return taScript.textArea(); } public void setText(String text) { main.setText(textArea(), text); } public boolean visible() { return isShowing(textArea()); } public void compile() { var script = lvScript.get(); var result = compileResult; if (result == null || !eq(result.script, script)) { try { result = newCompileResult(); result.script = script; result.parser = makeParser(); result.parsedScript = result.parser.parse(result.script); print(result.parsedScript); } catch (Throwable e) { print(e); result.compileError = e; } compileResult(result); showStatus(str(compileResult)); updateRunButtonState(); } } public void updateRunButtonState() { setEnabled(btnRun, runButtonShouldBeEnabled()); } transient public IF0 runButtonShouldBeEnabled; public boolean runButtonShouldBeEnabled() { return runButtonShouldBeEnabled != null ? runButtonShouldBeEnabled.get() : runButtonShouldBeEnabled_base(); } final public boolean runButtonShouldBeEnabled_fallback(IF0 _f) { return _f != null ? _f.get() : runButtonShouldBeEnabled_base(); } public boolean runButtonShouldBeEnabled_base() { return compileResult != null && compileResult.runnable(); } public LASCompileResult freshCompileResult() { runInQAndWait(compileQ, new Runnable() { public void run() { try { compile(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "compile();"; } }); return compileResult; } public GazelleV_LeftArrowScript.Script parsedScript() { return freshCompileResult().parsedScript; } transient public Runnable runScript; public void runScript() { if (runScript != null) runScript.run(); else runScript_base(); } final public void runScript_fallback(Runnable _f) { if (_f != null) _f.run(); else runScript_base(); } public void runScript_base() { var result = freshCompileResult(); if (result.parsedScript != null) { var value = okOrError(() -> callCompiledObjectWithTimeout(result.parsedScript)); showScriptResult(value); } } public void showScriptResult(OKOrError result) { if (result.isOK()) { setStatus(shorten(g22utils.stringify(result.get()))); { if (scpResult != null) scpResult.set(new G22JavaObjectVisualizer(g22utils, result.get())); } } else { setStatus(exceptionToStringShorter_dontDropOuterExceptions(result.error())); { if (scpResult != null) scpResult.set(jErrorView(result.getError())); } } collapsibleResultPanel.expand(); } final public void showStatus(String status) { setStatus(status); } public void setStatus(String status) { { if (taScript != null) taScript.setStatus(" " + unnull(status)); } } public void showRuntimeError(Throwable e) { showStatus(exceptionToStringShorter(e)); } transient public IF0 makeVarContextForExecution; public VarContext makeVarContextForExecution() { return makeVarContextForExecution != null ? makeVarContextForExecution.get() : makeVarContextForExecution_base(); } final public VarContext makeVarContextForExecution_fallback(IF0 _f) { return _f != null ? _f.get() : makeVarContextForExecution_base(); } public VarContext makeVarContextForExecution_base() { return new VarContext(); } public Object callCompiledObjectWithTimeout(GazelleV_LeftArrowScript.Script object) { return callCompiledObjectWithTimeout(scriptTimeout, object); } public Object callCompiledObjectWithTimeout(double timeoutSeconds, GazelleV_LeftArrowScript.Script object) { return callCompiledObjectWithTimeout(timeoutSeconds, object, makeVarContextForExecution()); } public Object callCompiledObjectWithTimeout(GazelleV_LeftArrowScript.Script object, VarContext ctx) { return callCompiledObjectWithTimeout(scriptTimeout, object, ctx); } public Object callCompiledObjectWithTimeout(double timeoutSeconds, GazelleV_LeftArrowScript.Script object, VarContext ctx) { return evalWithTimeoutOrTypedException(timeoutSeconds, () -> object.get(ctx)); } public GazelleV_LeftArrowScriptParser makeParser2() { var parser = makeParser(); print("Function containers: " + parser.functionContainers); return parser; } public void showGlobalClassNames() { showText("Global Class Names", pnlToString(toCIMap(makeParser().globalClassNames()))); } public void setEditable(boolean b) { main.setEditable(textArea(), b); } transient public IF0 newCompileResult; public LASCompileResult newCompileResult() { return newCompileResult != null ? newCompileResult.get() : newCompileResult_base(); } final public LASCompileResult newCompileResult_fallback(IF0 _f) { return _f != null ? _f.get() : newCompileResult_base(); } public LASCompileResult newCompileResult_base() { return new LASCompileResult(); } } static public class RSyntaxTextAreaWithSearch implements SearchListener, Swingable { public JPanel panel; final public RSyntaxTextArea getTextArea() { return textArea(); } public RSyntaxTextArea textArea() { return textArea; } public RSyntaxTextArea textArea; public CollapsibleSectionPanel csp; public FindDialog findDialog; public ReplaceDialog replaceDialog; public FindToolBar findToolBar; public ReplaceToolBar replaceToolBar; public StatusBar statusBar; public RSyntaxTextAreaWithSearch() { init(); } public RSyntaxTextAreaWithSearch(IF1 wrapStatusLabel) { this.wrapStatusLabel = wrapStatusLabel; init(); } public RSyntaxTextAreaWithSearch(String text) { init(); setText(text); } public RSyntaxTextAreaWithSearch(RSyntaxTextArea textArea) { this.textArea = textArea; init(); } public JComponent visualize() { return panel; } public void init() { swing(() -> { rsyntaxTextArea_fixNumPad(); initSearchDialogs(); panel = new JPanel(new BorderLayout()); csp = new CollapsibleSectionPanel(); panel.add(csp); if (textArea == null) textArea = javaxSyntaxTextArea(); RTextScrollPane sp = new RTextScrollPane(textArea); csp.add(sp); ErrorStrip errorStrip = new ErrorStrip(textArea); panel.add(errorStrip, BorderLayout.LINE_END); statusBar = new StatusBar(); panel.add(statusBar, BorderLayout.SOUTH); }); } transient public IF1 wrapStatusLabel; public JComponent wrapStatusLabel(JComponent label) { return wrapStatusLabel != null ? wrapStatusLabel.get(label) : wrapStatusLabel_base(label); } final public JComponent wrapStatusLabel_fallback(IF1 _f, JComponent label) { return _f != null ? _f.get(label) : wrapStatusLabel_base(label); } public JComponent wrapStatusLabel_base(JComponent label) { return label; } public void addItem(Action a, ButtonGroup bg, JMenu menu) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(a); bg.add(item); menu.add(item); } public void menuLessOperation() { swing(() -> { var mb = createMenuBar(); for (var menu : getMenus(mb)) for (var menuItem : getMenuItems(menu)) { var ks = menuItem.getAccelerator(); if (ks != null) { var action = menuItem.getAction(); textArea.getInputMap().put(ks, action); } } }); } public JMenuBar createMenuBar() { JMenuBar mb = new JMenuBar(); JMenu menu = new JMenu("Search"); menu.add(new JMenuItem(new ShowFindDialogAction())); menu.add(new JMenuItem(new ShowReplaceDialogAction())); menu.add(new JMenuItem(new GoToLineAction())); menu.addSeparator(); int ctrl = getToolkit().getMenuShortcutKeyMask(); int shift = InputEvent.SHIFT_MASK; KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_F, ctrl | shift); Action a = csp.addBottomComponent(ks, findToolBar); a.putValue(Action.NAME, "Show Find Search Bar"); menu.add(new JMenuItem(a)); ks = KeyStroke.getKeyStroke(KeyEvent.VK_H, ctrl | shift); a = csp.addBottomComponent(ks, replaceToolBar); a.putValue(Action.NAME, "Show Replace Search Bar"); menu.add(new JMenuItem(a)); mb.add(menu); return mb; } public String getSelectedText() { return textArea.getSelectedText(); } public void initSearchDialogs() { findDialog = new FindDialog((java.awt.Dialog) null, this); replaceDialog = new ReplaceDialog((java.awt.Dialog) null, this); SearchContext context = findDialog.getSearchContext(); replaceDialog.setSearchContext(context); findToolBar = new FindToolBar(this); findToolBar.setSearchContext(context); replaceToolBar = new ReplaceToolBar(this); replaceToolBar.setSearchContext(context); } @Override public void searchEvent(SearchEvent e) { SearchEvent.Type type = e.getType(); SearchContext context = e.getSearchContext(); SearchResult result = null; switch(type) { default: case MARK_ALL: result = SearchEngine.markAll(textArea, context); break; case FIND: result = SearchEngine.find(textArea, context); if (!result.wasFound()) { Caret c = textArea.getCaret(); int pos = c.getDot(); if (context.getSearchForward()) { c.setDot(0); } else { c.setDot(textArea.getDocument().getLength()); } result = SearchEngine.find(textArea, context); if (!result.wasFound()) { c.setDot(pos); UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } break; case REPLACE: result = SearchEngine.replace(textArea, context); if (!result.wasFound()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } break; case REPLACE_ALL: result = SearchEngine.replaceAll(textArea, context); JOptionPane.showMessageDialog(null, result.getCount() + " occurrences replaced."); break; } String text = null; if (result.wasFound()) { text = "Text found; occurrences marked: " + result.getMarkedCount(); } else if (type == SearchEvent.Type.MARK_ALL) { if (result.getMarkedCount() > 0) { text = "Occurrences marked: " + result.getMarkedCount(); } else { text = ""; } } else { text = "Text not found"; } setStatus(text); } public class GoToLineAction extends AbstractAction { public GoToLineAction() { super("Go To Line..."); int c = getToolkit().getMenuShortcutKeyMask(); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_L, c)); } public void actionPerformed(ActionEvent e) { findDialog.setVisible(false); replaceDialog.setVisible(false); GoToDialog dialog = new GoToDialog((java.awt.Dialog) null); dialog.setMaxLineNumberAllowed(textArea.getLineCount()); showDialogOnSameScreen(dialog, panel); int line = dialog.getLineNumber(); if (line > 0) { try { textArea.setCaretPosition(textArea.getLineStartOffset(line - 1)); } catch (BadLocationException ble) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); ble.printStackTrace(); } } } } public class ShowFindDialogAction extends AbstractAction { public ShowFindDialogAction() { super("Find..."); int c = getToolkit().getMenuShortcutKeyMask(); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, c)); } public void actionPerformed(ActionEvent e) { replaceDialog.setVisible(false); showDialogOnSameScreen(findDialog, panel); } } public class ShowReplaceDialogAction extends AbstractAction { public ShowReplaceDialogAction() { super("Replace..."); int c = getToolkit().getMenuShortcutKeyMask(); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_H, c)); } public void actionPerformed(ActionEvent e) { findDialog.setVisible(false); showDialogOnSameScreen(replaceDialog, panel); } } public class StatusBar extends JPanel { public JLabel label; public StatusBar() { label = new JLabel(" "); setLayout(new BorderLayout()); add(wrapStatusLabel(label), BorderLayout.CENTER); add(new JLabel(new SizeGripIcon()), BorderLayout.EAST); } public void setText(String label) { main.setText(this.label, label); } } public void setStatus(String text) { statusBar.setText(text); } public void setText(String text) { main.setText(textArea, text); } public String getText() { return main.getText(textArea); } public void setEditorFont(final Font font) { swing(() -> { SyntaxScheme ss = textArea.getSyntaxScheme(); ss = (SyntaxScheme) ss.clone(); for (int i = 0; i < ss.getStyleCount(); i++) if (ss.getStyle(i) != null) ss.getStyle(i).font = font; textArea.setSyntaxScheme(ss); textArea.setFont(font); }); } public Font getEditorFont() { return swing(new F0() { public Font get() { try { return textArea.getFont(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return textArea.getFont();"; } }); } public int getEditorFontSize() { return getEditorFont().getSize(); } public void setEditorFontSize(int size) { setEditorFont(deriveFont(getEditorFont(), size)); } public RSyntaxDocument getDocument() { return (RSyntaxDocument) textArea.getDocument(); } public Toolkit getToolkit() { return panel.getToolkit(); } } static public class G22Label extends ConceptWithGlobalID { public String name; public String toString() { return name; } final public boolean textIs(String text) { return nameIs(text); } public boolean nameIs(String text) { return eqic(name, text); } } static public class ImageSurface_PositionToolTip extends ImageSurfaceMouseHandler { public ImageSurface_PositionToolTip(ImageSurface is) { if (containsInstance(is.tools, ImageSurface_PositionToolTip.class)) return; register(is); } final public void mouseDragged(MouseEvent e) { mouseMoved(e); } public void mouseMoved(MouseEvent e) { setToolTip(is, getPt(e)); } } static public class ListAndIndex implements IFieldsToList { static final public String _fieldOrder = "list idx"; public List list; public int idx; public ListAndIndex() { } public ListAndIndex(List list, int idx) { this.idx = idx; this.list = list; } public boolean equals(Object o) { if (!(o instanceof ListAndIndex)) return false; ListAndIndex __1 = (ListAndIndex) o; return eq(list, __1.list) && idx == __1.idx; } public int hashCode() { int h = 276903961; h = boostHashCombine(h, _hashCode(list)); h = boostHashCombine(h, _hashCode(idx)); return h; } public Object[] _fieldsToList() { return new Object[] { list, idx }; } public boolean atEnd() { return idx >= l(list); } public A get() { return _get(list, idx); } public int size() { return l(list); } public String toString() { return subList(list, 0, idx) + ", then " + subList(list, idx); } public ListAndIndex plus(int ofs) { return new ListAndIndex(list, idx + ofs); } public List list() { return list; } final public int idx() { return index(); } public int index() { return idx; } } static public class TokenRange extends IntRange { public TokenRange() { } public TokenRange(int start, int end) { this.end = end; this.start = start; } } static public interface G22MasterStuff { public void openDatabase(File dir); public void closeDatabase(File dir); public Collection openConceptDirs(); public G22MasterStuff onLoadedDBsChange(Runnable r); public G22MasterStuff removeLoadedDBsChangeListener(Runnable r); public IF1 makeClassFinder(); } static public class ConceptWithGlobalID extends Concept implements IHasGlobalID { public GlobalID globalID = aGlobalIDObjUnlessLoading(); public GlobalID globalID() { return globalID; } public String globalIDStr() { return strOrNull(globalID); } public String prependGlobalID(String s) { return globalID == null ? s : "[" + globalID + "] " + s; } } static public class OKOrError implements IF0 { public A value; final public Throwable getError() { return error(); } public Throwable error() { return error; } public Throwable error; public OKOrError() { } public OKOrError(A value) { this.value = value; } public OKOrError(boolean dummy, Throwable error) { this.error = error; assertNotNull(error); } final public boolean isOK() { return ok(); } public boolean ok() { return error == null; } public String toString() { return ok() ? str(value) : "Error: " + str(error); } public A get() { return !ok() ? null : value; } public A getMandatory() { if (!ok()) throw rethrow(error); return value; } static public OKOrError ok(A a) { return new OKOrError(a); } static public OKOrError error(Throwable error) { return new OKOrError(false, error); } } static public class LASCompileResult { final public LASCompileResult setScript(String script) { return script(script); } public LASCompileResult script(String script) { this.script = script; return this; } final public String getScript() { return script(); } public String script() { return script; } public String script; final public LASCompileResult setParser(GazelleV_LeftArrowScriptParser parser) { return parser(parser); } public LASCompileResult parser(GazelleV_LeftArrowScriptParser parser) { this.parser = parser; return this; } final public GazelleV_LeftArrowScriptParser getParser() { return parser(); } public GazelleV_LeftArrowScriptParser parser() { return parser; } public GazelleV_LeftArrowScriptParser parser; final public LASCompileResult setCompileError(Throwable compileError) { return compileError(compileError); } public LASCompileResult compileError(Throwable compileError) { this.compileError = compileError; return this; } final public Throwable getCompileError() { return compileError(); } public Throwable compileError() { return compileError; } public Throwable compileError; public GazelleV_LeftArrowScript.Script parsedScript; public String toString() { return compileError != null ? exceptionToStringShorter_dontDropOuterExceptions(compileError) : "Compiled OK"; } public boolean runnable() { return parsedScript != null; } public void compile() { try { parsedScript = parser.parse(script); print(parsedScript); } catch (Throwable e) { print(e); compileError(e); } } public GazelleV_LeftArrowScript.Script parsedScript() { return parsedScript; } public GazelleV_LeftArrowScript.Script parsedScriptMandatory() { if (compileError != null) throw fail(compileError); return parsedScript; } } static public class WithTimestamp extends Var { public long timestamp; final public Timestamp timestamp() { return getTimestamp(); } final public Timestamp timeStamp() { return getTimestamp(); } public Timestamp getTimestamp() { return timestamp == 0 ? null : new Timestamp(timestamp); } public WithTimestamp() { } public WithTimestamp(long timestamp, A value) { super(value); this.timestamp = timestamp; } public WithTimestamp(A value) { this(now(), value); } public Timestamp timestampObj() { return timestamp == 0 ? null : new Timestamp(timestamp); } public String toString() { return toStringWithTimestamp(super.toString()); } public String toStringQuoted() { return toStringWithTimestamp(quote(super.toString())); } public String toStringWithTimestamp(String s) { return s + " at " + localDateWithSeconds(timestamp); } public boolean olderThanMinutes(double minutes) { return elapsedMinutes_timestamp(timestamp) >= minutes; } public boolean olderThanSeconds(double seconds) { return elapsedSeconds_timestamp(timestamp) >= seconds; } } static public class CollapsibleLeftPanel extends MetaWithChangeListeners implements Swingable { public transient FieldVar varSidePanelName_cache; public FieldVar varSidePanelName() { if (varSidePanelName_cache == null) varSidePanelName_cache = varSidePanelName_load(); return varSidePanelName_cache; } public FieldVar varSidePanelName_load() { return new FieldVar(this, "sidePanelName", () -> sidePanelName(), sidePanelName -> sidePanelName(sidePanelName)); } final public CollapsibleLeftPanel setSidePanelName(String sidePanelName) { return sidePanelName(sidePanelName); } public CollapsibleLeftPanel sidePanelName(String sidePanelName) { if (!eq(this.sidePanelName, sidePanelName)) { this.sidePanelName = sidePanelName; change(); } return this; } final public String getSidePanelName() { return sidePanelName(); } public String sidePanelName() { return sidePanelName; } volatile public String sidePanelName; public JComponent sideComponent, mainComponent; public JSplitPane splitPane; public transient FieldVar varExpanded_cache; public FieldVar varExpanded() { if (varExpanded_cache == null) varExpanded_cache = varExpanded_load(); return varExpanded_cache; } public FieldVar varExpanded_load() { return new FieldVar(this, "expanded", () -> expanded(), expanded -> expanded(expanded)); } final public CollapsibleLeftPanel setExpanded(boolean expanded) { return expanded(expanded); } public CollapsibleLeftPanel expanded(boolean expanded) { if (!eq(this.expanded, expanded)) { this.expanded = expanded; change(); } return this; } final public boolean getExpanded() { return expanded(); } public boolean expanded() { return expanded; } volatile public boolean expanded = false; public SingleComponentPanel scp = singleComponentPanel(); public CollapsibleLeftPanel(boolean expanded, String sidePanelName, JComponent sideComponent, JComponent mainComponent) { this.mainComponent = mainComponent; this.sideComponent = sideComponent; this.sidePanelName = sidePanelName; this.expanded = expanded; } public void expand() { if (scaffolding()) print("CollapsibleLeftPanel.expand"); setExpanded(true); } public void collapse() { setExpanded(false); } public void updateScp() { swing(() -> { if (metaGet("scaffolding") != null) scaffoldCalled(this, "updateScp"); if (expanded) { splitPane().setRightComponent(mainComponent); scp.set(splitPane()); } else scp.set(westAndCenterWithMargin(sidePanelMargins(vstack(expandButton())), mainComponent)); }); } public JComponent expandButton() { return jClickableImage_instantToolTip("#1103075", "Expand " + sidePanelName, new Runnable() { public void run() { try { expand(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "expand();"; } }); } public JComponent collapseButton() { return jClickableImage_instantToolTip("#1103076", "Collapse " + sidePanelName, new Runnable() { public void run() { try { collapse(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "collapse();"; } }); } public JComponent wrappedSideComponent() { return sidePanelMargins(northAndCenterWithMargin(westAndCenterWithMargin(collapseButton(), liveValueLabel(varSidePanelName())), sideComponent)); } public JSplitPane splitPane() { if (scaffolding()) print("splitPane " + splitPane); if (splitPane == null) { splitPane = jhsplit(0.25, wrappedSideComponent(), null); varExpanded().onChangeAndNow(new Runnable() { public void run() { try { updateScp(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "updateScp();"; } }); } return splitPane; } transient public IF1 sidePanelMargins; public JComponent sidePanelMargins(JComponent c) { return sidePanelMargins != null ? sidePanelMargins.get(c) : sidePanelMargins_base(c); } final public JComponent sidePanelMargins_fallback(IF1 _f, JComponent c) { return _f != null ? _f.get(c) : sidePanelMargins_base(c); } public JComponent sidePanelMargins_base(JComponent c) { return c; } public JComponent visualize() { splitPane(); return scp; } } static public class JPopDownButton extends JButton { public String menuPosition = "left"; public JPopDownButton() { this(""); } public JPopDownButton(String text) { super(joinNemptiesWithSpace(text, unicode_downPointingTriangle())); main.addActionListener(this, new Runnable() { public void run() { try { openMenu(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "openMenu();"; } }); } public JPopDownButton(IVF1 fillMenu) { this(); this.fillMenu = fillMenu; } transient public Set> onFillingMenu; public JPopDownButton onFillingMenu(IVF1 f) { onFillingMenu = createOrAddToSyncLinkedHashSet(onFillingMenu, f); return this; } public JPopDownButton removeFillingMenuListener(IVF1 f) { main.remove(onFillingMenu, f); return this; } public void fillingMenu(JPopupMenu menu) { pcallFAll(onFillingMenu, menu); } transient public IVF1 fillMenu; public void fillMenu(JPopupMenu menu) { if (fillMenu != null) fillMenu.get(menu); else fillMenu_base(menu); } final public void fillMenu_fallback(IVF1 _f, JPopupMenu menu) { if (_f != null) _f.get(menu); else fillMenu_base(menu); } public void fillMenu_base(JPopupMenu menu) { fillingMenu(menu); } public void openMenu() { JPopupMenu menu = new JPopupMenu(); int emptyCount = menu.getComponentCount(); fillMenu(menu); if (menu.getComponentCount() == emptyCount) return; int x = 0; if (eq(menuPosition, "center")) x = (getWidth() - getPreferredWidth(menu)) / 2; else if (eq(menuPosition, "right")) x = getWidth() - getPreferredWidth(menu); menu.show(this, x, getHeight()); } } public interface IStringifier { public String toString(A o); } static public class ConceptWithChangeListeners extends Concept implements IHasChangeListeners, ChangeTriggerable { transient public Set onChange; public ConceptWithChangeListeners onChange(Runnable r) { onChange = createOrAddToSyncLinkedHashSet(onChange, r); return this; } public ConceptWithChangeListeners removeChangeListener(Runnable r) { main.remove(onChange, r); return this; } public void fireChange() { pcallFAll(onChange); } public void _onChange() { super._onChange(); fireChange(); } public void change() { super.change(); } } static public class SimpleLiveValue extends LiveValue implements IVarWithNotify { transient public Set onChange; public SimpleLiveValue onChange(Runnable r) { onChange = createOrAddToSyncLinkedHashSet(onChange, r); return this; } public SimpleLiveValue removeChangeListener(Runnable r) { main.remove(onChange, r); return this; } public void change() { pcallFAll(onChange); } public Class type; volatile public A value; public SimpleLiveValue(Class type) { this.type = type; } public SimpleLiveValue(Class type, A value) { this.value = value; this.type = type; } public Class getType() { return type; } public A get() { return value; } public void fireChanged() { change(); } public void set(A a) { if (neq(value, a)) { value = a; fireChanged(); } } } static public class RunResultWithTimestamps { final public RunResultWithTimestamps setStarted(Timestamp started) { return started(started); } public RunResultWithTimestamps started(Timestamp started) { this.started = started; return this; } final public Timestamp getStarted() { return started(); } public Timestamp started() { return started; } public Timestamp started; final public RunResultWithTimestamps setEnded(Timestamp ended) { return ended(ended); } public RunResultWithTimestamps ended(Timestamp ended) { this.ended = ended; return this; } final public Timestamp getEnded() { return ended(); } public Timestamp ended() { return ended; } public Timestamp ended; final public RunResultWithTimestamps setResult(OKOrError result) { return result(result); } public RunResultWithTimestamps result(OKOrError result) { this.result = result; return this; } final public OKOrError getResult() { return result(); } public OKOrError result() { return result; } public OKOrError result; final public RunResultWithTimestamps setPrintOutput(CharSequence printOutput) { return printOutput(printOutput); } public RunResultWithTimestamps printOutput(CharSequence printOutput) { this.printOutput = printOutput; return this; } final public CharSequence getPrintOutput() { return printOutput(); } public CharSequence printOutput() { return printOutput; } public CharSequence printOutput; public void run(IF0 f) { printOutput(hijackPrint_tee(new Runnable() { public void run() { try { started(tsNow()); result(okOrError(f)); ended(tsNow()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "started(tsNow());\r\n result(okOrError(f));\r\n ended(tsNow());"; } })); } } static public class FieldVar extends VarWithNotify { public IHasChangeListeners containingObject; public String fieldName; public IF0 getter; public IVF1 setter; public FieldVar(IHasChangeListeners containingObject, String fieldName, IF0 getter, IVF1 setter) { this.setter = setter; this.getter = getter; this.fieldName = fieldName; this.containingObject = containingObject; containingObject.onChangeAndNow(() -> _updateFromObject()); } public void _updateFromObject() { set(getter.get()); } public void fireChange() { setter.get(get()); super.fireChange(); } public FieldVar onChange(IVF1 r) { if (r != null) onChange(() -> r.get(get())); return this; } } static public class ReliableSingleThread implements Runnable { public boolean _isTransient() { return true; } public Object runnable; public String name = "Single Thread"; public boolean cancelBeforeTrigger = false; public boolean waitBetweenCancelAndTrigger = false; public F0 enter; public int cancelTimeOut = 10000; public boolean trigger = false; public Thread thread; public WeakReference threadBeingCancelled; public List inserts = syncL(); public ReliableSingleThread(Object runnable) { this.runnable = runnable; } public void trigger() { go(); } synchronized public void go() { if (cancelBeforeTrigger) cancelAndPossiblyWait(); trigger = true; if (!running()) { AutoCloseable __1 = callF(enter); try { thread = startThread(name, new Runnable() { public void run() { try { AutoCloseable __2 = callF(enter); try { _run(); } finally { _close(__2); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp callF(enter);\r\n _run();"; } }); } finally { _close(__1); } } } public void run() { go(); } public void get() { go(); } synchronized public boolean running() { return thread != null; } public void triggerAndWait() { trigger(); waitUntilDone(); } public void waitUntilDone() { while (running()) sleep(1); } public void _run() { try { while (licensed()) { Thread oldThread; synchronized (this) { var currentInserts = syncGetAndClear(inserts); pcallFAll(currentInserts); if (!trigger) { thread = null; break; } oldThread = getWeakRef(threadBeingCancelled); trigger = false; } if (oldThread != null && oldThread != currentThread()) oldThread.join(cancelTimeOut); pcallF(runnable); } } catch (Exception __e) { throw rethrow(__e); } } synchronized public void cancel() { if (thread == null) return; threadBeingCancelled = new WeakReference(thread); cancelAndInterruptThread(thread); thread = null; } public void cancelAndWait() { Thread _thread; synchronized (this) { if (thread == null) return; _thread = thread; threadBeingCancelled = new WeakReference(thread); thread = null; } cancelAndInterruptThread(_thread); } public void cancelAndTrigger() { cancelAndPossiblyWait(); trigger(); } synchronized public boolean triggered() { return trigger; } public void cleanMeUp() { cancel(); } public ReliableSingleThread cancelBeforeTrigger() { cancelBeforeTrigger = true; return this; } public void cancelAndPossiblyWait() { if (waitBetweenCancelAndTrigger) cancel(); } public void insert(Runnable r) { inserts.add(r); trigger(); } synchronized public boolean hasThread() { return thread != null; } } static public class VarMatches extends WrappedMap { public VarMatches() { super(new LinkedHashMap()); } public VarMatches(Map map) { this(); main.putAll(this, map); } } abstract static public class ImageSurfaceMouseHandler extends MouseAdapter implements AutoCloseable { public ImageSurface is; public void register(ImageSurface is) { this.is = is; is.tools.add(this); is.addMouseListener(this); is.addMouseMotionListener(this); } public void close() { try { if (is == null) return; is.tools.remove(this); is.removeMouseListener(this); is.removeMouseMotionListener(this); is = null; } catch (Exception __e) { throw rethrow(__e); } } public Pt getPt(MouseEvent e) { return toPt(getPoint(e)); } public Point getPoint(MouseEvent e) { return new Point((int) (e.getX() / is.getZoomX()), (int) (e.getY() / is.getZoomY())); } public ImageSurface getImageSurface() { return is; } } enum G22ScriptMode { edit, saved, autoRunnable } static public class PersistableOKOrError implements IF0 { public A value; final public PersistableThrowable getError() { return error(); } public PersistableThrowable error() { return error; } public PersistableThrowable error; public PersistableOKOrError() { } public PersistableOKOrError(A value) { this.value = value; } public PersistableOKOrError(boolean dummy, PersistableThrowable error) { this.error = error; assertNotNull(error); } final public boolean isOK() { return ok(); } public boolean ok() { return error == null; } public String toString() { return ok() ? str(value) : "Error: " + str(error); } public A get() { return !ok() ? null : value; } public A getMandatory() { if (!ok()) throw error.asRuntimeException(); return value; } static public PersistableOKOrError ok(A a) { return new PersistableOKOrError(a); } static public PersistableOKOrError error(PersistableThrowable error) { return new PersistableOKOrError(false, error); } } static public class IntRange { public int start, end; public IntRange() { } public IntRange(int start, int end) { this.end = end; this.start = start; } public IntRange(IntRange r) { start = r.start; end = r.end; } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } final public int length() { return end - start; } final public boolean empty() { return start >= end; } final public boolean isEmpty() { return start >= end; } static public String _fieldOrder = "start end"; public String toString() { return "[" + start + ";" + end + "]"; } } static public interface IAutoCloseableF0 extends IF0, AutoCloseable { } static public class Flag implements Runnable { public boolean up = false; public synchronized boolean raise() { if (!up) { up = true; notifyAll(); return true; } else return false; } public synchronized void waitUntilUp() { while (!up) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public boolean waitUntilUp(double timeout) { return waitUntilUp(toMS(timeout)); } public synchronized boolean waitUntilUp(long timeout) { if (!up) { try { wait(timeout); } catch (InterruptedException e) { e.printStackTrace(); } } return isUp(); } public synchronized boolean isUp() { return up; } public boolean get() { return isUp(); } public String toString() { return isUp() ? "up" : "down"; } public void waitForThisOr(Flag otherFlag) { try { while (!isUp() && !otherFlag.isUp()) Thread.sleep(50); } catch (Exception __e) { throw rethrow(__e); } } public void run() { raise(); } } static public class G22JavaObjectVisualizer implements Swingable, IFieldsToList { public G22Utils g22utils; public G22JavaObjectVisualizer() { } public G22JavaObjectVisualizer(G22Utils g22utils) { this.g22utils = g22utils; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + g22utils + ")"; } public Object[] _fieldsToList() { return new Object[] { g22utils }; } final public G22JavaObjectVisualizer setWithTypeAndTime(boolean withTypeAndTime) { return withTypeAndTime(withTypeAndTime); } public G22JavaObjectVisualizer withTypeAndTime(boolean withTypeAndTime) { this.withTypeAndTime = withTypeAndTime; return this; } final public boolean getWithTypeAndTime() { return withTypeAndTime(); } public boolean withTypeAndTime() { return withTypeAndTime; } public boolean withTypeAndTime = true; final public G22JavaObjectVisualizer setSingleLineLayout(boolean singleLineLayout) { return singleLineLayout(singleLineLayout); } public G22JavaObjectVisualizer singleLineLayout(boolean singleLineLayout) { this.singleLineLayout = singleLineLayout; return this; } final public boolean getSingleLineLayout() { return singleLineLayout(); } public boolean singleLineLayout() { return singleLineLayout; } public boolean singleLineLayout = false; final public G22JavaObjectVisualizer setMaxElements(int maxElements) { return maxElements(maxElements); } public G22JavaObjectVisualizer maxElements(int maxElements) { this.maxElements = maxElements; return this; } final public int getMaxElements() { return maxElements(); } public int maxElements() { return maxElements; } public int maxElements = 1000; final public G22JavaObjectVisualizer setObject(Object object) { return object(object); } public G22JavaObjectVisualizer object(Object object) { this.object = object; return this; } final public Object getObject() { return object(); } public Object object() { return object; } transient public Object object; final public G22JavaObjectVisualizer setNanos(long nanos) { return nanos(nanos); } public G22JavaObjectVisualizer nanos(long nanos) { this.nanos = nanos; return this; } final public long getNanos() { return nanos(); } public long nanos() { return nanos; } transient public long nanos = -1; public G22JavaObjectVisualizer(G22Utils g22utils, Object object) { this.object = object; this.g22utils = g22utils; } public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { List infos = new ArrayList(); JComponent c = visualizeObject(object); if (withTypeAndTime) { infos.add(shortClassName(object)); if (object instanceof Collection) infos.add("size " + n2((Collection) object)); } if (withTypeAndTime) { String type = joinNemptiesWithComma(infos); String timeDesc = nanos < 0 ? "" : formatElapsedTimeWithAppropriateUnit(nanosToSeconds(nanos)); c = northAndCenterWithMargins(westAndEastWithMargin(withLabel("Type:", jlabel(type)), empty(timeDesc) ? jpanel() : withLabel("Execution time:", jlabel(timeDesc))), c); } return c; } public JComponent visualizeObject(Object object) { return mainVisualizer().visualize(object); } public ObjectVisualizer mainVisualizer() { return new ObjectVisualizer().recurse(true).bigFont(true); } public class ObjectVisualizer { final public ObjectVisualizer setRecurse(boolean recurse) { return recurse(recurse); } public ObjectVisualizer recurse(boolean recurse) { this.recurse = recurse; return this; } final public boolean getRecurse() { return recurse(); } public boolean recurse() { return recurse; } public boolean recurse = false; final public ObjectVisualizer setBigFont(boolean bigFont) { return bigFont(bigFont); } public ObjectVisualizer bigFont(boolean bigFont) { this.bigFont = bigFont; return this; } final public boolean getBigFont() { return bigFont(); } public boolean bigFont() { return bigFont; } public boolean bigFont = false; public ObjectVisualizer subVisualizer() { return new ObjectVisualizer(); } public JComponent makeBig(JComponent c) { if (bigFont) return fontSizePlus(10, c); return c; } public JComponent visualize(Object object) { try { return visualize2(object); } catch (Throwable e) { return jErrorView(new RuntimeException("Visualization error", e)); } } public JComponent visualize2(Object object) { if (object instanceof Throwable) return jErrorView((Throwable) object); if (object == null || eq(object, "")) return jpanel(); if (object instanceof Integer) object = toLong((Integer) object); if (object instanceof Long) return makeBig(jcenteredLabel(n2((Long) object))); if (object instanceof Number) return makeBig(jcenteredLabel(str((Number) object))); if (object instanceof MakesBufferedImage) object = toBufferedImage((MakesBufferedImage) object); if (object instanceof BufferedImage) return jscroll_centered_borderless(g22utils.stdImageSurface((BufferedImage) object)); if (recurse) { if (object instanceof Collection) { var sub = subVisualizer(); return jscroll_centered_borderless(vstackWithSpacing(map(cloneTakeFirst(maxElements, ((Collection) object)), element -> sub.visualize(element)))); } } String string = str(object); if (containsNewLine(string)) return jscroll_borderless(wordWrapTypeWriterTextArea(string)); return jcenteredlabel(shorten(string)); } } } static public class ClearForAutoRun extends Var { public ClearForAutoRun() { } public ClearForAutoRun(A code) { super(code); } } static public class Stringifier_ToString implements IStringifier { public String toString(Object o) { return str(o); } } public interface IPartialStringifier { public String toStringOpt(A o); } static public class G22TypeDesc { public String exactClassName; public Set implementedClassNames; } static public List _stickyLibs_1400546 = ll("#1400546", "#1400547", "#1400548"); static public class MetaWithChangeListeners extends Meta implements IHasChangeListeners, ChangeTriggerable { transient public Set onChange; public MetaWithChangeListeners onChange(Runnable r) { onChange = createOrAddToSyncLinkedHashSet(onChange, r); return this; } public MetaWithChangeListeners removeChangeListener(Runnable r) { main.remove(onChange, r); return this; } public void change() { pcallFAll(onChange); } } static public class Scored extends Var { public float score; public Scored() { } public Scored(A a, float score) { super(a); this.score = score; } public Scored(A a, double score) { super(a); this.score = (float) score; } public float score() { return score; } public String toString() { return toIntPercent(score) + "%: " + str(get()); } } public interface IVarWithNotify extends IVar, IF0WithChangeListeners { default public IVarWithNotify onChange(IVF1 r) { if (r == null) return this; onChange(() -> r.get(get())); return this; } default public IVarWithNotify onChangeAndNow(IVF1 r) { if (r == null) return this; onChangeAndNow(() -> r.get(get())); return this; } } static public class WrappedMap extends AbstractMap { public Map map; public WrappedMap() { } public WrappedMap(Map map) { this.map = map; } public B get(Object key) { return map.get(key); } public B put(A key, B value) { return map.put(key, value); } public boolean containsKey(Object key) { return map.containsKey(key); } public Set> entrySet() { return map.entrySet(); } } static public interface IHasGlobalID { public GlobalID globalID(); } public interface IHasChangeListeners { public IHasChangeListeners onChange(Runnable r); public IHasChangeListeners removeChangeListener(Runnable r); default public IHasChangeListeners onChangeAndNow(Runnable l) { onChange(l); callF(l); return this; } } static public class VarWithNotify extends Var implements IVarWithNotify { transient public Set onChange; public VarWithNotify onChange(Runnable r) { onChange = createOrAddToSyncLinkedHashSet(onChange, r); return this; } public VarWithNotify removeChangeListener(Runnable r) { main.remove(onChange, r); return this; } public void fireChange() { pcallFAll(onChange); } public VarWithNotify() { } public VarWithNotify(A a) { super(a); } public void set(A a) { A v = get(); if (eq(v, a)) { return; } synchronized (this) { this.v = a; notifyAll(); } fireChange(); } } static abstract public class LiveValue implements IGetterWithNotify { abstract public Class getType(); public abstract A get(); } static public class Timestamp implements Comparable, IFieldsToList { public long date; public Timestamp(long date) { this.date = date; } public boolean equals(Object o) { if (!(o instanceof Timestamp)) return false; Timestamp __1 = (Timestamp) o; return date == __1.date; } public int hashCode() { int h = 2059094262; h = boostHashCombine(h, _hashCode(date)); return h; } public Object[] _fieldsToList() { return new Object[] { date }; } public Timestamp() { date = now(); } public long unixDate() { return date; } public String toString() { return formatLocalDateWithSeconds(date); } public int compareTo(Timestamp t) { return t == null ? 1 : cmp(date, t.date); } public Timestamp plus(Seconds seconds) { return plus(seconds == null ? null : seconds.getDouble()); } final public Timestamp plusSeconds(double seconds) { return plus(seconds); } public Timestamp plus(double seconds) { return new Timestamp(date + toMS(seconds)); } public long minus(Timestamp ts) { return unixDate() - ts.unixDate(); } public long sysTime() { return clockTimeToSystemTime(date); } } public interface ChangeTriggerable { public void change(); } public interface IGetterWithNotify extends IF0, IHasChangeListeners { } public interface IF0WithChangeListeners extends IF0, IHasChangeListeners { } static public class Seconds implements Comparable, IFieldsToList { public double seconds; public Seconds() { } public Seconds(double seconds) { this.seconds = seconds; } public boolean equals(Object o) { if (!(o instanceof Seconds)) return false; Seconds __1 = (Seconds) o; return seconds == __1.seconds; } public int hashCode() { int h = -660217249; h = boostHashCombine(h, _hashCode(seconds)); return h; } public Object[] _fieldsToList() { return new Object[] { seconds }; } final public double get() { return seconds(); } final public double getDouble() { return seconds(); } public double seconds() { return seconds; } public String toString() { return formatDouble(seconds, 3) + " s"; } public int compareTo(Seconds s) { return cmp(seconds, s.seconds); } public Seconds div(double x) { return new Seconds(get() / x); } public Seconds minus(Seconds x) { return new Seconds(get() - x.get()); } } static public Class getClass(String name) { return _getClass(name); } static public Class getClass(Object o) { return _getClass(o); } static public Class getClass(Object realm, String name) { return _getClass(realm, name); } static public boolean classIsExportedTo(Class c, java.lang.Module destModule) { if (c == null || destModule == null) return false; java.lang.Module srcModule = c.getModule(); String packageName = c.getPackageName(); return srcModule.isExported(packageName, destModule); } static public boolean isAbstract(Class c) { return (c.getModifiers() & Modifier.ABSTRACT) != 0; } static public boolean isAbstract(Method m) { return (m.getModifiers() & Modifier.ABSTRACT) != 0; } static public boolean reflection_isForbiddenMethod(Method m) { return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives"); } static public void multiMapPut(Map> map, A a, B b) { List l = map.get(a); if (l == null) map.put(a, l = new ArrayList()); l.add(b); } static public void multiMapPut(MultiMap mm, A key, B value) { if (mm != null && key != null && value != null) mm.put(key, value); } static public Field makeAccessible(Field f) { try { f.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error", e, f); } return f; } static public Method makeAccessible(Method m) { try { m.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error", e, m); } return m; } static public Constructor makeAccessible(Constructor c) { try { c.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error", e, c); } return c; } static public Set allInterfacesImplementedBy(Class c) { if (c == null) return null; HashSet set = new HashSet(); allInterfacesImplementedBy_find(c, set); return set; } static public void allInterfacesImplementedBy_find(Class c, Set set) { if (c.isInterface() && !set.add(c)) return; do { for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set); } while ((c = c.getSuperclass()) != null); } static public Method findMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args); } static public 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 public boolean call_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != l(args)) { if (debug) print("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) { Object arg = args[i]; if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) { if (debug) print("Bad parameter " + i + ": " + arg + " vs " + types[i]); return false; } } return true; } static public Method findStaticMethod(Class c, String method, Object... args) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (!m.getName().equals(method)) continue; if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args)) continue; return m; } c = c.getSuperclass(); } return null; } static public boolean findStaticMethod_checkArgs(Method m, Object[] args) { Class[] types = m.getParameterTypes(); if (types.length != args.length) return false; for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) return false; return true; } static public Map putAll(Map a, Map b) { if (a != null && b != null) a.putAll(b); return a; } static public MultiMap putAll(MultiMap a, Map b) { if (a != null) a.putAll((Map) b); return a; } static public Map putAll(Map a, Object... b) { if (a != null) litmap_impl(a, b); return a; } static public void put(Map map, A a, B b) { if (map != null) map.put(a, b); } static public void put(List l, int i, A a) { if (l != null && i >= 0 && i < l(l)) l.set(i, a); } static public void remove(List l, int i) { if (l != null && i >= 0 && i < l(l)) l.remove(i); } static public void remove(Collection l, A a) { if (l != null) l.remove(a); } static public B remove(Map map, Object a) { return map == null ? null : map.remove(a); } static public void remove(BitSet bs, int i) { bs.clear(i); } static public A getAndClear(IVar v) { A a = v.get(); v.set(null); return a; } static public Set keySet(Map map) { return map == null ? new HashSet() : map.keySet(); } static public Set keySet(Object map) { return keys((Map) map); } static public Set keySet(MultiSet ms) { return ms.keySet(); } static public Set keySet(MultiMap mm) { return mm.keySet(); } static public Set keys(Map map) { return map == null ? new HashSet() : map.keySet(); } static public Set keys(Object map) { return keys((Map) map); } static public Set keys(MultiSet ms) { return ms.keySet(); } static public Set keys(MultiMap mm) { return mm.keySet(); } static public int keysSize(MultiMap mm) { return lKeys(mm); } static public A reverseGet(List l, int idx) { if (l == null || idx < 0) return null; int n = l(l); return idx < n ? l.get(n - 1 - idx) : null; } static public Map cloneMap(Map map) { if (map == null) return new HashMap(); synchronized (map) { return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map); } } static public List cloneMap(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : cloneList(l)) x.add(f.get(o)); return x; } static public Collection values(Map map) { return map == null ? emptyList() : map.values(); } static public Collection values(Object map) { return values((Map) map); } static public Collection values(MultiMap mm) { return mm == null ? emptyList() : concatLists(values(mm.data)); } static public > List allValues(Map map) { List out = new ArrayList(); for (var l : values(map)) addAll(out, l); return out; } static public String shortClassName_dropNumberPrefix(Object o) { return dropNumberPrefix(shortClassName(o)); } static public G22Utils g22utils(Concepts cc) { return (G22Utils) cc.miscMapGet(G22Utils.class); } static public CharInToken charIndexToCharInToken(List tok, int charIndex) { int i = 0, idx = 0, lTok; while (i < l(tok) && idx + (lTok = l(tok.get(i))) <= charIndex) { idx += lTok; i++; } return new CharInToken(tok, i, charIndex - idx); } static public boolean even(int i) { return (i & 1) == 0; } static public boolean even(long i) { return (i & 1) == 0; } static public boolean even(BigInteger n) { return even(n.intValue()); } static public List cloneKeys(Map map) { return cloneList(keys(map)); } static public String exceptionToStringShort(Throwable e) { lastException(e); e = getInnerException(e); String msg = hideCredentials(unnull(e.getMessage())); if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0) return baseClassName(e) + prependIfNempty(": ", msg); else return msg; } static public boolean eqOneOf(Object o, Object... l) { for (Object x : l) if (eq(o, x)) return true; return false; } static public boolean containsNewLine(String s) { return contains(s, '\n'); } static public List stringsSortedByLength(Iterable l) { return sortedByCalculatedField(l, new F1() { public Integer get(String s) { try { return l(s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "l(s)"; } }); } static public boolean scaffoldingEnabled(Object o) { return metaGet(o, "scaffolding") != null; } static public void printVars(Object... params) { printVars_str(params); } static public boolean isIdentifier(String s) { return isJavaIdentifier(s); } static public B floorValue(NavigableMap map, A key) { if (map == null) return null; var e = map.floorEntry(key); return e == null ? null : e.getValue(); } static public List concatMap(Object f, Iterable l) { return concatLists(map(f, l)); } static public List concatMap(Iterable l, Object f) { return concatMap(f, l); } static public List concatMap(Object f, Object[] l) { return concatLists(map(f, l)); } static public List concatMap(Object[] l, Object f) { return concatMap(f, l); } static public > List concatMap(Iterable l, IF1 f) { return concatMap(l, (Object) f); } static public > List concatMap(IF1 f, Iterable l) { return concatMap(l, f); } static public > List concatMap(IF1 f, A[] l) { return concatMap((Object) f, l); } static public List methodNames(Object o) { return allMethodNames(o); } static public int _hashCode(Object a) { return a == null ? 0 : a.hashCode(); } static public Method hashMap_findKey_method; static public A hashMap_findKey(HashMap map, Object key) { try { if (hashMap_findKey_method == null) hashMap_findKey_method = findMethodNamed(HashMap.class, "getNode"); Map.Entry entry = (Map.Entry) hashMap_findKey_method.invoke(map, hashMap_internalHash(key), key); return entry == null ? null : entry.getKey(); } catch (Exception __e) { throw rethrow(__e); } } static public Set createOrAddToSyncLinkedHashSet(Set set, A a) { if (set == null) set = syncLinkedHashSet(); set.add(a); return set; } static public void pcallFAll(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) pcallF(f, args); } static public void pcallFAll(Iterator it, Object... args) { while (it.hasNext()) pcallF(it.next(), args); } static public int boostHashCombine(int a, int b) { return a ^ (b + 0x9e3779b9 + (a << 6) + (a >>> 2)); } static public A last(List l) { return empty(l) ? null : l.get(l.size() - 1); } static public char last(String s) { return empty(s) ? '#' : s.charAt(l(s) - 1); } static public byte last(byte[] a) { return l(a) != 0 ? a[l(a) - 1] : 0; } static public int last(int[] a) { return l(a) != 0 ? a[l(a) - 1] : 0; } static public double last(double[] a) { return l(a) != 0 ? a[l(a) - 1] : 0; } static public A last(A[] a) { return l(a) != 0 ? a[l(a) - 1] : null; } static public A last(Iterator it) { A a = null; while (it.hasNext()) { ping(); a = it.next(); } return a; } static public A last(Collection l) { if (l == null) return null; if (l instanceof List) return (A) last((List) l); if (l instanceof SortedSet) return (A) last((SortedSet) l); Iterator it = iterator(l); A a = null; while (it.hasNext()) { ping(); a = it.next(); } return a; } static public A last(SortedSet l) { return l == null ? null : l.last(); } static public A last(CompactLinkedHashSet set) { return set == null ? null : set.last(); } static public void replaceLast(List l, A a) { replaceLastElement(l, a); } static public A[] toTypedArray(Class type, Iterable c) { return toArray(c, type); } static public String pnlToLines(String prefix, Iterable l) { return pnlToString(prefix, l); } static public String pnlToLines(Iterable l) { return pnlToString(l); } static public String pnlToLines(A[] l) { return pnlToString(l); } static public String pnlToLines(Map map) { return pnlToString(map); } static public String pnlToLines(MultiMap map) { return pnlToString(map); } static public String formatRecordVars(String recordName, Object... params) { return renderRecordVars(recordName, params); } static public boolean setText_opt = true; static public A setText(A c, Object text) { setText((JComponent) c, text); return c; } static public A setText(final A c, Object text) { final String s = strUnnull(text); { swing(() -> { c.getEditor().setItem(s); }); } return c; } static public void setText(JLabel c, Object text) { setText((JComponent) c, text); } static public JButton setText(JButton c, Object text) { setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text))); return c; } static public A setText(final A c, Object text) { if (c == null) return null; final String s = strUnnull(text); { swing(() -> { if (!setText_opt || neq(callOpt(c, "getText"), s)) call(c, "setText", s); }); } return c; } static public RuntimeException rethrowAndAppendToMessage(Throwable t, String msg) { String haveMsg = t.getMessage(); if (empty(msg) || endsWith(haveMsg, " " + msg)) throw rethrow(t); throw new RuntimeException(joinWithSpace(t.getMessage(), msg), t); } static public String squareBracketed(String s) { return "[" + s + "]"; } static public boolean is(String a, String b) { return false; } static public String assertIdentifier(String s) { return assertIsIdentifier(s); } static public String assertIdentifier(String msg, String s) { return assertIsIdentifier(msg, s); } static public boolean startsWithDigit(String s) { return nempty(s) && isDigit(s.charAt(0)); } static public int parseInt(String s) { return emptyString(s) ? 0 : Integer.parseInt(s); } static public int parseInt(char c) { return Integer.parseInt(str(c)); } static public float parseFloat(String s) { return Float.parseFloat(s); } static public boolean isQuoted(String s) { if (isNormalQuoted(s)) return true; return isMultilineQuoted(s); } static public String unquote(String s) { if (s == null) return null; if (startsWith(s, '[')) { int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; if (i < s.length() && s.charAt(i) == '[') { String m = s.substring(1, i); if (s.endsWith("]" + m + "]")) return s.substring(i + 1, s.length() - i - 1); } } if (s.length() > 1) { char c = s.charAt(0); if (c == '\"' || c == '\'') { int l = endsWith(s, c) ? s.length() - 1 : s.length(); StringBuilder sb = new StringBuilder(l - 1); for (int i = 1; i < l; i++) { char ch = s.charAt(i); if (ch == '\\') { char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1); if (nextChar >= '0' && nextChar <= '7') { String code = "" + nextChar; i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; } } sb.append((char) Integer.parseInt(code, 8)); continue; } switch(nextChar) { case '\"': ch = '\"'; break; case '\\': ch = '\\'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\'': ch = '\''; break; case 'u': if (i >= l - 5) { ch = 'u'; break; } int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16); sb.append(Character.toChars(code)); i += 5; continue; default: ch = nextChar; } i++; } sb.append(ch); } return sb.toString(); } } return s; } static public boolean hasMethodNamed(Object obj, String method) { if (obj == null) return false; if (obj instanceof Class) return hasMethodNamed((Class) obj, method); return hasMethodNamed(obj.getClass(), method); } static public boolean hasMethodNamed(Class c, String method) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) return true; c = c.getSuperclass(); } return false; } static public boolean isInterface(Class c) { return c != null && c.isInterface(); } static public A[] toArrayOrNull(Class type, Collection c) { if (empty(c)) return null; return toArray(type, c); } static public AutoCloseable tempMapPutAll(Map map, Map toAdd) { if (map != null && nempty(toAdd)) { List> toRestore = new ArrayList(); for (var __0 : _entrySet(toAdd)) { var key = __0.getKey(); var value = __0.getValue(); if (key != null && value != null) { B old = map.put(key, value); toRestore.add(pair(key, value)); } } return () -> { for (var p : toRestore) mapPutOrRemove(map, p.a, p.b); }; } return null; } static public Map mapWithSingleValue(Iterable l, B b) { HashMap map = new HashMap(); if (l != null) for (A a : l) map.put(a, b); return map; } static public TreeSet mapToTreeSet(Object f, Iterable l) { TreeSet x = new TreeSet(); if (l != null) for (Object o : l) x.add(callF(f, o)); return x; } static public TreeSet mapToTreeSet(IF1 f, Iterable l) { TreeSet x = new TreeSet(); if (l != null) for (var o : l) x.add(f.get(o)); return x; } static public TreeSet mapToTreeSet(Iterable l, IF1 f) { return mapToTreeSet(f, l); } static public boolean isAnonymousClassName(String s) { for (int i = 0; i < l(s); i++) if (s.charAt(i) == '$' && Character.isDigit(s.charAt(i + 1))) return true; return false; } static public String longestPrefixInTreeSet(String s, TreeSet set) { return longestPrefixInNavigableSet(s, set); } static public String dropPrefix(String prefix, String s) { return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s; } static public List itemPlus(A a, Collection l) { return itemPlusList(a, l); } static public List standardImports_fullyImportedPackages() { return endingWith_dropSuffix(standardImports(), ".*"); } static public String joinNemptiesWithColon(String... strings) { return joinNempties(": ", strings); } static public String joinNemptiesWithColon(Collection strings) { return joinNempties(": ", strings); } static public String commaCombine(Object... l) { return joinNemptiesWithComma(flattenCollectionsAndArrays(ll(l))); } static public int hashCodeFor(Object a) { return a == null ? 0 : a.hashCode(); } static public void assertSame(Object a, Object b) { assertSame("", a, b); } static public void assertSame(String msg, Object a, Object b) { if (a != b) throw fail(joinNemptiesWithColon(msg, a + " != " + b + " (" + identityHash(a) + "/" + identityHash(b) + ")")); } static public void assertSame(IF0 msg, Object a, Object b) { if (a != b) throw fail(joinNemptiesWithColon(msg.get(), a + " != " + b + " (" + identityHash(a) + "/" + identityHash(b) + ")")); } static public LineAndColumn tokenToLineAndColumn(ListAndIndex ptr) { return ptr == null ? null : tokenToLineAndColumn(ptr.list(), ptr.idx()); } static public LineAndColumn tokenToLineAndColumn(List tok, int tokenIndex) { int line = 1, col = 1; tokenIndex = min(tokenIndex, l(tok)); for (int i = 0; i < tokenIndex; i++) { String t = tok.get(i); int n = l(t); for (int j = 0; j < n; j++) if (t.charAt(j) == '\n') { ++line; col = 1; } else ++col; } return new LineAndColumn(line, col); } static public List uniquify(Collection l) { return uniquifyList(l); } static public void add(BitSet bs, int i) { bs.set(i); } static public boolean add(Collection c, A a) { return c != null && c.add(a); } static public void add(Container c, Component x) { addToContainer(c, x); } static public long add(AtomicLong l, long b) { return l.addAndGet(b); } static public String renderRecordVars(String recordName, Object... params) { List l = new ArrayList(); int i = 0; for (; i + 1 < l(params); i += 2) l.add(params[i] + "=" + params[i + 1]); return formatFunctionCall(recordName, l); } static public ImageSurface pixelatedImageSurface() { var is = imageSurface(); imageSurface_pixelated(is); return is; } static public ImageSurface pixelatedImageSurface(MakesBufferedImage img) { return pixelatedImageSurface(toBufferedImage(img)); } static public ImageSurface pixelatedImageSurface(BufferedImage img) { var is = pixelatedImageSurface(); is.setImage(img); return is; } static public File dbDir() { return programDir(dbProgramID()); } static public BufferedImage toBufferedImage(Object o) { return toBufferedImageOpt(o); } static public File getBytecodePathForClass(Object o) { return getBytecodePathForClass(_getClass(o)); } static public File getBytecodePathForClass(Class c) { try { return c == null ? null : new File(c.getProtectionDomain().getCodeSource().getLocation().toURI()); } catch (Exception __e) { throw rethrow(__e); } } static public File javaxDataDir_dir; static public File javaxDataDir() { return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data"); } static public File javaxDataDir(String... subs) { return newFile(javaxDataDir(), subs); } static public File newFile(File base, String... names) { for (String name : names) base = new File(base, name); return base; } static public File newFile(String name) { return name == null ? null : new File(name); } static public File newFile(String base, String... names) { return newFile(newFile(base), names); } static public boolean fileExists(String path) { return path != null && new File(path).exists(); } static public boolean fileExists(File f) { return f != null && f.exists(); } static public void createOrRemoveFile(File f, boolean create) { if (create) { if (!fileExists(f)) touchFile(f); } else if (fileExists(f)) removeFile(f); } static public List tlft(String s) { return toLinesFullTrim(s); } static public List tlft(File f) { return toLinesFullTrim(f); } static public String loadTextFile(String fileName) { return loadTextFile(fileName, null); } static public String loadTextFile(File f, String defaultContents) { return loadTextFile(f, defaultContents, "UTF-8"); } static public String loadTextFile(File f, String defaultContents, String encoding) { try { checkFileNotTooBigToRead(f); if (f == null || !f.exists()) return defaultContents; FileInputStream fileInputStream = new FileInputStream(f); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding); return loadTextFile(inputStreamReader); } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFile(File fileName) { return loadTextFile(fileName, null); } static public String loadTextFile(String fileName, String defaultContents) { return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents); } static public String loadTextFile(Reader reader) throws IOException { StringBuilder builder = new StringBuilder(); try { char[] buffer = new char[1024]; int n; while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n); } finally { reader.close(); } return str(builder); } static public boolean sameFile(File a, File b) { try { return a == null ? b == null : b != null && eq(a.getCanonicalPath(), b.getCanonicalPath()); } catch (Exception __e) { throw rethrow(__e); } } static public File dirOfFile(File f) { return f == null ? null : f.getParentFile(); } static public String fileName(File f) { return f == null ? null : f.getName(); } static public File saveTextFile(String fileName, String contents) throws IOException { File file = new File(fileName); mkdirsForFile(file); String tempFileName = fileName + "_temp"; File tempFile = new File(tempFileName); if (contents != null) { if (tempFile.exists()) try { String saveName = tempFileName + ".saved." + now(); copyFile(tempFile, new File(saveName)); } catch (Throwable e) { printStackTrace(e); } FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath()); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (contents != null) if (!tempFile.renameTo(file)) throw new IOException("Can't rename " + tempFile + " to " + file); vmBus_send("wroteFile", file); return file; } static public File saveTextFile(File fileName, String contents) { try { saveTextFile(fileName.getPath(), contents); return fileName; } catch (Exception __e) { throw rethrow(__e); } } static public String lines(Iterable lines) { return fromLines(lines); } static public String lines(Object[] lines) { return fromLines(asList(lines)); } static public List lines(String s) { return toLines(s); } static public String lines(Iterable l, IF1 f) { return mapToLines(l, f); } static public List llNonNulls(A... a) { List l = new ArrayList(); for (A x : a) if (x != null) l.add(x); return l; } static public A jMinHeight(A c, int h) { return jMinHeight(h, c); } static public A jMinHeight(int h, A c) { Dimension size = c.getMinimumSize(); c.setMinimumSize(new Dimension(size.width, max(h, size.height))); return jPreferHeight(h, c); } static public LinkedHashMap litorderedmap(Object... x) { LinkedHashMap map = new LinkedHashMap(); litmap_impl(map, x); return map; } static public String appendBracketed(Object o) { String b = strOrNull(o); return empty(b) ? "" : "" + " (" + b + ")"; } static public String appendBracketed(String a, String b) { return a + appendBracketed(b); } static public String or2_rev(String b, String a) { return or2(a, b); } static public String joinNemptiesWithSpacedPlus(Object... strings) { return joinNempties(" + ", strings); } static public String joinNemptiesWithSpacedPlus(Iterable strings) { return joinNempties(" + ", strings); } static public String n2(long l) { return formatWithThousands(l); } static public String n2(AtomicLong l) { return n2(l.get()); } static public String n2(Collection l) { return n2(l(l)); } static public String n2(Map map) { return n2(l(map)); } static public String n2(double l, String singular) { return empty(singular) ? str(l) : n2(l, singular, singular + "s"); } static public String n2(double l, String singular, String plural) { if (fraction(l) == 0) return n2((long) l, singular, plural); else return l + " " + plural; } static public String n2(long l, String singular, String plural) { return n_fancy2(l, singular, plural); } static public String n2(long l, String singular) { return empty(singular) ? n2(l) : n_fancy2(l, singular, singular + "s"); } static public String n2(Collection l, String singular) { return n2(l(l), singular); } static public String n2(Collection l, String singular, String plural) { return n_fancy2(l, singular, plural); } static public String n2(Map m, String singular, String plural) { return n_fancy2(m, singular, plural); } static public String n2(Map m, String singular) { return n2(l(m), singular); } static public String n2(long[] a, String singular) { return n2(l(a), singular); } static public String n2(Object[] a, String singular) { return n2(l(a), singular); } static public String n2(Object[] a, String singular, String plural) { return n_fancy2(a, singular, plural); } static public String n2(MultiSet ms, String singular, String plural) { return n_fancy2(ms, singular, plural); } static public int intMax(Collection c, String field) { int max = Integer.MIN_VALUE; for (Object o : c) max = Math.max(max, toInt(getOpt(o, field))); return max; } static public int intMax(Iterable l) { int max = Integer.MIN_VALUE; for (int i : unnullForIteration(l)) max = Math.max(max, i); return max; } static public int intMax(int... l) { int max = Integer.MIN_VALUE; if (l != null) for (int i : l) max = Math.max(max, i); return max; } static public List mapLL(Object f, Object... data) { return map(f, ll(data)); } static public List mapLL(IF1 f, A... data) { return map(f, ll(data)); } static public int linesOfCode_javaTok(String text) { List tok = javaTok(text); int lines = 0; boolean codeInCurrentLine = false; for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i)) { int lTok = l(t); for (int j = 0; j < lTok; j++) { char c = t.charAt(j); if (c == '\n') codeInCurrentLine = false; else if (!isSpaceEtc(c) && !codeInCurrentLine) { codeInCurrentLine = true; ++lines; } } } else { if (codeInCurrentLine && containsNewLine(t)) codeInCurrentLine = false; } } return lines; } static public File appendToFileName(File f, String suffix) { return fileAppendToName(f, suffix); } static public File appendToFileName(String suffix, File f) { return appendToFileName(f, suffix); } static public List map(Iterable l, Object f) { return map(f, l); } static public List map(Object f, Iterable l) { List x = emptyList(l); if (l != null) for (Object o : l) { ping(); x.add(callF(f, o)); } return x; } static public List map(Iterable l, F1 f) { return map(f, l); } static public List map(F1 f, Iterable l) { List x = emptyList(l); if (l != null) for (A o : l) { ping(); x.add(callF(f, o)); } return x; } static public List map(IF1 f, Iterable l) { return map(l, f); } static public List map(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : l) { ping(); x.add(f.get(o)); } return x; } static public List map(IF1 f, A[] l) { return map(l, f); } static public List map(A[] l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : l) { ping(); x.add(f.get(o)); } return x; } static public List map(Object f, Object[] l) { return map(f, asList(l)); } static public List map(Object[] l, Object f) { return map(f, l); } static public List map(Object f, Map map) { return map(map, f); } static public List map(Map map, Object f) { List x = new ArrayList(); if (map != null) for (Object _e : map.entrySet()) { ping(); Map.Entry e = (Map.Entry) _e; x.add(callF(f, e.getKey(), e.getValue())); } return x; } static public List map(Map map, IF2 f) { return map(map, (Object) f); } static public List map(IF1 f, A data1, A... moreData) { List x = emptyList(l(moreData) + 1); x.add(f.get(data1)); if (moreData != null) for (A o : moreData) { ping(); x.add(f.get(o)); } return x; } static public String nLabels(long n) { return n2(n, "label"); } static public String nLabels(Collection l) { return nLabels(l(l)); } static public String nLabels(Map map) { return nLabels(l(map)); } static public A uniqCI(Class c, Object... params) { return uniqueConcept(db_mainConcepts(), c, params); } static public A uniqCI(Concepts cc, Class c, Object... params) { AutoCloseable __1 = tempDBLock(cc); try { params = expandParams(c, params); A x = findConceptWhereCI(cc, c, params); if (x == null) { x = unlisted(c); csetAll(x, params); cc.register(x); } return x; } finally { _close(__1); } } static public File conceptsDir() { return conceptsDir(db_mainConcepts()); } static public File conceptsDir(Concepts cc) { return cc.conceptsDir(); } static public File conceptsDir(String subName) { return conceptsDir(db_mainConcepts(), subName); } static public File conceptsDir(Concepts cc, String subName) { return newFile(conceptsDir(cc), subName); } static public boolean containsFile(File dir, String name) { return new File(dir, name).exists(); } static public boolean containsFile(Iterable l, File f) { return any(l, file -> sameFile(f, file)); } static public File conceptsFile(String progID) { return getProgramFile(progID, conceptsFileName()); } static public File conceptsFile() { return conceptsFile(dbProgramID()); } static public File conceptsFile(Concepts concepts) { return concepts.conceptsFile(); } static public File conceptsFileIn(File dir) { return newFile(dir, conceptsFileName()); } static public List listDirsContainingFileNamed(File dir, String fileName) { return filter(listDirs(dir), d -> isFile(newFile(d, fileName))); } static public long incAtomicLong(AtomicLong l) { return l.incrementAndGet(); } static public B mapGet(Map map, A a) { return map == null || a == null ? null : map.get(a); } static public B mapGet(A a, Map map) { return map == null || a == null ? null : map.get(a); } static public boolean preciseNuObject_debug = false; static public A preciseNuObject(Class c, Object... args) { try { Constructor[] methods = c.getDeclaredConstructors(); Constructor best = null; int bestScore = Integer.MAX_VALUE; boolean widening = false; if (preciseNuObject_debug) printVars("preciseNuObject", "c", c, "methods", l(methods)); for (var m : methods) { int score = methodApplicabilityScore_withPrimitiveWidening(m, args); if (score == 0) return (A) invokeConstructor(m, args); if (preciseNuObject_debug) print("Method score: " + m + " " + score); if (abs(score) < bestScore) { best = m; bestScore = abs(score); widening = score < 0; } } if (best != null) if (widening) return (A) invokeConstructorWithWidening(best, args); else return (A) invokeConstructor(best, args); methodSearch: for (var m : methods) { { if (!(m.isVarArgs())) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return (A) invokeConstructor(m, newArgs); } throw fail("No matching constructor found: " + formatFunctionCall(c, map(__61 -> _getClass(__61), args))); } catch (Exception __e) { throw rethrow(__e); } } static public Object[] mapToArrayOrNull(A[] l, IF1 f) { if (l == null) return null; int n = l.length; if (n == 0) return null; Object[] array = new Object[n]; for (int i = 0; i < n; i++) array[i] = f.get(l[i]); return array; } static public Object[] mapToArrayOrNull(IF1 f, A[] l) { return mapToArrayOrNull(l, f); } static public Object[] mapToArrayOrNull(IF1 f, Collection l) { int n = l(l); if (n == 0) return null; Object[] array = new Object[n]; if (n != 0) { Iterator it = iterator(l); for (int i = 0; i < n; i++) array[i] = callF(f, it.next()); } return array; } static public Object[] mapToArrayOrNull(Collection l, IF1 f) { return mapToArrayOrNull(l, f); } static public String formatFunctionCall(String fname, Object... args) { return formatFunctionCall((Object) fname, args); } static public String formatFunctionCall(Object fname, Object... args) { return fname + "(" + joinWithComma(allToString(args)) + ")"; } static public String formatFunctionCall(String fname, Iterable args) { return formatFunctionCall((Object) fname, args); } static public String formatFunctionCall(Object fname, Iterable args) { return formatFunctionCall(fname, toObjectArray(args)); } static public String strOrClassName(Object o) { if (o instanceof Class) return className((Class) o); return str(o); } static public boolean canCallWithVarargs(Object o, String method, Object... args) { if (o == null) return false; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); if (cache.findStaticMethod(method, args) != null) return true; List methods = cache.cache.get(method); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs() && isStaticMethod(m))) continue; } if (massageArgsForVarArgsCall(m, args) != null) return true; } } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); if (cache.findMethod(method, args) != null) return true; List methods = cache.cache.get(method); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } if (massageArgsForVarArgsCall(m, args) != null) return true; } } return false; } static public A _get(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } static public Object _get(Object o, String field) { return get(o, field); } static public Object _get(String field, Object o) { return get(o, field); } static public A _get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } static public boolean newPreciseCall_debug = false; static public Object newPreciseCall(Object o, String method, Object... args) { try { if (o == null) return null; boolean staticCall = o instanceof Class; Class c = staticCall ? (Class) o : o.getClass(); Object target = staticCall ? null : o; _MethodCache cache = callOpt_getCache(c); List methods = cache.cache.get(method); Method best = null; int bestScore = Integer.MAX_VALUE; boolean widening = false; if (newPreciseCall_debug) printVars("newPreciseCall", "method", method, "staticCall", staticCall, "c", c, "methods", l(methods)); if (methods != null) for (Method m : methods) { if (staticCall && !isStaticMethod(m)) continue; int score = methodApplicabilityScore_withPrimitiveWidening(m, args); if (score == 0) return invokeMethod(m, target, args); if (newPreciseCall_debug) print("Method score: " + m + " " + score); if (abs(score) < bestScore) { best = m; bestScore = abs(score); widening = score < 0; } } if (best != null) if (widening) return invokeMethodWithWidening(best, target, args); else return invokeMethod(best, target, args); return callWithVarargs(o, method, args); } catch (Exception __e) { throw rethrow(__e); } } static public Method findMethod_precise_onTypes(Object o, String method, Class... argTypes) { try { if (o instanceof Class) { _MethodCache cache = callOpt_getCache((Class) o); List methods = cache.cache.get(method); Lowest best = new Lowest(); if (methods != null) for (Method m : methods) { { if (!(isStaticMethod(m))) continue; } int score = methodApplicabilityScore_onTypes(m, argTypes); if (score < Integer.MAX_VALUE) best.put(m, score); } return best.get(); } if (o == null) return null; _MethodCache cache = callOpt_getCache(o.getClass()); List methods = cache.cache.get(method); Lowest best = new Lowest(); if (methods != null) for (Method m : methods) { int score = methodApplicabilityScore_onTypes(m, argTypes); if (score < Integer.MAX_VALUE) best.put(m, score); } return best.get(); } catch (Exception __e) { throw rethrow(__e); } } static public Method findSingleInterfaceMethod(Class intrface) { return singletonOpt(findNonDefaultInterfaceMethods(intrface)); } static public A proxyFromInvocationHandler(Class intrface, InvocationHandler handler) { return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, handler); } static public Object[] concatMethodArgs(Object[] args1, Object[] args2) { int n1, n2; if (args1 == null || (n1 = args1.length) == 0) return args2; if (args2 == null || (n2 = args2.length) == 0) return args1; Object[] args = new Object[n1 + n2]; for (int i = 0; i < n1; i++) args[i] = args1[i]; for (int i = 0; i < n2; i++) args[n1 + i] = args2[i]; return args; } static public int javaTok_n, javaTok_elements; static public boolean javaTok_opt = false; static public List javaTok(String s) { ++javaTok_n; ArrayList tok = new ArrayList(); int l = s == null ? 0 : s.length(); int i = 0; while (i < l) { int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !regionMatches(s, j, "*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(javaTok_substringN(s, i, j)); i = j; if (i >= l) break; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) { j += 2; while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j; } else if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { int c2 = s.charAt(j); if (c2 == opener || c2 == '\n' && opener == '\'') { ++j; break; } else if (c2 == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else if (c == '[' && d == '[') { do ++j; while (j < l && !regionMatches(s, j, "]]")); j = Math.min(j + 2, l); } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') { do ++j; while (j + 2 < l && !regionMatches(s, j, "]=]")); j = Math.min(j + 3, l); } else ++j; tok.add(javaTok_substringC(s, i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } static public List javaTok(List tok) { return javaTokWithExisting(join(tok), tok); } static public boolean eqOrEqic(boolean caseInsensitive, String a, String b) { return caseInsensitive ? eqic(a, b) : eq(a, b); } static public boolean any(Object pred, Iterable l) { if (l != null) for (A a : l) if (isTrue(callF(pred, a))) return true; return false; } static public boolean any(IF1 pred, Iterable l) { if (l != null) for (A a : l) if (pred.get(a)) return true; return false; } static public boolean any(Iterable l, IF1 pred) { return any(pred, l); } static public boolean any(A[] l, IF1 pred) { if (l != null) for (A a : l) if (pred.get(a)) return true; return false; } static public boolean any(Iterable l) { if (l != null) for (Boolean a : l) if (isTrue(a)) return true; return false; } static public boolean containsLineBreak(String s) { return containsNewLine(s); } static public boolean warn_on = true; static public ThreadLocal> warn_warnings = new ThreadLocal(); static public void warn(String s) { if (warn_on) print("Warning: " + s); } static public void warn(String s, List warnings) { warn(s); if (warnings != null) warnings.add(s); addToCollection(warn_warnings.get(), s); } static public String joinSubList(List l, int i, int j) { return join(subList(l, i, j)); } static public String joinSubList(List l, int i) { return join(subList(l, i)); } static public String joinSubList(List l, IntRange r) { return r == null ? null : joinSubList(l, r.start, r.end); } static public A set(A o, String field, Object value) { if (o == null) return null; if (o instanceof Class) set((Class) o, field, value); else try { Field f = set_findField(o.getClass(), field); makeAccessible(f); smartSet(f, o, value); } catch (Exception e) { throw new RuntimeException(e); } return o; } static public void set(Class c, String field, Object value) { if (c == null) return; try { Field f = set_findStaticField(c, field); makeAccessible(f); smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } static public 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 public 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 public void set(BitSet bs, int idx) { { if (bs != null) bs.set(idx); } } static public MultiMap descTreeMultiMap() { return new MultiMap(descTreeMap()); } static public A optPar(ThreadLocal tl, A defaultValue) { A a = tl.get(); if (a != null) { tl.set(null); return a; } return defaultValue; } static public A optPar(ThreadLocal tl) { return optPar(tl, null); } static public Object optPar(Object[] params, String name) { return optParam(params, name); } static public Object optPar(String name, Object[] params) { return optParam(params, name); } static public Object optPar(String name, Map params) { return optParam(name, params); } static public A optPar(Object[] params, String name, A defaultValue) { return optParam(params, name, defaultValue); } static public A optPar(String name, Object[] params, A defaultValue) { return optParam(params, name, defaultValue); } static public List scoredSearch_prepare(String query) { return map(__62 -> replacePlusWithSpace(__62), splitAtSpace(query)); } static public float score(Scored s) { return s == null ? 0 : s.score(); } static public double scoredSearch_scoreWeighted2(Collection> l, List words) { double score = 0; if (l != null) for (Pair __0 : l) { String s = pairA(__0); double weight = pairB(__0); score += scoredSearch_score(s, words) * weight; } return score; } static public int scoredSearch_score(Iterable l, List words) { int score = 0; if (l != null) for (String s : l) score += scoredSearch_score(s, words); return score; } static public int scoredSearch_score(String s, List words) { int score = 0; if (nempty(s)) for (String word : unnullForIteration(words)) score += scoredSearch_score_single(s, word); return score; } static public int scoredSearch_score(String s, String query) { return scoredSearch_score(s, scoredSearch_prepare(query)); } static public List pairsB(Collection> l) { return secondOfPairs(l); } static public IterableIterator> multiMapPairIterator(MultiMap mm) { return nestedIterator(iterator(keys(mm.data)), key -> (IterableIterator>) mapI(iterator(mm.data.get(key)), val -> pair(key, val))); } static public IterableIterator> multiMapPairIterator_transformValueList(MultiMap mm, IF1, List> f) { return nestedIterator(iterator(keys(mm.data)), key -> (IterableIterator>) mapI(iterator(f.get(mm.data.get(key))), val -> pair(key, val))); } static public B firstValue(Map map) { return first(values(map)); } static public B firstValue(MultiMap map) { return map == null ? null : first(firstValue(map.data)); } static public Set setWithNotify(final Runnable onChange) { return setWithNotify(new HashSet(), onChange); } static public Set setWithNotify(Set set, final Runnable onChange) { return new NotifyingSet(set) { public void change() { onChange.run(); } }; } static public Set syncLinkedHashSet() { return synchroLinkedHashSet(); } static public MenuItem menuItem(String text, final Object r) { MenuItem mi = new MenuItem(text); mi.addActionListener(actionListener(r)); return mi; } static public A bindToolTipToTransformedLiveValue(IF1 f, LiveValue lv, A c) { bindLiveValueListenerToComponent(c, lv, new Runnable() { public void run() { try { setToolTipText(c, strOrNull(f.get(lv.get()))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setToolTipText(c, strOrNull(f.get(lv!)))"; } }); return c; } static public JLabel simpleTransformedLiveValueLabel(IF1 f, LiveValue lv) { return bindJLabelToTransformedLiveValue(f, swing(() -> new JLabel()), lv); } static public MouseAdapter onMouseDown_anyButton(Component c, Runnable r) { return onMouseDown(c, runnableToIVF1(r)); } static public MouseAdapter onMouseDown_anyButton(Component c, IVF1 f) { return c == null || f == null ? null : swing(() -> { MouseAdapter ma = new MouseAdapter() { public void mousePressed(MouseEvent e) { f.get(e); } }; c.addMouseListener(ma); return ma; }); } static public int componentCount(Container c) { return numberOfChildren(c); } static public void addMenuItem(JPopupMenu menu, String text, Object action) { menu.add(jmenuItem(text, action)); } static public void addMenuItem(JPopupMenu menu, JMenuItem menuItem) { if (menu != null && menuItem != null) menu.add(menuItem); } static public void addMenuItem(JMenu menu, String text, Object action) { menu.add(jmenuItem(text, action)); } static public void addMenuItem(Menu menu, String text, Object action) { menu.add(menuItem(text, action)); } static public void addMenuItem(JMenu menu, JMenuItem menuItem) { menu.add(menuItem); } static public void addMenuItem(JMenuBar menuBar, String text, Runnable action) { addMenuItem(menuBar, jmenuItem(text, action)); } static public void addMenuItem(JMenuBar menuBar, JMenuItem menuItem) { addDirectMenuItem(menuBar, menuItem); } static public TitledBorder jRaisedSectionBorder(String title) { return swing(() -> { Border border = BorderFactory.createBevelBorder(BevelBorder.RAISED); return BorderFactory.createTitledBorder(border, title); }); } static public A setBorder(Border border, A c) { if (c != null) { swing(() -> { c.setBorder(border); }); } return c; } static public A setBorder(A c, Border border) { return setBorder(border, c); } static public void showPopupMenu(JPopupMenu menu, MouseEvent e) { if (menu != null && e != null) menu.show(e.getComponent(), e.getX(), e.getY()); } static public Dimension dimensionPlus(int w, int h, Dimension d) { return d == null ? null : new Dimension(d.width + w, d.height + h); } static public Dimension maxDimension(Dimension a, Dimension b) { return a == null ? b : b == null ? a : new Dimension(max(a.width, b.width), max(a.height, b.height)); } static public AutoCloseable tempAdd(Collection l, A a) { if (l == null || l.contains(a)) return null; l.add(a); return new AutoCloseable() { public String toString() { return "l.remove(a);"; } public void close() throws Exception { l.remove(a); } }; } static public String or2(String a, String b) { return nempty(a) ? a : b; } static public String or2(String a, String b, String c) { return or2(or2(a, b), c); } static public File byteCodePathForClass(Class c) { if (c == null) return null; ClassLoader cl = getClassLoader(c); Collection files = (Collection) (getOpt(cl, "files")); if (files != null) { String name = c.getName().replace('.', '/') + ".class"; for (File location : files) if (dirOrZipContainsPath(location, name)) return location; throw fail(name + " not found in: " + files); } return null; } static public File byteCodePathForClass(Object o) { return byteCodePathForClass(_getClass(o)); } static public List itemPlusList(A a, Collection l) { return concatLists(ll(a), l); } static public List endingWith_dropSuffix(Collection l, String suffix) { List out = new ArrayList(); for (String s : unnullForIteration(l)) if (endsWith(s, suffix)) out.add(dropLast(l(suffix), s)); return out; } static public List endingWith_dropSuffix(String suffix, Collection l) { return endingWith_dropSuffix(l, suffix); } static public List standardImports_cache; static public List standardImports() { if (standardImports_cache == null) standardImports_cache = standardImports_load(); return standardImports_cache; } static public List standardImports_load() { return ll("java.util.*", "java.util.zip.*", "java.util.List", "java.util.regex.*", "java.util.concurrent.*", "java.util.concurrent.atomic.*", "java.util.concurrent.locks.*", "java.util.function.*", "javax.swing.*", "javax.swing.event.*", "javax.swing.text.*", "javax.swing.table.*", "java.io.*", "java.net.*", "java.lang.reflect.*", "java.lang.ref.*", "java.lang.management.*", "java.security.*", "java.security.spec.*", "java.awt.*", "java.awt.event.*", "java.awt.image.*", "java.awt.geom.*", "javax.imageio.*", "java.math.*"); } static public List classNamesInJarOrDir(File dir) { return classNamesInJarOrDir(dir, ""); } static public List classNamesInJarOrDir(File dir, String prefixInJar) { List classes = new ArrayList(); if (dir == null) { } else if (dir.isDirectory()) { for (File f : listFiles(dir)) { String s = f.getName(); if (s.endsWith(".class")) classes.add(dropSuffix(".class", s)); } } else if (dir.isFile()) { try { JarFile jarFile = new JarFile(dir); try { Enumeration e = jarFile.entries(); while (e.hasMoreElements()) { JarEntry je = e.nextElement(); if (je.isDirectory() || je.getName().startsWith("META-INF/") || !je.getName().endsWith(".class")) continue; String className = dropSuffix(".class", je.getName()); className = dropPrefixOrNull(prefixInJar, className); if (className == null) continue; if (className.contains("-")) continue; className = className.replace('/', '.'); classes.add(className); } } finally { jarFile.close(); } } catch (Throwable __e) { printStackTrace(__e); } } return classes; } static public List classNamesInLoadedJigsawModules() { return concatMap(loadedJigsawModuleNames(), moduleName -> classNamesInJigsawModule(moduleName)); } static public boolean containsKey(Map map, A key) { return map != null && map.containsKey(key); } static public Map putOrCreate(Map map, A key, B value) { if (map == null) map = new HashMap(); map.put(key, value); return map; } static public A pnl(A l) { return pnl("", l); } static public A pnl(String prefix, A l) { printNumberedLines(prefix, l); return l; } static public A[] pnl(A[] l) { return pnl("", l); } static public A[] pnl(String prefix, A[] l) { printNumberedLines(prefix, l); return l; } static public A pnl(A map) { printNumberedLines(map); return map; } static public A pnl(String prefix, A map) { printNumberedLines(prefix, map); return map; } static public String pnl(String s) { printNumberedLines(lines(s)); return s; } static public MultiSet pnl(MultiSet ms) { pnl(ms == null ? null : ms.asMap()); return ms; } static public MultiMap pnl(MultiMap mm) { pnl(mm == null ? null : mm.asMap()); return mm; } static public Object metaGet(IMeta o, Object key) { return metaMapGet(o, key); } static public Object metaGet(Object o, Object key) { return metaMapGet(o, key); } static public Object metaGet(String key, IMeta o) { return metaMapGet(o, key); } static public Object metaGet(String key, Object o) { return metaMapGet(o, key); } static public Object metaMapGet(IMeta o, Object key) { return o == null ? null : o.metaGet(key); } static public Object metaMapGet(Object o, Object key) { return metaMapGet(toIMeta(o), key); } static public void metaPut(IMeta o, Object key, Object value) { metaMapPut(o, key, value); } static public void metaPut(Object o, Object key, Object value) { metaMapPut(o, key, value); } static public void metaMapPut(IMeta o, Object key, Object value) { { if (o != null) o.metaPut(key, value); } } static public void metaMapPut(Object o, Object key, Object value) { var meta = initIMeta(o); { if (meta != null) meta.metaPut(key, value); } } static public Map convertObjectMetaToMap(IMeta o) { return convertObjectMetaToMap(o, () -> makeObjectMetaMap()); } static public Map convertObjectMetaToMap(IMeta o, IF0 createEmptyMap) { if (o == null) return null; Object meta = o._getMeta(); if (meta instanceof Map) return ((Map) meta); var mutex = tempMetaMutex(o); try { var actualMutex = mutex.get(); synchronized (actualMutex) { meta = o._getMeta(); if (meta instanceof Map) return ((Map) meta); Map map = createEmptyMap.get(); if (meta != null) map.put("previousMeta", meta); o._setMeta(map); return map; } } finally { _close(mutex); } } static public void syncMapPutOrRemove(Map map, A key, B value) { syncMapPut2(map, key, value); } static public String nlLogic_text(Exp e) { return e == null ? null : e.text(); } static public String nlLogic_text(IfThen r) { return r == null ? null : r.text(); } static public A setEnabled(A c, boolean enable) { if (c != null) { swing(() -> { c.setEnabled(enable); }); } return c; } static public A setEnabled(boolean enable, A c) { return setEnabled(c, enable); } static public void setEnabled(boolean enable, JComponent... l) { for (var c : unnullForIteration(l)) setEnabled(c, enable); } static public void change() { callOpt(getOptMC("mainConcepts"), "allChanged"); } static public int syncL(Collection l) { if (l == null) return 0; synchronized (collectionMutex(l)) { return l.size(); } } static public int syncL(Map map) { if (map == null) return 0; synchronized (collectionMutex(map)) { return map.size(); } } static public List syncL() { return syncList(); } static public ReliableSingleThread rst(Runnable r) { return new ReliableSingleThread(r); } static public Class _run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } static public Class run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } static public Collection conceptsWhere(Class c, Object... params) { return findConceptsWhere(c, params); } static public Collection conceptsWhere(String c, Object... params) { return findConceptsWhere(c, params); } static public Collection conceptsWhere(Concepts concepts, Class c, Object... params) { return findConceptsWhere(concepts, c, params); } static public List sortByCalculatedFieldAlphaNumIC(Iterable c, IF1 f) { List l = cloneList(c); sort(l, (a, b) -> cmpAlphanumIC(f.get(a), f.get(b))); return l; } static public AutoCloseable tempAddGlobalCtrlKeyListener(IVF1 onStatusChanged) { AWTEventListener l = new AWTEventListener() { public Boolean status; public void eventDispatched(AWTEvent evt) { if (evt instanceof InputEvent) { Boolean b = ((InputEvent) evt).isControlDown(); if (!eq(b, status)) pcallF_typed(onStatusChanged, status = b); } } }; Toolkit.getDefaultToolkit().addAWTEventListener(l, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK); return () -> Toolkit.getDefaultToolkit().removeAWTEventListener(l); } static public void sleepSeconds(double s) { if (s > 0) sleep(round(s * 1000)); } static public int done_minPrint = 10; static public long done(long startTime, String desc) { long time = now() - startTime; if (time >= done_minPrint) print(desc + " [" + time + " ms]"); return time; } static public long done(String desc, long startTime) { return done(startTime, desc); } static public long done(long startTime) { return done(startTime, ""); } static public void close(AutoCloseable c) { _close(c); } static public JWindow infoBox(Object text) { return infoMessage(strOrNull(text)); } static public JWindow infoBox(String text) { return infoMessage(text); } static public JWindow infoBox(String text, double seconds) { return infoMessage(text, seconds); } static public JWindow infoBox(Throwable e) { return infoMessage(e); } static public String formatDouble1(double d) { return formatDouble(d, 1); } static public boolean cleanUp_interruptThreads = false; static public void cleanUp(Object c) { if (c == null) return; if (c instanceof AutoCloseable) { close_pcall((AutoCloseable) c); return; } if (c instanceof java.util.Timer) { ((java.util.Timer) c).cancel(); return; } if (c instanceof Collection) { cleanUp((Collection) c); return; } if (c instanceof Map) { for (Object o : keys((Map) c)) cleanUp(o); for (Object o : values((Map) c)) cleanUp(o); ((Map) c).clear(); return; } try { preCleanUp(c); setOpt_raw(c, "ping_pauseAll", false); innerCleanUp(c); List androids = (List) getOpt(c, "record_list"); for (Object android : unnull(androids)) pcallOpt(android, "dispose"); List classes = (List) (getOpt(c, "hotwire_classes")); if (classes != null) for (WeakReference cc : classes) { try { cleanUp(cc.get()); } catch (Throwable __e) { printStackTrace(__e); } } if (cleanUp_interruptThreads) { List threads = registeredThreads(c); if (nempty(threads)) { print("cleanUp: Interrupting " + n2(threads, "thread") + ": " + joinWithComma(allToString(threads))); interruptThreads(threads); } } } catch (Throwable __e) { printStackTrace(__e); } setOpt_raw(c, "cleaningUp_flag", false); if (c instanceof Class && ((Class) c).getName().equals("main")) retireClassLoader(((Class) c).getClassLoader()); } static public void cleanUp(Collection l) { if (l == null) return; for (Object c : l) cleanUp(c); l.clear(); } static public A waitForVarPredicate(Var v, IF0 pred) { try { synchronized (v) { while (!pred.get()) v.wait(); return v.get(); } } catch (Exception __e) { throw rethrow(__e); } } static public void cMigrateField(Concept c, String oldField, String newField) { if (c == null) return; Object oldValue = cget(c, oldField); Object newValue = cget(c, newField); if (oldValue != null && newValue == null) { try { String name = shortDynName(c); print("Migrating " + name + "." + oldField + " -> " + name + "." + newField + " [id " + c.id + "]"); cset(c, newField, oldValue); cset(c, oldField, null); } catch (Throwable __e) { printStackTrace(__e); } } } static public String shortClassName(Object o) { if (o == null) return null; Class c = o instanceof Class ? (Class) o : o.getClass(); String name = c.getName(); return shortenClassName(name); } static public void printVars_shorten(Object... params) { print(renderVars_stringifier(o -> str_shorten(o), params)); } static public String shortDynName(Object o) { return shortDynamicClassName(o); } static public String nLines(long n) { return n2(n, "line"); } static public String nLines(Collection l) { return nLines(l(l)); } static public String nLines(String s) { return nLines(countLines(s)); } static public String nChars(long n) { return n2(n, "char"); } static public String nChars(String s) { return nChars(l(s)); } static public String indentx(String s) { return indentx(indent_default, s); } static public String indentx(int n, String s) { return dropSuffix(repeat(' ', n), indent(n, s)); } static public String indentx(String indent, String s) { return dropSuffix(indent, indent(indent, s)); } static public void appendToTextFile(File file, String s) { appendToFile(file, s); } static public void appendToTextFile(String file, String s) { appendToTextFile(programFile(file), s); } static public String dateWithMSUTC() { return dateWithMSUTC(now()); } static public String dateWithMSUTC(long time) { var format = simpleDateFormat_UTC("yyyy/MM/dd"); return format.format(time) + " " + formatUTCWithMS_24(time); } static public String firstToUpper(String s) { if (empty(s)) return s; return Character.toUpperCase(s.charAt(0)) + s.substring(1); } static public A getVar(IF0 v) { return v == null ? null : v.get(); } static public A getVar(Optional v) { return v == null ? null : v.orElse(null); } static public SimpleLiveValue stringLiveValue() { return new SimpleLiveValue(String.class); } static public SimpleLiveValue stringLiveValue(String value) { return new SimpleLiveValue(String.class, value); } static public void setSectionTitle(JComponent c, String title) { swing(() -> { var _c_1 = c; while (_c_1 != null) { var b = _c_1.getBorder(); if (b != null) { if (b instanceof javax.swing.border.TitledBorder) { ((javax.swing.border.TitledBorder) b).setTitle(title); revalidate(_c_1); return; } } if (_c_1.getParent() instanceof JComponent) _c_1 = (JComponent) _c_1.getParent(); else break; } }); } static public JPanel jline(final Component... components) { return swing(new F0() { public JPanel get() { try { return new LeftAlignedLine(components); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return new LeftAlignedLine(components);"; } }); } static public JPanel jline(List components) { return jline(asArray(Component.class, components)); } static public SingleComponentPanel singleComponentPanel() { return singleComponentPanel(null); } static public SingleComponentPanel singleComponentPanel(final Component c) { return swing(new F0() { public SingleComponentPanel get() { try { return new SingleComponentPanel(c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return new SingleComponentPanel(c);"; } }); } static public String getText(final AbstractButton c) { return c == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getText();"; } }); } static public String getText(final JTextComponent c) { return c == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getText();"; } }); } static public String getText(final JLabel l) { return l == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return l.getText(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return l.getText();"; } }); } static public String getText(final JComboBox cb) { if (cb == null) return null; if (isEditableComboBox(cb)) return unnull((String) cb.getEditor().getItem()); else return str(cb.getSelectedItem()); } static public A enableScaffolding(A o) { if (o instanceof IMeta) ((IMeta) o).metaPut("scaffolding", true); return o; } static public int getCaretPosition(final JTextComponent c) { return c == null ? 0 : swing(new F0() { public Integer get() { try { return c.getCaretPosition(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getCaretPosition();"; } }); } static public void addMenuItems(JMenu m, Object... x) { fillJMenu(m, x); } static public void addMenuItems(JPopupMenu m, Object... x) { fillJPopupMenu(m, x); } static public 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 public JTextArea showTextWordWrapped(final String title, final String text) { return showWrappedText(title, text); } static public JTextArea showTextWordWrapped(Object text) { return showWrappedText(text); } static public JPanel centerAndEastWithMargin(Component c, Component e) { return centerAndEastWithMarginInbetween(c, e); } static public JScrollPane jBorderlessHigherScrollPane(JComponent c) { return borderlessScrollPane(jHigherScrollPane(c)); } static public JPanel jfullcenter(Component c) { return jFullCenter(c); } static public A markVisualizer(Object visualizer, A a) { return setMetaSrc(a, visualizer); } static public A bindTextComponentToLiveValue_bothWays(A tc, SimpleLiveValue lv) { bindLiveValueListenerToComponent(tc, lv, new Runnable() { public void run() { try { setTextKeepCaret(tc, lv.get()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setTextKeepCaret(tc, lv!)"; } }); onChange(tc, new Runnable() { public void run() { try { lv.set(getText(tc)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lv.set(getText(tc))"; } }); return tc; } static public A onCtrlEnter(A c, Runnable action) { return onCtrlEnter(c, (Object) action); } static public A onCtrlEnter(A c, Object action) { addKeyListener(c, ctrlEnterKeyListener(action)); return c; } static public SingleThread awtCalcEvery(JFrame f, int delay, int firstDelay, final Object runnable) { return awtCalcRegularly(f, delay, firstDelay, runnable); } static public SingleThread awtCalcEvery(JComponent c, int delay, int firstDelay, final Object runnable) { return awtCalcRegularly(c, delay, firstDelay, runnable); } static public SingleThread awtCalcEvery(JFrame f, int delay, final Object runnable) { return awtCalcRegularly(f, delay, delay, runnable); } static public SingleThread awtCalcEvery(JComponent c, int delay, Runnable runnable) { return awtCalcRegularly(c, delay, delay, runnable); } static public SingleThread awtCalcEvery(JComponent c, int delay, final Object runnable) { return awtCalcRegularly(c, delay, delay, runnable); } static public SingleThread awtCalcEvery(JComponent c, double delay, Runnable runnable) { return awtCalcEvery(c, delay, (Object) runnable); } static public SingleThread awtCalcEvery(JComponent c, double delay, Object runnable) { return awtCalcEvery(c, toMS_int(delay), runnable); } static public SingleThread awtCalcEvery(JComponent c, double firstDelay, double delay, final Object runnable) { return awtCalcEvery(c, toMS_int(delay), toMS_int(firstDelay), runnable); } static public AutoCompletion installCompletionProvider(DefaultCompletionProvider completionProvider, RSyntaxTextArea textArea) { return swing(() -> { if (completionProvider == null || textArea == null) return null; completionProvider.setAutoActivationRules(true, " "); var autoComplete = new AutoCompletion(completionProvider); autoComplete.setAutoCompleteSingleChoices(false); autoComplete.setAutoActivationEnabled(true); autoComplete.setAutoActivationDelay(2000); autoComplete.install(textArea); return autoComplete; }); } static public JPanel jCenteredSection(Component c) { return jCenteredSection("", c); } static public JPanel jCenteredSection(String title, Swingable c) { return jCenteredSection(title, wrap(c)); } static public JPanel jCenteredSection(String title, Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = jSection(title, c); ((TitledBorder) p.getBorder()).setTitleJustification(TitledBorder.CENTER); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = jSection(title, c);\r\n ((TitledBorder) p.getBorder()).setTitleJu..."; } }); } static public JPanel jCenteredSection(String title) { return jCenteredSection(title, jpanel()); } static public JButton jbutton(String text, Runnable action) { return newButton(text, action); } static public JButton jbutton(String text, Object action) { return newButton(text, action); } static public JButton jbutton(String text) { return newButton(text, null); } static public JButton jbutton(Action action) { return swingNu(JButton.class, action); } static public JPanel withTopAndLeftMargin(Component c) { return withTopAndLeftMargin(defaultMargin(), c); } static public JPanel withTopAndLeftMargin(int w, Component c) { return swing(() -> { JPanel p = marginPanel(); p.setBorder(BorderFactory.createEmptyBorder(w, w, 0, 0)); p.add(c); return p; }); } static public boolean isShowing(Component c) { return isComponentShowing(c); } static public void runInQAndWait(Q q, Runnable r) { if (r == null) return; if (isInQ(q)) { callF(r); return; } final Flag done = new Flag(); final Var error = new Var(); q.add(new Runnable() { public void run() { try { try { callF(r); } catch (Throwable e) { error.set(e); } finally { done.raise(); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n callF(r);\r\n } catch (Throwable e) {\r\n error.set(e);\r\n ..."; } }); done.waitUntilUp(); if (error.has()) throw rethrow(error.get()); } static public OKOrError okOrError(IF0 f) { try { return OKOrError_ok(f.get()); } catch (Throwable e) { printStackTrace(e); return OKOrError_error(e); } } static public OKOrError okOrError(Runnable r) { return okOrError(runnableToIF0(r)); } static public String exceptionToStringShorter_dontDropOuterExceptions(Throwable e) { String msg = hideCredentials(unnull(e.getMessage())); String className = baseClassName(e); if (!eq(className, "RuntimeException") && (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)) return className + prependIfNempty(": ", msg); else return msg; } static public JComponent jErrorView(Throwable e) { return jSmallErrorView(e); } static public String exceptionToStringShorter(Throwable e) { e = getInnerException(e); return exceptionToStringShorter_dontDropOuterExceptions(e); } static public A evalWithTimeoutOrTypedException(int timeoutMS, IF0 f) { return evalWithTimeoutOrTypedException(toSeconds(timeoutMS), f); } static public A evalWithTimeoutOrTypedException(double timeoutSeconds, IF0 f) { Either e = evalWithTimeout(timeoutSeconds, f); if (e.isA()) return (A) e.a(); throw new TimeoutException(timeoutSeconds, f, e.b()); } static public JTextArea showText(final String title, Object text) { return showText(null, title, text); } static public JTextArea showText(JTextArea ta, final String title, Object text) { final String _text = str(text); if (ta != null) return activateFrameAndReturnComponent(setFrameTitle(title, setText(ta, _text))); return swing(new F0() { public JTextArea get() { try { JTextArea textArea = newTypeWriterTextArea(_text); makeFrame(title, new JScrollPane(textArea)); return textArea; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JTextArea textArea = newTypeWriterTextArea(_text);\r\n makeFrame(title, new ..."; } }); } static public JTextArea showText(Object text) { return showText(str(text)); } static public JTextArea showText(String text) { return showText(autoFrameTitle(), text); } static public JTextArea showText() { return showText(""); } static public String pnlToString(String prefix, Iterable l) { return hijackPrint(new Runnable() { public void run() { try { pnl(prefix, l); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pnl(prefix, l)"; } }); } static public String pnlToString(final Iterable l) { return hijackPrint(new Runnable() { public void run() { try { pnl(l); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pnl(l)"; } }); } static public String pnlToString(final A[] l) { return hijackPrint(new Runnable() { public void run() { try { pnl(l); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pnl(l)"; } }); } static public String pnlToString(final Map map) { return hijackPrint(new Runnable() { public void run() { try { pnl(map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pnl(map)"; } }); } static public String pnlToString(MultiMap map) { return pnlToString(multiMapToMap(map)); } static public TreeMap toCIMap(Map map) { return asCIMap(map); } static public A setEditable(A a, boolean b) { if (a != null) { swing(() -> { a.setEditable(b); }); } return a; } static public Map rsyntaxTextArea_fixNumPad_map = litmap(KeyEvent.VK_UP, KeyEvent.VK_KP_UP, KeyEvent.VK_DOWN, KeyEvent.VK_KP_DOWN, KeyEvent.VK_LEFT, KeyEvent.VK_KP_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_KP_RIGHT); static public boolean rsyntaxTextArea_fixNumPad_done = false; static public void rsyntaxTextArea_fixNumPad() { if (rsyntaxTextArea_fixNumPad_done) return; RSyntaxTextAreaDefaultInputMap inputMap = new RSyntaxTextAreaDefaultInputMap(); for (KeyStroke key : inputMap.keys()) { Integer code = rsyntaxTextArea_fixNumPad_map.get(key.getKeyCode()); if (code != null) inputMap.put(KeyStroke.getKeyStroke(code, key.getModifiers()), inputMap.get(key)); } UIManager.put("RSyntaxTextAreaUI.inputMap", inputMap); } static public RSyntaxTextArea javaxSyntaxTextArea() { return swing(new F0() { public RSyntaxTextArea get() { try { RSyntaxTextArea textArea = new RSyntaxTextArea(1, 10); initSyntaxTextArea(textArea); textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); return textArea; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "RSyntaxTextArea textArea = new RSyntaxTextArea(1, 10);\r\n initSyntaxTextAre..."; } }); } static public List getMenus(JMenuBar mb) { if (mb == null) return null; return countIteratorAsList(mb.getMenuCount(), i -> mb.getMenu(i)); } static public List getMenuItems(JMenu menu) { if (menu == null) return null; return nonNulls(countIterator(menu.getItemCount(), i -> menu.getItem(i))); } static public void showDialogOnSameScreen(JDialog dialog, Component c) { swing(() -> { if (dialog == null) return; Window w = getWindow(c); if (w != null) centerWindowWithin(dialog, screenBounds_safe(screenNrOfWindow(w))); dialog.setVisible(true); }); } static public Font deriveFont(Font font, float size) { return font == null ? null : font.deriveFont(size); } static public boolean containsInstance(Iterable i, Class c) { if (i != null) for (Object o : i) if (isInstanceX(c, o)) return true; return false; } static public void register(Concept c) { registerConcept(c); } static public A setToolTip(A c, Object toolTip) { return setToolTipText(c, toolTip); } static public A setToolTip(Object toolTip, A c) { return setToolTipText(c, toolTip); } static public void setToolTip(TrayIcon trayIcon, String toolTip) { setTrayIconToolTip(trayIcon, toolTip); } static public BigInteger plus(BigInteger a, BigInteger b) { return a.add(b); } static public BigInteger plus(BigInteger a, long b) { return a.add(bigint(b)); } static public long plus(long a, long b) { return a + b; } static public int plus(int a, int b) { return a + b; } static public float plus(float a, float b) { return a + b; } static public double plus(double a, double b) { return a + b; } static public List list(Class type) { return list(type, db_mainConcepts()); } static public List list(Class type, Concepts cc) { return cc.list(type); } static public List list(Concepts concepts, Class type) { return concepts.list(type); } static public List list(String type) { return db_mainConcepts().list(type); } static public List list(Concepts concepts, String type) { return concepts.list(type); } static public List list(Concepts concepts) { return asList(concepts.allConcepts()); } static public RuntimeException error() { throw new RuntimeException("fail"); } static public RuntimeException error(String msg) { throw new RuntimeException(msg); } static public String ok(Object o) { return format("ok *", o); } static public long now_virtualTime; static public long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } static public String localDateWithSeconds(long time) { SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss"); return format.format(time); } static public String localDateWithSeconds() { return localDateWithSeconds(now()); } static public double elapsedMinutes_timestamp(long time) { return toMinutes(now() - time); } static public double elapsedSeconds_timestamp(long time) { return toSeconds(now() - time); } static public void scaffoldCalled(Object obj, Object function, Object... args) { printShortenedFunctionCall(200, (obj == null ? "" : shorten(20, str(obj)) + " :: ") + function, args); } static public JPanel westAndCenterWithMargin(Component w, Component c) { return westAndCenter(withRightMargin(w), c); } static public JPanel westAndCenterWithMargin(int margin, Component w, Component c) { return westAndCenter(withRightMargin(margin, w), c); } static public JPanel vstack(Object... parts) { return vstack2(parts); } static public JPanel vstack(List parts) { return vstack(toObjectArray(parts)); } static public JLabel jClickableImage_instantToolTip(String imageID, String toolTip, Runnable action) { return onLeftClick(instaToolTip(toolTip, jImageLabel(imageID)), action); } static public String collapse(String s) { return collapseWord(s); } static public JPanel northAndCenterWithMargin(int margin, Component n, Component c) { return northAndCenter(withBottomMargin(margin, n), c); } static public JPanel northAndCenterWithMargin(Component n, Component c) { return northAndCenter(withBottomMargin(n), c); } static public JLabel liveValueLabel(LiveValue lv) { return jLiveValueLabel(lv); } static public JLabel liveValueLabel(IVarWithNotify var) { return jVarLabel(var); } static public JSplitPane jhsplit(Component l, Component r) { return jhsplit(l, r, 0.5); } static public JSplitPane jhsplit(Component l, Component r, double splitPoint, int delay) { return jhsplit(l, r, splitPoint); } static public JSplitPane jhsplit(Component l, Component r, double splitPoint) { return setSplitPaneOnFirstShowing(swingNu(JSplitPane.class, JSplitPane.HORIZONTAL_SPLIT, wrap(l), wrap(r)), splitPoint); } static public JSplitPane jhsplit(double splitPoint, Component l, Component r) { return jhsplit(l, r, splitPoint); } static public String joinNemptiesWithSpace(String... strings) { return joinNempties(" ", strings); } static public String joinNemptiesWithSpace(Collection strings) { return joinNempties(" ", strings); } static public String unicode_downPointingTriangle() { return charToString(0x25BC); } static public void addActionListener(JTextField tf, final Runnable action) { onEnter(tf, action); } static public void addActionListener(final JComboBox cb, final Runnable action) { if (cb != null) { swing(() -> { cb.addActionListener(actionListener(action)); }); } } static public void addActionListener(final AbstractButton b, final Runnable action) { if (b != null) { swing(() -> { b.addActionListener(actionListener(action)); }); } } static public int getWidth(Component c) { return c == null ? 0 : (int) swingCall(c, "getWidth"); } static public int getPreferredWidth(Component c) { return preferredWidth(c); } static public int getHeight(Component c) { return c == null ? 0 : (int) swingCall(c, "getHeight"); } static public A onChange(A spinner, Object r) { return onChange(spinner, toRunnable(r)); } static public A onChange(A spinner, Runnable r) { if (r != null) { swing(() -> { spinner.addChangeListener(changeListener(r)); }); } return spinner; } static public A onChange(A b, Object r) { { swing(() -> { b.addItemListener(itemListener(r)); }); } return b; } static public void onChange(JTextComponent tc, Object r) { onUpdate(tc, r); } static public void onChange(JTextComponent tc, Runnable r) { onUpdate(tc, r); } static public A onChange(A slider, final Object r) { { swing(() -> { slider.addChangeListener(changeListener(r)); }); } return slider; } static public JComboBox onChange(JComboBox cb, Runnable r) { addActionListener(cb, r); return cb; } static public JComboBox onChange(JComboBox cb, IVF1 f) { if (f != null) addActionListener(cb, () -> f.get(getSelectedItem_typed(cb))); return cb; } static public JComboBox onChange(Object r, JComboBox cb) { return onChange(cb, r); } static public JComboBox 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)"; } }); return cb; } static public A onChange(A tabs, Runnable r) { { swing(() -> { tabs.addChangeListener(changeListener(r)); }); } return tabs; } static public A onChange(Runnable r, A cc) { if (cc != null && r != null) { swing(() -> { cc.getSelectionModel().addChangeListener(changeListener(r)); }); } return cc; } static public void onChange(IHasChangeListeners a, ChangeTriggerable b) { if (a != null && b != null) a.onChange(new ChangeTrigger(b)); } static public String hijackPrint_tee(Runnable r) { final StringBuilder buf = new StringBuilder(); Object old = interceptPrintInThisThread(new F1() { public Boolean get(String s) { buf.append(s); return true; } }); try { callF(r); return str(buf); } finally { interceptPrintInThisThread(old); } } static public Timestamp tsNow() { return new Timestamp(); } static volatile public boolean sleep_noSleep = false; static public void sleep(long ms) { ping(); if (ms < 0) return; if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread"); try { Thread.sleep(ms); } catch (Exception e) { throw new RuntimeException(e); } } static public void sleep() { try { if (sleep_noSleep) throw fail("nosleep"); print("Sleeping."); sleepQuietly(); } catch (Exception __e) { throw rethrow(__e); } } static public List syncGetAndClear(Collection l) { return syncCloneAndClearList(l); } static public A getWeakRef(Reference ref) { return ref == null ? null : ref.get(); } static public Object pcallF(Object f, Object... args) { return pcallFunction(f, args); } static public A pcallF(F0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { printStackTrace(__e); } return null; } static public B pcallF(F1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { printStackTrace(__e); } return null; } static public void pcallF(VF1 f, A a) { try { { if (f != null) f.get(a); } } catch (Throwable __e) { printStackTrace(__e); } } static public Object pcallF(Runnable r) { try { { if (r != null) r.run(); } } catch (Throwable __e) { printStackTrace(__e); } return null; } static public A pcallF(IF0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { printStackTrace(__e); } return null; } static public B pcallF(IF1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { printStackTrace(__e); } return null; } static public void cancelAndInterruptThread(Thread t) { if (t == null) return; cancelThread(t); t.interrupt(); } static public Pt toPt(Point p) { return p == null ? null : new Pt(p.x, p.y); } static public Pt toPt(Dimension d) { return d == null ? null : new Pt(d.width, d.width); } static public boolean stdEq2(Object a, Object b) { if (a == null) return b == null; if (b == null) return false; if (a.getClass() != b.getClass()) return false; for (String field : allFields(a)) if (neq(getOpt(a, field), getOpt(b, field))) return false; return true; } static public int stdHash2(Object a) { if (a == null) return 0; return stdHash(a, toStringArray(allFields(a))); } static public long toMS(double seconds) { return (long) (seconds * 1000); } static public long nanos() { return nanoTime(); } static public String joinNemptiesWithComma(Object... strings) { return joinNempties(", ", strings); } static public String joinNemptiesWithComma(Iterable strings) { return joinNempties(", ", strings); } static public String formatElapsedTimeWithAppropriateUnit(double seconds) { if (seconds >= 1) return formatDouble(seconds, 3) + " s"; double ms = seconds * 1000; if (ms >= 1) return formatDouble(ms, 3) + " ms"; double us = ms * 1000; if (us >= 1) return formatDouble(us, 3) + " µs"; double ns = us * 1000; return formatDouble(ns, 3) + " ns"; } static public double nanosToSeconds(double nanos) { return nanoSecondsToSeconds(nanos); } static public JPanel northAndCenterWithMargins(Component n, Component c) { return applyDefaultMargin(northAndCenter(withBottomMargin(n), c)); } static public JPanel northAndCenterWithMargins(int margin, Component n, Component c) { return applyMargin(margin, northAndCenter(withBottomMargin(margin, n), c)); } static public JPanel westAndEastWithMargin(Component w, Component e) { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.WEST, wrap(w)); panel.add(BorderLayout.CENTER, horizontalStrut(10)); panel.add(BorderLayout.EAST, wrap(e)); return panel; } static public JComponent withLabel(String label, JComponent component) { return westAndCenter(jlabel(label + " "), component); } static public JComponent withLabel(JComponent label, JComponent component) { return westAndCenterWithMargin(label, component); } static public JLabel jlabel(final String text) { return swingConstruct(BetterLabel.class, text); } static public JLabel jlabel() { return jlabel(" "); } static public JPanel jpanel(LayoutManager layout) { return swingNu(JPanel.class, layout); } static public JPanel jpanel() { return swingNu(JPanel.class); } static public A fontSizePlus(final int delta, final A c) { if (c != null) { swing(() -> { Font font = c.getFont(); c.setFont(font.deriveFont(font.getSize2D() + delta)); }); } return c; } static public long toLong(Object o) { if (o instanceof Number) return ((Number) o).longValue(); if (o instanceof String) return parseLong((String) o); return 0; } static public JLabel jcenteredLabel(String text) { return setHorizontalAlignment(JLabel.CENTER, jLabel(text)); } static public JLabel jcenteredLabel() { return jcenteredLabel(" "); } static public JScrollPane jscroll_centered_borderless(Component c) { return borderlessScrollPane(jscroll_centered(c)); } static public int vstackWithSpacing_default = 10; static public JPanel vstackWithSpacing(final List parts) { return vstackWithSpacing(parts, vstackWithSpacing_default); } static public JPanel vstackWithSpacing(final List parts, final int spacing) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.insets = new Insets(spacing / 2, 0, (spacing + 1) / 2, 0); smartAddWithLayout(panel, gbc, toObjectArray(nonNulls(parts))); 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 public JPanel vstackWithSpacing(Component... parts) { return vstackWithSpacing(asList(parts), vstackWithSpacing_default); } static public JPanel vstackWithSpacing(int spacing, Component... parts) { return vstackWithSpacing(asList(parts), spacing); } static public List cloneTakeFirst(Collection l, int n) { n = min(n, l(l)); List out = emptyList(n); if (n != 0) for (A a : l) { out.add(a); if (l(out) >= n) break; } return out; } static public List cloneTakeFirst(int n, Collection l) { return cloneTakeFirst(l, n); } static public List cloneTakeFirst(List l, int n) { return l(l) <= n ? l : cloneSubList(l, 0, n); } static public List cloneTakeFirst(int n, List l) { return cloneTakeFirst(l, n); } static public JScrollPane jscroll_borderless(Component c) { return borderlessScrollPane(jscroll(c)); } static public JTextArea wordWrapTypeWriterTextArea() { return wrappedTextArea(newTypeWriterTextArea()); } static public JTextArea wordWrapTypeWriterTextArea(String text) { return wrappedTextArea(newTypeWriterTextArea(text)); } static public JLabel jcenteredlabel(String text) { return jcenteredLabel(text); } static public JLabel jcenteredlabel() { return jcenteredLabel(); } static public int toIntPercent(double ratio) { return roundToInt(ratio * 100); } static public int toIntPercent(float ratio) { return toIntPercent((double) ratio); } static public void onChangeAndNow(JComponent c, Object r) { onUpdateAndNow(c, r); } static public void onChangeAndNow(List l, Object r) { onUpdateAndNow(l, r); } static public JComboBox onChangeAndNow(JComboBox cb, IVF1 f) { onChange(cb, f); { if (f != null) f.get(getSelectedItem_typed(cb)); } return cb; } static public A onChangeAndNow(A tabs, Runnable r) { if (r != null) { onChange(tabs, r); r.run(); } return tabs; } static public String formatLocalDateWithSeconds(long time) { return localDateWithSeconds(time); } static public String formatLocalDateWithSeconds() { return localDateWithSeconds(); } static public long clockTimeToSystemTime(long now) { return now == 0 ? 0 : now + clockToSysTimeDiff(); } static public int seconds() { return seconds(Calendar.getInstance()); } static public int seconds(Calendar c) { return c.get(Calendar.SECOND); } static public String formatDouble(double d, int digits) { String format = digits <= 0 ? "0" : "0." + rep(digits, '#'); return decimalFormatEnglish(format, d); } static public String formatDouble(double d) { return str(d); } static public String div(Object contents, Object... params) { return hfulltag("div", contents, params); } static public String div() { return div(""); } static public BigInteger div(BigInteger a, BigInteger b) { return a.divide(b); } static public BigInteger div(BigInteger a, int b) { return a.divide(bigint(b)); } static public Complex div(Complex a, double b) { return new Complex(a.re / b, a.im / b); } static public double div(double a, double b) { return a / b; } static public double div(double a, int b) { return a / b; } static public int div(int a, int b) { return a / b; } static public List minus(Collection a, Object... b) { Set set = asSet(b); List l = new ArrayList(); for (Object s : unnull(a)) if (!set.contains(s)) l.add(s); return l; } static public BigInteger minus(BigInteger a, BigInteger b) { return a.subtract(b); } static public Complex minus(Complex c) { return c == null ? null : complex(-c.re(), -c.im()); } static public int minus(int a, int b) { return a - b; } static public double minus(double a, double b) { return a - b; } static public Class _getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } static public Class _getClass(Object o) { return o == null ? null : o instanceof Class ? (Class) o : o.getClass(); } static public Class _getClass(Object realm, String name) { try { return classLoaderForObject(realm).loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } static public Method findMethod_cached(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { _MethodCache cache = callOpt_getCache((Class) o); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false)) return m; return null; } else { _MethodCache cache = callOpt_getCache(o.getClass()); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) if (findMethod_checkArgs(m, args, false)) return m; return null; } } catch (Exception __e) { throw rethrow(__e); } } static public HashMap litmap(Object... x) { HashMap map = new HashMap(); litmap_impl(map, x); return map; } static public void litmap_impl(Map map, Object... x) { if (x != null) for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null) map.put(x[i], x[i + 1]); } static public int lKeys(MultiMap mm) { return mm == null ? 0 : mm.keysSize(); } static public String dropNumberPrefix(String s) { return dropFirst(s, indexOfNonDigit(s)); } static public Throwable getInnerException(Throwable e) { if (e == null) return null; while (e.getCause() != null) e = e.getCause(); return e; } static public Throwable getInnerException(Runnable r) { return getInnerException(getException(r)); } static public String baseClassName(String className) { return substring(className, className.lastIndexOf('.') + 1); } static public String baseClassName(Object o) { return baseClassName(getClassName(o)); } static public String prependIfNempty(String prefix, String s) { return empty(s) ? unnull(s) : prefix + s; } static public List sortedByCalculatedField(Iterable c, Object f) { return sortByCalculatedField(c, f); } static public List sortedByCalculatedField(Object f, Iterable c) { return sortedByCalculatedField(c, f); } static public List sortedByCalculatedField(IF1 f, Iterable c) { return sortedByCalculatedField(c, f); } static public List sortedByCalculatedField(Iterable c, IF1 f) { List l = cloneList(c); sort(l, new Comparator() { public int compare(A a, A b) { return stdcompare(f.get(a), f.get(b)); } }); return l; } static public void printVars_str(Object... params) { print(renderVars_str(params)); } static public List allMethodNames(Object o) { Class c = _getClass(o); TreeSet names = new TreeSet(); while (c != null) { for (Method m : c.getDeclaredMethods()) names.add(m.getName()); c = c.getSuperclass(); } return asList(names); } static public Method findMethodNamed(Object obj, String method) { if (obj == null) return null; if (obj instanceof Class) return findMethodNamed((Class) obj, method); return findMethodNamed(obj.getClass(), method); } static public Method findMethodNamed(Class c, String method) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) { makeAccessible(m); return m; } c = c.getSuperclass(); } return null; } static public int hashMap_internalHash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } static public void replaceLastElement(List l, A a) { if (nempty(l)) l.set(l(l) - 1, a); } static public Object[] toArray(Collection c) { return toObjectArray(c); } static public A[] toArray(Class type, Iterable c) { return toArray(c, type); } static public A[] toArray(Class type, Collection c) { return toArray(c, type); } static public A[] toArray(Collection c, Class type) { A[] a = arrayOfType(l(c), type); if (a.length == 0) return a; asList(c).toArray(a); return a; } static public A[] toArray(Iterable c, Class type) { A[] a = arrayOfType(l(c), type); if (a.length == 0) return a; asList(c).toArray(a); return a; } static public A[] toArray(A[] array, Collection c) { if (array == null || c == null) return null; asList(c).toArray(array); return array; } static public String strUnnull(Object o) { return o == null ? "" : str(o); } static public String jlabel_textAsHTML_center_ifNeeded(String text) { if (swic(text, "") && ewic(text, "")) return text; if (!containsNewLines(text)) return text; return jlabel_textAsHTML_center(text); } static public String assertIsIdentifier(String s) { if (!isIdentifier(s)) throw fail("Not an identifier: " + quote(s)); return s; } static public String assertIsIdentifier(String msg, String s) { if (!isIdentifier(s)) throw fail(msg + " - Not an identifier: " + quote(s)); return s; } static public boolean isDigit(char c) { return Character.isDigit(c); } static public boolean emptyString(String s) { return s == null || s.length() == 0; } static public boolean isNormalQuoted(String s) { int l = l(s); if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"')) return false; int j = 1; while (j < l) if (s.charAt(j) == '"') return j == l - 1; else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; return false; } static public boolean isMultilineQuoted(String s) { if (!startsWith(s, "[")) return false; int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; return i < s.length() && s.charAt(i) == '['; } static public String longestPrefixInNavigableSet(String s, NavigableSet set) { if (set == null || s == null) return null; while (licensed()) { String key = set.floor(s); if (key == null) break; int n = lCommonPrefix(key, s); if (n == l(key)) return key; s = takeFirst(s, n); } return null; } static public String joinNempties(String sep, Object... strings) { return joinStrings(sep, strings); } static public String joinNempties(String sep, Iterable strings) { return joinStrings(sep, strings); } static public List flattenCollectionsAndArrays(Iterable a) { List l = new ArrayList(); for (Object x : a) if (x instanceof Collection) l.addAll(flattenCollectionsAndArrays((Collection) x)); else if (x instanceof Object[]) l.addAll(flattenCollectionsAndArrays(asList((Object[]) x))); else l.add(x); return l; } static public int identityHash(Object o) { return identityHashCode(o); } static public List uniquifyList(Collection l) { if (l == null) return null; if (l(l) < 2) return asList(l); HashSet set = new HashSet(); List out = new ArrayList(); for (A a : l) if (set.add(a)) out.add(a); return out; } static public void addToContainer(Container a, Component... b) { if (a == null) return; { swing(() -> { for (Component c : unnullForIteration(b)) if (c != null) a.add(c); }); } } static public ImageSurface imageSurface(BufferedImage img) { return swingNu(ImageSurface.class, img); } static public ImageSurface imageSurface(MakesBufferedImage img) { return swingNu(ImageSurface.class, img); } static public ImageSurface imageSurface() { return swingNu(ImageSurface.class); } static public void imageSurface_pixelated(ImageSurface imageSurface) { if (imageSurface == null) return; imageSurface.setDoubleBuffered(true); imageSurface.noAlpha = true; imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR; repaint(imageSurface); } static public void imageSurface_pixelated(ImageSurface imageSurface, boolean pixelated) { if (pixelated) imageSurface_pixelated(imageSurface); else imageSurface_unpixelated(imageSurface); } static public File programDir_mine; static public File programDir() { return programDir(getProgramID()); } static public File programDir(String snippetID) { boolean me = sameSnippetID(snippetID, programID()); if (programDir_mine != null && me) return programDir_mine; File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID)); if (me) { String c = caseID(); if (nempty(c)) dir = newFile(dir, c); } return dir; } static public File programDir(String snippetID, String subPath) { return new File(programDir(snippetID), subPath); } static public String dbProgramID() { return getDBProgramID(); } static public BufferedImage toBufferedImageOpt(Object o) { if (o instanceof BufferedImage) return ((BufferedImage) o); if (o instanceof Image) return copyImage((Image) o); if (o instanceof MakesBufferedImage) return ((MakesBufferedImage) o).getBufferedImage(); if (o instanceof File) if (isImageFile((File) o)) return loadBufferedImageFile((File) o); String c = getClassName(o); if (eqOneOf(c, "main$BWImage", "main$RGBImage")) return (BufferedImage) call(o, "getBufferedImage"); if (eq(c, "main$PNGFile")) return (BufferedImage) call(o, "getImage"); return null; } static public String _userHome; static public String userHome() { if (_userHome == null) return actualUserHome(); return _userHome; } static public File userHome(String path) { return new File(userDir(), path); } static public File touchFile(File file) { try { closeRandomAccessFile(newRandomAccessFile(mkdirsForFile(file), "rw")); return file; } catch (Exception __e) { throw rethrow(__e); } } static public boolean removeFile(File file) { return deleteFile(file); } static public List toLinesFullTrim(String s) { List l = new ArrayList(); for (String line : toLines(s)) if (nempty(line = trim(line))) l.add(line); return l; } static public List toLinesFullTrim(File f) { List l = new ArrayList(); for (String line : linesFromFile(f)) if (nempty(line = trim(line))) l.add(line); return l; } static public ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal(); static public void checkFileNotTooBigToRead(File f) { callF(checkFileNotTooBigToRead_tl.get(), f); } public static File mkdirsForFile(File file) { File dir = file.getParentFile(); if (dir != null) { dir.mkdirs(); if (!dir.isDirectory()) if (dir.isFile()) throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!"); else throw fail("Unknown IO exception during mkdirs of " + f2s(file)); } return file; } public static String mkdirsForFile(String path) { mkdirsForFile(new File(path)); return path; } static public File copyFile(File src, File dest) { try { FileInputStream inputStream = new FileInputStream(src.getPath()); FileOutputStream outputStream = newFileOutputStream(dest.getPath()); try { copyStream(inputStream, outputStream); inputStream.close(); } finally { outputStream.close(); } return dest; } catch (Exception __e) { throw rethrow(__e); } } static public FileOutputStream newFileOutputStream(File path) throws IOException { return newFileOutputStream(path.getPath()); } static public FileOutputStream newFileOutputStream(String path) throws IOException { return newFileOutputStream(path, false); } static public FileOutputStream newFileOutputStream(File path, boolean append) throws IOException { return newFileOutputStream(path.getPath(), append); } static public FileOutputStream newFileOutputStream(String path, boolean append) throws IOException { mkdirsForFile(path); FileOutputStream f = new FileOutputStream(path, append); _registerIO(f, path, true); return f; } static public String fromLines(Iterable lines) { StringBuilder buf = new StringBuilder(); if (lines != null) for (Object line : lines) buf.append(str(line)).append('\n'); return buf.toString(); } static public String fromLines(String... lines) { return fromLines(asList(lines)); } static public IterableIterator toLines(File f) { return linesFromFile(f); } static public List toLines(String s) { List lines = new ArrayList(); if (s == null) return lines; int start = 0; while (true) { int i = toLines_nextLineBreak(s, start); if (i < 0) { if (s.length() > start) lines.add(s.substring(start)); break; } lines.add(s.substring(start, i)); if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n') i += 2; else ++i; start = i; } return lines; } static public int toLines_nextLineBreak(String s, int start) { int n = s.length(); for (int i = start; i < n; i++) { char c = s.charAt(i); if (c == '\r' || c == '\n') return i; } return -1; } static public List mapToLines(Map map) { List l = new ArrayList(); for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key))); return l; } static public String mapToLines(Map map, Object f) { return lines(map(map, f)); } static public String mapToLines(Object f, Map map) { return lines(map(map, f)); } static public String mapToLines(Object f, Iterable l) { return lines(map(f, l)); } static public String mapToLines(Iterable l, IF1 f) { return mapToLines((Object) f, l); } static public String mapToLines(IF1 f, Iterable l) { return mapToLines((Object) f, l); } static public String mapToLines(Map map, IF2 f) { return lines(map(map, f)); } static public String mapToLines(IF1 f, A data1, A... moreData) { return lines(map(f, data1, moreData)); } static public A jPreferHeight(int h, A c) { Dimension size = c.getPreferredSize(); c.setPreferredSize(new Dimension(size.width, max(h, size.height))); return c; } static public String strOrNull(Object o) { return o == null ? null : str(o); } static public String formatWithThousands(long l) { return formatWithThousandsSeparator(l); } static public double fraction(double d) { return d % 1; } static public String n_fancy2(long l, String singular, String plural) { return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural); } static public String n_fancy2(Collection l, String singular, String plural) { return n_fancy2(l(l), singular, plural); } static public String n_fancy2(Map m, String singular, String plural) { return n_fancy2(l(m), singular, plural); } static public String n_fancy2(Object[] a, String singular, String plural) { return n_fancy2(l(a), singular, plural); } static public String n_fancy2(MultiSet ms, String singular, String plural) { return n_fancy2(l(ms), singular, plural); } static public int toInt(Object o) { if (o == null) return 0; if (o instanceof Number) return ((Number) o).intValue(); if (o instanceof String) return parseInt((String) o); if (o instanceof Boolean) return boolToInt((Boolean) o); throw fail("woot not int: " + getClassName(o)); } static public int toInt(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } static public boolean odd(int i) { return (i & 1) != 0; } static public boolean odd(long i) { return (i & 1) != 0; } static public boolean odd(BigInteger i) { return odd(toInt(i)); } static public boolean isSpaceEtc(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } static public File fileAppendToName(File f, String suffix) { return newFile(f.getPath() + suffix); } static public A uniqueConcept(Class c, Object... params) { return uniqueConcept(db_mainConcepts(), c, params); } static public A uniqueConcept(Concepts cc, Class c, Object... params) { AutoCloseable __1 = tempDBLock(cc); try { params = expandParams(c, params); A x = findConceptWhere(cc, c, params); if (x == null) { x = unlisted(c); csetAll(x, params); cc.register(x); } else { } return x; } finally { _close(__1); } } static public AutoCloseable tempDBLock(Concepts concepts) { return tempLock(concepts.lock); } static public AutoCloseable tempDBLock() { return tempDBLock(db_mainConcepts()); } static public Object[] expandParams(Class c, Object[] params) { if (l(params) == 1) params = new Object[] { singleFieldName(c), params[0] }; else warnIfOddCount(params); return params; } static public A findConceptWhereCI(Class c, Object... params) { return findConceptWhereCI(db_mainConcepts(), c, params); } static public A findConceptWhereCI(Concepts concepts, Class c, Object... params) { params = expandParams(c, params); Lowest>> bestIndex = new Lowest(); if (concepts.ciFieldIndices != null) for (int i = 0; i < l(params); i += 2) { ping(); Object val = params[i + 1]; IFieldIndex index = concepts.getCIFieldIndex(c, (String) params[i]); if (index != null) { Collection l = index.getAll(val); bestIndex.put(() -> l, l(l)); } if (concepts.useBackRefsForSearches && val instanceof Concept) { bestIndex.put(() -> findBackRefs(((Concept) val), c), ((Concept) val)._backRefCount()); } } if (bestIndex.has()) { Collection l = bestIndex.get().get(); if (l(params) == 2) return first(l); for (A x : l) { ping(); if (checkConceptFieldsIC(x, params)) return x; } return null; } else { for (A x : concepts.list(c)) { ping(); if (checkConceptFieldsIC(x, params)) return x; } return null; } } static public Concept findConceptWhereCI(Concepts concepts, String c, Object... params) { for (Concept x : concepts.list(c)) { ping(); if (checkConceptFieldsIC(x, params)) return x; } return null; } static public A unlisted(Class c, Object... args) { concepts_unlisted.set(true); try { return nuObject(c, args); } finally { concepts_unlisted.set(null); } } static public Concept unlisted(String name, Object... args) { Class cc = findClass(name); concepts_unlisted.set(true); try { return cc != null ? nuObject(cc) : new Concept(name); } finally { concepts_unlisted.set(null); } } static public int csetAll(Concept c, Object... values) { return cset(c, values); } static public int csetAll(Iterable l, Object... values) { int n = 0; for (Concept c : unnullForIteration(l)) n += cset(c, values); return n; } static public int csetAll(Concept c, Map values) { int n = 0; for (Map.Entry __0 : _entrySet(values)) { String field = __0.getKey(); Object value = __0.getValue(); n += cset(c, field, value); } return n; } static public File getProgramFile(String progID, String fileName) { if (new File(fileName).isAbsolute()) return new File(fileName); return new File(getProgramDir(progID), fileName); } static public File getProgramFile(String fileName) { return getProgramFile(getProgramID(), fileName); } static public String conceptsFileName() { return "concepts.structure.gz"; } static public List filter(Iterable c, Object pred) { if (pred instanceof F1) return filter(c, (F1) pred); List x = new ArrayList(); if (c != null) for (Object o : c) if (isTrue(callF(pred, o))) x.add(o); return x; } static public List filter(Object pred, Iterable c) { return filter(c, pred); } static public List filter(Iterable c, F1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o)) x.add(o); return x; } static public List filter(F1 pred, Iterable c) { return filter(c, pred); } static public List filter(Iterable c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o)) x.add(o); return x; } static public List filter(B[] c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o)) x.add(o); return x; } static public List filter(IF1 pred, Iterable c) { return filter(c, pred); } static public List listDirs(File dir) { if (dir == null) return emptyList(); File[] files = dir.listFiles(); List l = new ArrayList(); if (files != null) for (File f : files) if (f.isDirectory()) l.add(f); return l; } static public List listDirs(String dir) { return listDirs(newFile(dir)); } static public boolean isFile(File f) { return f != null && f.isFile(); } static public boolean isFile(String path) { return isFile(newFile(path)); } static public int methodApplicabilityScore_withPrimitiveWidening(Executable m, Object[] args) { Class[] types = m.getParameterTypes(); if (types.length != l(args)) return Integer.MAX_VALUE; int score = 0; boolean widenings = false; for (int i = 0; i < types.length; i++) { Object a = args[i]; Class c = types[i]; if (a == null) { if (c.isPrimitive()) return Integer.MAX_VALUE; } else { Class t = a.getClass(); int s = typeConversionScoreWithUnboxing(t, c); if (s == Integer.MAX_VALUE) return Integer.MAX_VALUE; if (s < 0) widenings = true; score += abs(s); } } return widenings ? -score : score; } static public Object invokeConstructor(Constructor m, Object... args) { try { makeAccessible(m); return m.newInstance(args); } catch (Exception __e) { throw rethrow(__e); } } static public float abs(float f) { return Math.abs(f); } static public int abs(int i) { return Math.abs(i); } static public double abs(double d) { return Math.abs(d); } static public double abs(Complex c) { return c.abs(); } static public Object invokeConstructorWithWidening(Constructor m, Object... args) { try { try { Class[] types = m.getParameterTypes(); int n = types.length; Object[] args2 = new Object[n]; for (int i = 0; i < n; i++) args2[i] = convertPrimitiveIfNecessary(args[i], types[i]); return invokeConstructor(m, args2); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args))); } } catch (Exception __e) { throw rethrow(__e); } } static public List allToString(Iterable c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } static public List allToString(Object[] c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } static public Object[] toObjectArray(Collection c) { return toObjectArray((Iterable) c); } static public Object[] toObjectArray(Iterable c) { List l = asList(c); return l.toArray(new Object[l.size()]); } static public Object invokeMethodWithWidening(Method m, Object o, Object... args) { try { try { Class[] types = m.getParameterTypes(); int n = types.length; Object[] args2 = new Object[n]; for (int i = 0; i < n; i++) args2[i] = convertPrimitiveIfNecessary(args[i], types[i]); return m.invoke(o, args2); } catch (InvocationTargetException e) { throw rethrow(getExceptionCause(e)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args))); } } catch (Exception __e) { throw rethrow(__e); } } static public Object callWithVarargs(Object o, String method, Object... args) { return call_withVarargs(o, method, args); } static public int methodApplicabilityScore_onTypes(Method m, Class[] argTypes) { return methodApplicabilityScore_onTypes((Executable) m, argTypes); } static public int methodApplicabilityScore_onTypes(Executable m, Class[] argTypes) { Class[] types = m.getParameterTypes(); if (types.length != argTypes.length) return Integer.MAX_VALUE; int score = 0; for (int i = 0; i < types.length; i++) { Class a = argTypes[i]; Class c = types[i]; if (c == a) { } else if (isSubclassOf(a, c)) ++score; else return Integer.MAX_VALUE; } return score; } static public A singletonOpt(Collection l) { return l(l) == 1 ? first(l) : null; } static public List findNonDefaultInterfaceMethods(Class intrface) { if (!isInterface(intrface)) return null; List l = new ArrayList(); _MethodCache cache = getMethodCache(intrface); Class c = intrface; do { for (Method m : c.getDeclaredMethods()) if (m.getDeclaringClass() != Object.class && !m.isDefault() && !isStaticMethod(m)) l.add(m); c = c.getSuperclass(); } while (c != null); return l; } static public boolean regionMatches(String a, int offsetA, String b, int offsetB, int len) { return a != null && b != null && a.regionMatches(offsetA, b, offsetB, len); } static public boolean regionMatches(String a, int offsetA, String b) { return regionMatches(a, offsetA, b, 0, l(b)); } static public String javaTok_substringN(String s, int i, int j) { if (i == j) return ""; if (j == i + 1 && s.charAt(i) == ' ') return " "; return s.substring(i, j); } static public String javaTok_substringC(String s, int i, int j) { return s.substring(i, j); } static public List javaTokWithExisting(String s, List existing) { ++javaTok_n; int nExisting = javaTok_opt && existing != null ? existing.size() : 0; ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList(); int l = s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(javaTok_substringN(s, i, j)); ++n; i = j; if (i >= l) break; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) { j += 2; while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j; } else if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else if (c == '[' && d == '[') { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') { do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]")); j = Math.min(j + 3, l); } else ++j; if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } static public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) { return t.length() == j - i && s.regionMatches(i, t, 0, j - i); } static public boolean addToCollection(Collection c, A a) { return c != null && c.add(a); } static public void smartSet(Field f, Object o, Object value) throws Exception { try { f.set(o, value); } catch (Exception e) { Class type = f.getType(); if (type == int.class && value instanceof Long) { f.set(o, ((Long) value).intValue()); return; } if (type == boolean.class && value instanceof String) { f.set(o, isTrueOrYes(((String) value))); return; } 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 public TreeMap descTreeMap() { return revTreeMap(); } static public A optParam(ThreadLocal tl, A defaultValue) { return optPar(tl, defaultValue); } static public A optParam(ThreadLocal tl) { return optPar(tl); } static public Object optParam(String name, Map params) { return mapGet(params, name); } static public A optParam(Object[] opt, String name, A defaultValue) { int n = l(opt); if (n == 1 && opt[0] instanceof Map) { Map map = (Map) (opt[0]); return map.containsKey(name) ? (A) map.get(name) : 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 public Object optParam(Object[] opt, String name) { return optParam(opt, name, null); } static public Object optParam(String name, Object[] params) { return optParam(params, name); } static public String replacePlusWithSpace(String s) { return replace(s, '+', ' '); } static public List splitAtSpace(String s) { return empty(s) ? emptyList() : asList(s.split("\\s+")); } static public A pairA(Pair p) { return p == null ? null : p.a; } static public B pairB(Pair p) { return p == null ? null : p.b; } static public int scoredSearch_score_single(String s, String query) { int i = indexOfIC_underscore(s, query); if (i < 0) return 0; if (i > 0) return 1; return l(s) == l(query) ? 3 : 2; } static public List secondOfPairs(Collection> l) { return lambdaMap(__63 -> secondOfPair(__63), l); } static public > IterableIterator nestedIterator(final Iterable c, final F1 makeInnerIterator) { return nestedIterator(iterator(c), makeInnerIterator); } static public > IterableIterator nestedIterator(Collection c, final IF1 makeInnerIterator) { return nestedIterator(iterator(c), makeInnerIterator); } static public > IterableIterator nestedIterator(Iterator it1, IF1 makeInnerIterator) { return nestedIterator(it1, toF1(makeInnerIterator)); } static public > IterableIterator nestedIterator(final Iterator it1, final F1 makeInnerIterator) { if (it1 == null || !it1.hasNext()) return emptyIterableIterator(); return iff(new F0() { public A a; public Iterator innerIterator; { nextOuter(); } public void nextOuter() { a = it1.next(); innerIterator = makeInnerIterator.get(a); } public Object get() { while (true) { ping(); if (innerIterator != null && innerIterator.hasNext()) return innerIterator.next(); if (!it1.hasNext()) return endMarker(); nextOuter(); } } }); } static public > IterableIterator nestedIterator(IF1 makeInnerIterator, Iterator it1) { return nestedIterator(it1, makeInnerIterator); } static public > IterableIterator nestedIterator(IF1 makeInnerIterator, Collection l) { return nestedIterator(l, makeInnerIterator); } static public class mapI_It extends IterableIterator { public Object f; public Iterator i; public mapI_It() { } public mapI_It(Object f, Iterator i) { this.i = i; this.f = f; } public boolean hasNext() { return i.hasNext(); } public Object next() { return callF(f, i.next()); } public String toString() { return formatFunctionCall("mapI", f, i); } } static public IterableIterator mapI(final Object f, final Iterator i) { return new mapI_It(f, i); } static public IterableIterator mapI(IterableIterator i, Object f) { return mapI((Iterator) i, f); } static public IterableIterator mapI(Object f, IterableIterator i) { return mapI((Iterator) i, f); } static public IterableIterator mapI(Iterator i, Object f) { return mapI(f, i); } static public IterableIterator mapI(Iterable i, IF1 f) { return mapI(i, (Object) f); } static public IterableIterator mapI(Iterator i, IF1 f) { return mapI(f, i); } static public IterableIterator mapI(IterableIterator i, IF1 f) { return mapI((Iterator) i, f); } static public IterableIterator mapI(IF1 f, Iterable i) { return mapI(i, (Object) f); } static public IterableIterator mapI(Iterable i, Object f) { return mapI(f, i.iterator()); } static public IterableIterator mapI(Object f, Iterable i) { return mapI(i, f); } static public Set synchroLinkedHashSet() { return Collections.synchronizedSet(new CompactLinkedHashSet()); } static public ActionListener actionListener(final Object runnable) { return actionListener(runnable, null); } static public ActionListener actionListener(final Object runnable, final Object instanceToHold) { if (runnable instanceof ActionListener) return (ActionListener) runnable; final Object info = _threadInfo(); return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { _threadInheritInfo(info); AutoCloseable __1 = holdInstance(instanceToHold); try { pcallF(runnable); } finally { _close(__1); } } catch (Throwable __e) { messageBox(__e); } } }; } static public 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.removeChangeListener(listener); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lv.removeChangeListener(listener)"; } }); return component; } static public A setToolTipText(final A c, final Object toolTip) { if (c == null) return null; { swing(() -> { String s = nullIfEmpty(str(toolTip)); if (neq(s, c.getToolTipText())) c.setToolTipText(s); }); } return c; } static public A setToolTipText(Object toolTip, A c) { return setToolTipText(c, toolTip); } static public A bindJLabelToTransformedLiveValue(IF1 f, A label, LiveValue lv) { bindLiveValueListenerToComponent(label, lv, () -> { setText(label, strOrNull(f.get(lv.get()))); }); return label; } static public MouseAdapter onMouseDown(Component c, Runnable r) { return onMouseDown(c, runnableToIVF1(r)); } static public MouseAdapter onMouseDown(Component c, IVF1 f) { return c == null || f == null ? null : swing(() -> { MouseAdapter ma = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) f.get(e); } }; c.addMouseListener(ma); return ma; }); } static public IVF1 runnableToIVF1(Runnable r) { return r == null ? null : a -> r.run(); } static public int numberOfChildren(final Container c) { return c == null ? 0 : swing(new F0() { public Integer get() { try { return c.getComponentCount(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getComponentCount();"; } }); } static public boolean jmenuItem_newThreads = false; static public JMenuItem jmenuItem(final String text) { return jMenuItem(text, null); } static public JMenuItem jmenuItem(final String text, final Object r) { return swing(new F0() { public JMenuItem get() { try { Pair p = jmenu_autoMnemonic(dropPrefix("[disabled] ", text)); JMenuItem mi = new JMenuItem(p.a); if (startsWith(text, "[disabled] ")) disableMenuItem(mi); if (p.b != 0) mi.setMnemonic(p.b); mi.addActionListener(jmenuItem_newThreads ? actionListenerInNewThread(r) : actionListener(r)); return mi; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Pair p = jmenu_autoMnemonic(dropPrefix(\"[disabled] \", text));\r\n JM..."; } }); } static public void addDirectMenuItem(JMenuBar mb, String text, Object action) { if (mb != null) { swing(() -> { addDirectMenuItem(mb, directJMenuItem(text, action)); }); } } static public void addDirectMenuItem(Component c, String text, Object action) { addDirectMenuItem(addMenuBar(c), text, action); } static public void addDirectMenuItem(JMenuBar mb, JMenuItem menuItem) { if (mb != null) { swing(() -> { mb.add(menuItem); revalidate(mb); }); } } static public ClassLoader getClassLoader(Object o) { return o == null ? null : _getClass(o).getClassLoader(); } static public boolean dirOrZipContainsPath(File location, String subPath) { try { if (location.isDirectory()) { return new File(location, subPath).exists(); } else if (location.isFile()) { return zipFileContains_falseOnError(location, subPath); } return false; } catch (Exception __e) { throw rethrow(__e); } } static public File[] listFiles(File dir) { File[] files = dir.listFiles(); return files == null ? new File[0] : files; } static public File[] listFiles(String dir) { return listFiles(new File(dir)); } static public String dropPrefixOrNull(String prefix, String s) { return s != null && s.startsWith(prefix) ? s.substring(l(prefix)) : null; } static public List loadedJigsawModuleNames() { var moduleLayer = ModuleLayer.boot(); var modules = moduleLayer.modules(); return map(modules, mod -> mod.getName()); } static public List classNamesInJigsawModule(String moduleName) { return classNamesInJigsawModule(moduleName, javaHome()); } static public List classNamesInJigsawModule(String moduleName, File javaHome) { return classNamesInJarOrDir(jigsawModuleFile(moduleName, javaHome), "classes/"); } static public void printNumberedLines(Map map) { printNumberedLines(mapToLines(map)); } static public void printNumberedLines(String prefix, Map map) { printNumberedLines(prefix, mapToLines(map)); } static public A printNumberedLines(A l) { int i = 0; if (l != null) for (Object a : cloneList(l)) print((++i) + ". " + str(a)); return l; } static public A printNumberedLines(String prefix, A l) { int i = 0; if (l != null) for (Object a : cloneList(l)) print(prefix + (++i) + ". " + str(a)); return l; } static public void printNumberedLines(Object[] l) { printNumberedLines("", l); } static public void printNumberedLines(String prefix, Object[] l) { printNumberedLines(prefix, wrapAsList(l)); } static public void printNumberedLines(Object o) { printNumberedLines(lines(str(o))); } static public IMeta toIMeta(Object o) { if (o == null) return null; if (o instanceof IMeta) return ((IMeta) o); if (o instanceof JComponent) return initMetaOfJComponent((JComponent) o); if (o instanceof BufferedImage) return optCast(IMeta.class, ((BufferedImage) o).getProperty("meta")); return null; } static public IMeta initIMeta(Object o) { if (o == null) return null; if (o instanceof IMeta) return ((IMeta) o); if (o instanceof JComponent) return initMetaOfJComponent((JComponent) o); if (o instanceof BufferedImage) return optCast(IMeta.class, ((BufferedImage) o).getProperty("meta")); return null; } static public Map makeObjectMetaMap() { return new CompactHashMap(); } static public IAutoCloseableF0 tempMetaMutex(IMeta o) { return o == null ? null : o._tempMetaMutex(); } static public void syncMapPut2(Map map, A key, B value) { if (map != null && key != null) synchronized (collectionMutex(map)) { if (value != null) map.put(key, value); else map.remove(key); } } static public Object getOptMC(String field) { return getOpt(mc(), field); } static public List syncList() { return synchroList(); } static public List syncList(List l) { return synchroList(l); } static public Class hotwire(String src) { return hotwire(src, __1 -> mainClassNameForClassLoader(__1)); } static public Class hotwire(String src, IF1 calculateMainClass) { assertFalse(_inCore()); Class j = getJavaX(); if (isAndroid()) { synchronized (j) { 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 public A callMain(A c, String... args) { callOpt(c, "main", new Object[] { args }); return c; } static public void callMain() { callMain(mc()); } static public Collection findConceptsWhere(Class c, Object... params) { return findConceptsWhere(db_mainConcepts(), c, params); } static public Collection findConceptsWhere(String c, Object... params) { return findConceptsWhere(db_mainConcepts(), c, params); } static public Collection findConceptsWhere(Concepts concepts, Class c, Object... params) { ping(); params = expandParams(c, params); if (concepts.fieldIndices != null) for (int i = 0; i < l(params); i += 2) { IFieldIndex index = concepts.getFieldIndex(c, (String) params[i]); if (index != null) { Collection rawList = index.getAll(params[i + 1]); params = dropEntryFromParams(params, i); if (params == null) return rawList; List l = new ArrayList(); for (A x : rawList) if (checkConceptFields(x, params)) l.add(x); return l; } } return filterConcepts(concepts.list(c), params); } static public Collection findConceptsWhere(Concepts concepts, String c, Object... params) { return filterConcepts(concepts.list(c), params); } static public void sort(T[] a, Comparator c) { if (a != null) Arrays.sort(a, c); } static public void sort(T[] a) { if (a != null) Arrays.sort(a); } static public void sort(int[] a) { if (a != null) Arrays.sort(a); } static public void sort(List a, Comparator c) { if (a != null) Collections.sort(a, c); } static public void sort(List a) { if (a != null) Collections.sort(a); } static public int cmpAlphanumIC(String a, String b) { return cmpAlphaNum(a, b); } static public A pcallF_typed(F0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { printStackTrace(__e); } return null; } static public B pcallF_typed(F1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { printStackTrace(__e); } return null; } static public void pcallF_typed(VF1 f, A a) { try { { if (f != null) f.get(a); } } catch (Throwable __e) { printStackTrace(__e); } } static public void pcallF_typed(IVF1 f, A a) { try { { if (f != null) f.get(a); } } catch (Throwable __e) { printStackTrace(__e); } } static public Object pcallF_typed(Runnable r) { try { { if (r != null) r.run(); } } catch (Throwable __e) { printStackTrace(__e); } return null; } static public A pcallF_typed(IF0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { printStackTrace(__e); } return null; } static public B pcallF_typed(IF1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { printStackTrace(__e); } return null; } static public long round(double d) { return Math.round(d); } static public String round(String s) { return roundBracket(s); } static public Complex round(Complex c) { return new Complex(round(c.re), round(c.im)); } static public boolean infoMessage_alwaysOnTop = true; static public double infoMessage_defaultTime = 5.0; static public JWindow infoMessage(String text) { return infoMessage(text, infoMessage_defaultTime); } static public JWindow infoMessage(final String text, final double seconds) { printHidingCredentials(text); return infoMessage_noprint(text, seconds); } static public JWindow infoMessage_noprint(String text) { return infoMessage_noprint(text, infoMessage_defaultTime); } static public JWindow infoMessage_noprint(final String _text, final double seconds) { final String text = hideCredentials(_text); if (empty(text)) return null; logQuotedWithDate(infoBoxesLogFile(), text); if (isHeadless()) return null; return (JWindow) swingAndWait(new F0() { public Object get() { try { JWindow window = makeWindow(infoMessage_makePanel(text)); window.setSize(300, 150); moveToTopRightCorner(window); if (infoMessage_alwaysOnTop) window.setAlwaysOnTop(true); if (vmBus_noObjections("shouldShowInfoBox", window, text)) window.setVisible(true); if (seconds != 0) disposeWindowAfter(iround(seconds * 1000), window); return window; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JWindow window = makeWindow(infoMessage_makePanel(text));\r\n window.setSize..."; } }); } static public JWindow infoMessage(Throwable e) { printStackTrace(e); return infoMessage(exceptionToStringShort(e)); } static public void close_pcall(AutoCloseable c) { if (c != null) { try { c.close(); } catch (Throwable __e) { printStackTrace(__e); } } } static public void preCleanUp(Object c) { if (c instanceof Collection) { for (Object o : ((Collection) c)) preCleanUp(o); return; } callOpt(c, "licensed_off"); setOpt_raw(c, "ping_anyActions", true); setOpt_raw(c, "cleaningUp_flag", true); } static public void innerCleanUp(Object c) { if (!isFalse(pcallOpt(c, "cleanMeUp"))) for (String name : sorted(methodsStartingWith(c, "cleanMeUp_"))) try { callOpt(c, name); } catch (Throwable e) { print("Error cleaning up: " + programID(c)); _handleException(e); } } static public void innerCleanUp() { innerCleanUp(mc()); } static public Object pcallOpt(Object o, String method, Object... args) { try { return callOpt(o, method, args); } catch (Throwable __e) { printStackTrace(__e); } return null; } static public List registeredThreads(Object o) { Map map = (Map) (getOpt(o, "_registerThread_threads")); if (map == null) return ll(); map.size(); synchronized (map) { return asList(keys(map)); } } static public List registeredThreads() { _registerThread_threads.size(); return asList(keys(_registerThread_threads)); } static public void interruptThreads(Collection threads) { for (Thread t : unnull(threads)) interruptThread(t); } static public void interruptThreads(Class mainClass) { interruptThreads(registeredThreads(mainClass)); } static public void retireClassLoader(ClassLoader cl) { if (isJavaXClassLoader(cl)) setOptAll(cl, "retired", true, "retiredMarker", new DefunctClassLoader()); } static public Object cget(Object c, String field) { c = derefRef(c); Object o = getOpt(c, field); return derefRef(o); } static public Object cget(String field, Object c) { return cget(c, field); } static public String shortenClassName(String name) { if (name == null) return null; int i = lastIndexOf(name, "$"); if (i < 0) i = lastIndexOf(name, "."); return i < 0 ? name : substring(name, i + 1); } static public String renderVars_stringifier(IStringifier stringifier, Object... params) { List l = new ArrayList(); int i = 0; if (odd(l(params))) { l.add(stringifier.toString(first(params))); ++i; } for (; i + 1 < l(params); i += 2) l.add(params[i] + "=" + stringifier.toString(params[i + 1])); return trim(joinWithComma(l)); } static public String shortDynamicClassName(Object o) { if (o instanceof DynamicObject && ((DynamicObject) o).className != null) return ((DynamicObject) o).className; return shortClassName(o); } static public int countLines(String s) { return l(toLines(s)); } static public String repeat(char c, int n) { n = Math.max(n, 0); char[] chars = new char[n]; for (int i = 0; i < n; i++) chars[i] = c; return new String(chars); } static public List repeat(A a, int n) { n = Math.max(n, 0); List l = new ArrayList(n); for (int i = 0; i < n; i++) l.add(a); return l; } static public List repeat(int n, A a) { return repeat(a, n); } static public int indent_default = 2; static public String indent(int indent) { return repeat(' ', indent); } static public String indent(int indent, String s) { return indent(repeat(' ', indent), s); } static public String indent(String indent, String s) { return indent + replace(unnull(s), "\n", "\n" + indent); } static public String indent(String s) { return indent(indent_default, s); } static public List indent(String indent, List lines) { List l = new ArrayList(); if (lines != null) for (String s : lines) l.add(indent + s); return l; } static public Lock appendToFile_lock = lock(); static public boolean appendToFile_keepOpen = false; static public HashMap appendToFile_writers = new HashMap(); static public void appendToFile(String path, String s) { try { Lock __0 = appendToFile_lock; lock(__0); try { mkdirsForFile(new File(path)); path = getCanonicalPath(path); Writer writer = appendToFile_writers.get(path); if (writer == null) { writer = new BufferedWriter(new OutputStreamWriter(newFileOutputStream(path, true), "UTF-8")); if (appendToFile_keepOpen) appendToFile_writers.put(path, writer); } writer.write(s); if (!appendToFile_keepOpen) writer.close(); } finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } } static public void appendToFile(File path, String s) { if (path != null) appendToFile(path.getPath(), s); } static public void cleanMeUp_appendToFile() { AutoCloseable __3 = tempCleaningUp(); try { Lock __1 = appendToFile_lock; lock(__1); try { closeAllWriters(values(appendToFile_writers)); appendToFile_writers.clear(); } finally { unlock(__1); } } finally { _close(__3); } } static public File programFile(String name) { return prepareProgramFile(name); } static public File programFile(String progID, String name) { return prepareProgramFile(progID, name); } static public SimpleDateFormat simpleDateFormat_UTC(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf; } static public String formatUTCWithMS_24() { return formatUTCWithMS_24(now()); } static public String formatUTCWithMS_24(long time) { var sdf = new SimpleDateFormat("HH:mm:ss.SSSS"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf.format(time) + " UTC"; } static public Object[] asArray(List l) { return toObjectArray(l); } static public A[] asArray(Class type, List l) { return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size())); } static public boolean isEditableComboBox(final JComboBox cb) { return cb != null && swing(new F0() { public Boolean get() { try { return cb.isEditable(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return cb.isEditable();"; } }); } static public void fillJMenu(final JMenu 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) fillJMenu(m, asArray((List) o)); else if (isMenuSeparatorIndicator(o)) { if (menuItemCount(m) != 0) 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!;\r\n if (isCurlyBracketed(s)) {\r\n setEnabled(mi,..."; } }); 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); else if (o instanceof String || o instanceof Action || o instanceof Component) call(m, "add", o); else if (o == null && y instanceof Runnable) ++i; else if (o != null) print("Unknown menu item: " + o); } } static public 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 IVF1) callF(o, m); else 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!;\r\n if (isCurlyBracketed(s)) {\r\n setEnabled(mi,..."; } }); 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); else if (o instanceof String || o instanceof Action || o instanceof Component) call(m, "add", o); else if (o != null) print("Unknown menu item: " + o); } } static public JTextArea showWrappedText(final String title, final String text) { return (JTextArea) swingAndWait(new F0() { public Object get() { try { JTextArea textArea = wrappedTextArea(text); caretToHome(textArea); textArea.setFont(typeWriterFont()); makeFrame(title, new JScrollPane(textArea)); return textArea; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JTextArea textArea = wrappedTextArea(text);\r\n caretToHome(textArea);\r\n ..."; } }); } static public JTextArea showWrappedText(Object text) { return showWrappedText(autoFrameTitle(), str(text)); } static public JPanel centerAndEastWithMarginInbetween(Component c, final Component e) { return centerAndEast(c, withLeftMargin(e)); } static public JScrollPane borderlessScrollPane(JScrollPane sp) { return setBorder(null, withoutViewportBorder(sp)); } static public JScrollPane jHigherScrollPane(final JComponent c) { return swing(new F0() { public JScrollPane get() { try { return new JScrollPane(c) { public Dimension getPreferredSize() { Component view = getViewport().getView(); if (view == null) return super.getPreferredSize(); int pref_width = view.getPreferredSize().width; setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); Dimension dim = new Dimension(pref_width, super.getPreferredSize().height + getHorizontalScrollBar().getSize().height); setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); return dim; } }; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret new JScrollPane(c) {\r\n public Dimension getPreferredSize() {\r\n Co..."; } }); } static public JPanel jFullCenter(final Component c) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new GridBagLayout()); panel.add(c); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new GridBagLayout);\r\n panel.add(c);\r\n ret panel;"; } }); } static public A setMetaSrc(A a, Object src) { setMetaAndVerify(a, "src", src); return a; } static public A setMetaSrc(A a, Object src) { setMetaAndVerify(a, "src", src); return a; } static public A setTextKeepCaret(final String text, final A c) { if (c != null) { swing(() -> { int caret = c.getCaretPosition(); setText(c, text); setCaretPosition(c, caret); }); } return c; } static public A setTextKeepCaret(A c, String text) { return setTextKeepCaret(text, c); } static public void addKeyListener(final Component c, final KeyListener l) { if (c != null) { swing(() -> { c.addKeyListener(l); }); } } static public KeyListener ctrlEnterKeyListener(final Object action) { final Object info = _threadInfo(); return new KeyAdapter() { public void keyReleased(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_ENTER && ke.getModifiers() == KeyEvent.CTRL_MASK) { _threadInheritInfo(info); pcallF(action); } } }; } static public SingleThread awtCalcRegularly(JComponent component, int delay, int firstDelay, Object runnable) { final SingleThread thread = new SingleThread(); final Runnable r2 = addThreadInfoToRunnable(runnable); final Object info = _threadInfo(); installTimer(component, delay, firstDelay, new Runnable() { public void run() { if (!licensed()) return; _threadInheritInfo(info); thread.go(r2); } }); return thread; } static public SingleThread awtCalcRegularly(JFrame frame, int delay, int firstDelay, final Object runnable) { return awtCalcRegularly(getRootPane(frame), delay, firstDelay, runnable); } static public int toMS_int(double seconds) { return toInt_checked((long) (seconds * 1000)); } static public JComponent wrap(Object swingable) { return _recordNewSwingComponent(wrap_2(swingable)); } static public JComponent wrap_2(Object swingable) { if (swingable == null) return null; JComponent c; if (swingable instanceof Component) c = componentToJComponent((Component) swingable); else if (swingable instanceof Swingable) c = componentToJComponent(((Swingable) swingable).visualize()); else c = componentToJComponent((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 public JPanel jSection(Component c) { return jSection("", c); } static public JPanel jSection(final String title, final Component c) { return swing(new F0() { public 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 public JPanel jSection(String title) { return jSection(title, jpanel()); } static public JPanel jSection(LiveValue lv, Component c) { return jLiveValueSection(lv, c); } static public boolean newButton_autoToolTip = true; static public JButton newButton(final String text, final Object action) { return swing(new F0() { public JButton get() { try { String text2 = dropPrefix("[disabled] ", text); JButton btn = basicJButton(text2); if (l(text2) < l(text)) btn.setEnabled(false); if (newButton_autoToolTip) { btn.setToolTipText(btn.getText()); } if (action != null) btn.addActionListener(actionListener(action, btn)); return btn; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "S text2 = dropPrefix(\"[disabled] \", text);\r\n JButton btn = basicJButton(te..."; } }); } static public A swingNu(final Class c, final Object... args) { return swingConstruct(c, args); } static public int defaultMargin() { return withMargin_defaultWidth; } static public JPanel marginPanel() { return jtransparent(borderLayoutPanel()); } static public boolean isComponentShowing(final Component c) { return c != null && swing(new F0() { public Boolean get() { try { return c.isShowing(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.isShowing();"; } }); } static public boolean isInQ(Q q) { return q != null && isCurrentThread(q.rst.thread); } static public OKOrError OKOrError_ok(A a) { return new OKOrError(a); } static public OKOrError OKOrError_error(Throwable e) { return new OKOrError(false, e); } static public IF0 runnableToIF0(Runnable r) { return r == null ? null : () -> { r.run(); return null; }; } static public JComponent jSmallErrorView(Throwable e) { var btn = jimageButtonScaledToWidth(32, errorIconID(), "Show error details", () -> showErrorFrame(e)); var label = jlabel_noAutoToolTip(exceptionType(e)); return jline(btn, label); } static public double toSeconds(long ms) { return ms / 1000.0; } static public String toSeconds(long ms, int digits) { return formatDouble(toSeconds(ms), digits); } static public double toSeconds(double ms) { return ms / 1000.0; } static public String toSeconds(double ms, int digits) { return formatDouble(toSeconds(ms), digits); } static public Set evalWithTimeout_inTime = synchroSet(); static public Set evalWithTimeout_allThreads = newWeakHashSet(); static public ThreadLocal evalWithTimeout_threadName = new ThreadLocal(); static public Either evalWithTimeout(double timeoutSeconds, IF0 r) { return (Either) evalWithTimeout(timeoutSeconds, (Object) r); } static public Either evalWithTimeout(int timeoutMS, final Object r) { final Flag done = new Flag(); final Flag doneWaiting = new Flag(); final Var var = new Var(); final Var error = new Var(); Thread t = newThread(getAndClearThreadLocal(evalWithTimeout_threadName), new Runnable() { public void run() { try { try { try { var.set(callF(r)); } finally { evalWithTimeout_allThreads.remove(currentThread()); } } catch (Throwable e) { error.set(e); if (doneWaiting.isUp()) printStackTrace_inPossiblyCancelledThread(e); } finally { done.raise(); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n try {\r\n var.set(callF(r));\r\n } finally {\r\n ev..."; } }); beforeDelegatingToThread(t); try { startThread(t); evalWithTimeout_inTime.add(t); evalWithTimeout_allThreads.add(t); try { done.waitUntilUp(timeoutMS); doneWaiting.raise(); } finally { evalWithTimeout_inTime.remove(t); } if (!done.isUp()) { print("Cancelling thread (timeout)"); cancelAndInterruptThread(t); return either2(t); } if (error.get() != null) rethrow(error.get()); return either1(var.get()); } finally { afterDelegatingToThread(t); } } static public Either evalWithTimeout(double timeoutSeconds, final Object r) { return evalWithTimeout(toMS_int(timeoutSeconds), r); } static public A activateFrameAndReturnComponent(A c) { activateFrame(c); return c; } static public A setFrameTitle(A c, final String title) { final Frame f = getAWTFrame(c); if (f != null) { swing(() -> { f.setTitle(title); }); } return c; } static public A setFrameTitle(String title, A c) { return setFrameTitle(c, title); } static public JFrame setFrameTitle(String title) { Object f = getOpt(mc(), "frame"); if (f instanceof JFrame) return setFrameTitle((JFrame) f, title); return null; } static public JTextArea newTypeWriterTextArea() { return newTypeWriterTextArea(""); } static public JTextArea newTypeWriterTextArea(String text) { return withTypeWriterFont(jTextArea(text)); } static public String makeFrame_defaultIcon; static public boolean makeFrame_hideConsole = false; static public ThreadLocal> makeFrame_post = new ThreadLocal(); static public JFrame makeFrame() { return makeFrame((Component) null); } static public JFrame makeFrame(Object content) { return makeFrame(programTitle(), content); } static public JFrame makeFrame(String title) { return makeFrame(title, null); } static public JFrame makeFrame(String title, Object content) { return makeFrame(title, content, true); } static public JFrame makeFrame(final String title, final Object content, final boolean showIt) { final VF1 post = optParam(makeFrame_post); return swing(new F0() { public 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); 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 public String autoFrameTitle_value; static public String autoFrameTitle() { return autoFrameTitle_value != null ? autoFrameTitle_value : getProgramTitle(); } static public void autoFrameTitle(Component c) { setFrameTitle(getFrame(c), autoFrameTitle()); } static public String hijackPrint(Runnable r) { StringBuilder buf = new StringBuilder(); Object old = interceptPrintInThisThread(new F1() { public Boolean get(String s) { buf.append(s); return false; } }); try { { if (r != null) r.run(); } return str(buf); } finally { interceptPrintInThisThread(old); } } static public Map> multiMapToMap(MultiMap m) { return m == null ? null : m.data; } static public TreeMap asCIMap(Map map) { return asCaseInsensitiveMap(map); } static public boolean initSyntaxTextArea_numPadFix = true; static public void initSyntaxTextArea(RSyntaxTextArea textArea) { swing(() -> { if (initSyntaxTextArea_numPadFix) new NumPadFixingInputMap().replaceOn(textArea); textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); textArea.setHighlightCurrentLine(false); textArea.setTabSize(2); textArea.setTabsEmulated(true); textArea.setCodeFoldingEnabled(false); textArea.setMarkOccurrences(true); }); } static public List countIteratorAsList(int b) { return countIteratorAsList(0, b); } static public List countIteratorAsList(int a, int b) { return countIteratorToList(a, b); } static public List countIteratorAsList(int b, IF1 f) { return countIteratorAsList(0, b, f); } static public List countIteratorAsList(int a, int b, IF1 f) { return countIteratorToList(a, b, f); } static public List countIteratorAsList(int a, int b, int step) { return countIteratorToList(a, b, step); } static public List countIteratorAsList(double a, double b, double step, IF1 f) { return countIteratorToList(a, b, step, f); } static public List countIteratorAsList(double a, double b, double step) { return countIteratorToList(a, b, step); } static public List countIteratorAsList(IF1 f, double a, double b, double step) { return countIteratorToList(f, a, b, step); } static public List countIteratorAsList(IF1 f, int b) { return countIteratorAsList(f, 0, b); } static public List countIteratorAsList(IF1 f, int a, int b) { return countIteratorToList(f, a, b); } static public List nonNulls(Iterable l) { return withoutNulls(l); } static public List nonNulls(A[] l) { return withoutNulls(l); } static public Map nonNulls(Map map) { return withoutNulls(map); } static public IterableIterator countIterator(int b) { return countIterator(0, b); } static public IterableIterator countIterator(int a, int b) { return countIterator_exclusive(a, b); } static public IterableIterator countIterator(int b, IF1 f) { return countIterator(0, b, f); } static public IterableIterator countIterator(int a, int b, IF1 f) { return countIterator_exclusive(a, b, f); } static public IterableIterator countIterator(int a, int b, int step) { return countIterator_exclusive_step(a, b, step); } static public IterableIterator countIterator(double a, double b, double step, IF1 f) { return countIterator_exclusive_step(a, b, step, f); } static public IterableIterator countIterator(double a, double b, double step) { return countIterator_exclusive_step(a, b, step); } static public IterableIterator countIterator(IF1 f, double a, double b, double step) { return countIterator(a, b, step, f); } static public IterableIterator countIterator(IF1 f, int b) { return countIterator(f, 0, b); } static public IterableIterator countIterator(IF1 f, int a, int b) { return countIterator_exclusive(a, b, f); } static public Window getWindow(Object o) { if (!(o instanceof Component)) return null; return swing(() -> { Component c = (Component) o; while (c != null) { if (c instanceof Window) return ((Window) c); c = c.getParent(); } return null; }); } static public void centerWindowWithin(Window w, Rect r) { if (w != null) { swing(() -> { w.setLocation(r.x + (r.w - w.getWidth()) / 2, r.y + (r.h - w.getHeight()) / 2); }); } } static public Rect screenBounds_safe(int iScreen) { return screenBounds(min(iScreen, screenCount() - 1)); } static public int screenNrOfWindow(Window w) { if (w == null) return -1; Rect bounds = boundsAsRect(w); return indexOfMax(allScreenBounds(), screen -> area(intersectRects(bounds, screen))); } static public A registerConcept(A c) { return registerConcept(db_mainConcepts(), c); } static public A registerConcept(Concepts cc, A c) { { if (cc != null) cc.register(c); } return c; } static public void setTrayIconToolTip(TrayIcon trayIcon, String toolTip) { if (trayIcon != null) trayIcon.setToolTip(toolTip); } static public BigInteger bigint(String s) { return new BigInteger(s); } static public BigInteger bigint(long l) { return BigInteger.valueOf(l); } static public String format(String pat, Object... args) { return format3(pat, args); } static public SimpleDateFormat simpleDateFormat_local(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(localTimeZone()); return sdf; } static public double toMinutes(long ms) { return ms / 60000.0; } static public void printShortenedFunctionCall(Object fname, Object... args) { printShortenedFunctionCall(100, fname, args); } static public void printShortenedFunctionCall(int len, Object fname, Object... args) { print(shorten(len, formatFunctionCall(fname, args))); } static public JPanel westAndCenter(final Component w, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.WEST, wrap(w)); panel.add(BorderLayout.CENTER, wrap(c)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST..."; } }); } static public int withRightMargin_defaultWidth = 6; static public JPanel withRightMargin(Component c) { return withRightMargin(withRightMargin_defaultWidth, c); } static public JPanel withRightMargin(final int w, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = marginPanel(); 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 = marginPanel();\r\n p.setBorder(BorderFactory.createEmptyBorder(0,..."; } }); } static public JPanel vstack2(final Object... parts) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = GridBagConstraints.REMAINDER; smartAddWithLayout(panel, gbc, parts); gbc.weighty = 1; 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 public A onLeftClick(final A c, final Object runnable) { { swing(() -> { c.addMouseListener(leftClickMouseAdapter(runnable)); }); } return c; } static public TrayIcon onLeftClick(final TrayIcon c, final Object runnable) { { swing(() -> { c.addMouseListener(leftClickMouseAdapter_noPt(runnable)); }); } return c; } static public A onLeftClick(final Object runnable, A c) { return onLeftClick(c, runnable); } static public A onLeftClick(Runnable runnable, A c) { return onLeftClick((Object) runnable, c); } static public A onLeftClick(A c, Runnable r) { return onLeftClick(r, c); } static public A onLeftClick(A c, IVF1 r) { return onLeftClick(c, (Object) r); } static public A instaToolTip(A c, String toolTip) { return instaToolTip(toolTip, c); } static public A instaToolTip(IF0 toolTip, A c) { new InstantNeverHideToolTip(toolTip, c); return c; } static public A instaToolTip(String toolTip, A c) { new InstantNeverHideToolTip(toolTip, c); return c; } static public JLabel jImageLabel(Image img) { return swingNu(JLabel.class, imageIcon(img)); } static public JLabel jImageLabel(javax.swing.Icon icon) { return swingNu(JLabel.class, icon); } static public JLabel jImageLabel(String imageID) { return jImageLabel(imageIcon(imageID)); } static public JLabel jImageLabel(String text, String imageID) { final JLabel l = swingNu(JLabel.class, text, imageIcon(imageID), JLabel.CENTER); { swing(() -> { l.setVerticalTextPosition(SwingConstants.BOTTOM); l.setHorizontalTextPosition(SwingConstants.CENTER); }); } return l; } static public String collapseWord(String s) { if (s == null) return ""; StringBuilder buf = new StringBuilder(); for (int i = 0; i < l(s); i++) if (i == 0 || !charactersEqualIC(s.charAt(i), s.charAt(i - 1))) buf.append(s.charAt(i)); return buf.toString(); } static public JPanel northAndCenter(Component n, Component c) { return centerAndNorth(c, n); } static public int withBottomMargin_defaultWidth = 6; static public JPanel withBottomMargin(Component c) { return withBottomMargin(withBottomMargin_defaultWidth, c); } static public JPanel withBottomMargin(final int w, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createEmptyBorder(0, 0, w, 0)); 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 public JLabel jLiveValueLabel(final LiveValue lv) { return bindJLabelToLiveValue(jlabel(), lv); } static public JLabel jVarLabel(IVarWithNotify var) { return bindJLabelToVar(jlabel(), var); } static public JSplitPane setSplitPaneOnFirstShowing(Component c, double value) { return setSplitPaneOnFirstShowing(c, value, 0); } static public JSplitPane setSplitPaneOnFirstShowing(Component c, double value, int delay) { final JSplitPane sp = first(childrenOfType(c, JSplitPane.class)); if (sp != null) onFirstResize(sp, new Runnable() { public void run() { try { if (delay == 0) sp.setDividerLocation(value); else awtLater(delay, new Runnable() { public void run() { try { sp.setDividerLocation(value); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "sp.setDividerLocation(value);"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef setSplitPaneOnFirstShowing_debug\r\n printVars setSplitPaneOnFirst..."; } }); return sp; } static public String charToString(char c) { return String.valueOf(c); } static public String charToString(int c) { return String.valueOf((char) c); } static public JTextField onEnter(JTextField tf, JButton btn) { if (btn != null) onEnter(tf, new Runnable() { public void run() { try { clickButton(btn); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "clickButton(btn)"; } }); return tf; } static public JTextField onEnter(JTextField tf, 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 public JButton onEnter(JButton btn, final Object action) { if (action == null || btn == null) return btn; btn.addActionListener(actionListener(action)); return btn; } static public JList onEnter(JList list, Object action) { list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action))); return list; } static public JComboBox onEnter(final JComboBox cb, Runnable action) { { swing(() -> { 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);"; } })); } }); } return cb; } static public 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 public JTextField onEnter(Runnable action, JTextField tf) { return onEnter(tf, action); } static public Object swingCall(final Object o, final String method, final Object... args) { return swing(new F0() { public Object get() { try { return call(o, method, args); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return call(o, method, args);"; } }); } static public int preferredWidth(Component c) { return c == null ? 0 : getPreferredSize(c).width; } static public ChangeListener changeListener(final Object r) { return new ChangeListener() { public void stateChanged(ChangeEvent e) { pcallF(r); } }; } static public ItemListener itemListener(final Object r) { return new ItemListener() { public void itemStateChanged(ItemEvent e) { pcallF(r); } }; } static public void onUpdate(JComponent c, Runnable r) { onUpdate(c, (Object) r); } static public void onUpdate(JComponent c, 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) ((ItemSelectable) c).addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { call(r); } }); else print("Warning: onUpdate doesn't know " + getClassName(c)); } static public void onUpdate(List l, Object r) { for (JComponent c : l) onUpdate(c, r); } static public A getSelectedItem_typed(JList l) { return swing(() -> l.getSelectedValue()); } static public A getSelectedItem_typed(JComboBox cb) { return swing(() -> (A) cb.getSelectedItem()); } static public JTextField textFieldFromComboBox(JComboBox cb) { return (JTextField) cb.getEditor().getEditorComponent(); } static public 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 public JComboBox onSelectedItem(final JComboBox cb, IVF1 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 public Object interceptPrintInThisThread(Object f) { Object old = print_byThread().get(); print_byThread().set(f); return old; } static public Object sleepQuietly_monitor = new Object(); static public void sleepQuietly() { try { assertFalse(isAWTThread()); synchronized (sleepQuietly_monitor) { sleepQuietly_monitor.wait(); } } catch (Exception __e) { throw rethrow(__e); } } static public List syncCloneAndClearList(Collection l) { if (l == null) return emptyList(); synchronized (collectionMutex(l)) { List l2 = cloneList(l); l.clear(); return l2; } } static public Object pcallFunction(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable __e) { printStackTrace(__e); } return null; } static public void cancelThread(Thread t) { if (t == null) return; ping(); synchronized (ping_actions) { ping_actions.put(t, "cancelled"); ping_anyActions = true; } } static public Map> allFields_cache = weakHashMap(); static public Set allFields(Object o) { if (o == null) return emptySet(); Class _c = _getClass(o); Set fields = allFields_cache.get(_c); if (fields == null) allFields_cache.put(_c, fields = asTreeSet(keys(getOpt_getFieldMap(o)))); return fields; } static public int stdHash(Object a, String... fields) { if (a == null) return 0; int hash = getClassName(a).hashCode(); for (String field : fields) hash = boostHashCombine(hash, hashCode(getOpt(a, field))); return hash; } static public String[] toStringArray(Collection c) { String[] a = new String[l(c)]; Iterator it = c.iterator(); for (int i = 0; i < l(a); i++) a[i] = it.next(); return a; } static public String[] toStringArray(Object o) { if (o instanceof String[]) return (String[]) o; else if (o instanceof Collection) return toStringArray((Collection) o); else throw fail("Not a collection or array: " + getClassName(o)); } static public long nanoTime() { return System.nanoTime(); } static public double nanoSecondsToSeconds(double nanos) { return nanos * 1e-9; } static public A applyDefaultMargin(final A c) { if (c != null) { swing(() -> { c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth)); }); } return c; } static public A applyMargin(int top, int left, int bottom, int right, A c) { return addMargin(top, left, bottom, right, c); } static public A applyMargin(int w, A c) { return addMargin(w, c); } static public Component horizontalStrut(int height) { return Box.createHorizontalStrut(height); } static public A swingConstruct(final Class c, final Object... args) { return swing(new F0() { public A get() { try { return nuObject(c, args); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return nuObject(c, args);"; } }); } static public A setHorizontalAlignment(final int pos, final A a) { swingCall(a, "setHorizontalAlignment", pos); return a; } static public A setHorizontalAlignment(final int pos, final A a) { swingCall(a, "setHorizontalAlignment", pos); return a; } static public A setHorizontalAlignment(final int pos, final A a) { swingCall(a, "setHorizontalAlignment", pos); return a; } static public JLabel jLabel(String text) { return jlabel(text); } static public JLabel jLabel() { return jlabel(); } static public JScrollPane jscroll_centered(Component c) { return c instanceof JScrollPane ? ((JScrollPane) c) : jscroll(jFullCenter(c)); } static public JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) { for (Object o : parts) panel.add(wrapForSmartAdd(o), layout); return panel; } static public JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) { return smartAddWithLayout(panel, layout, asList(flattenArray2(parts))); } static public Component jrigid() { return javax.swing.Box.createRigidArea(new Dimension(0, 0)); } static public List cloneSubList(List l, int startIndex, int endIndex) { return newSubList(l, startIndex, endIndex); } static public List cloneSubList(List l, int startIndex) { return newSubList(l, startIndex); } static public JScrollPane jscroll(Component c) { return swing(() -> { return c instanceof JScrollPane ? ((JScrollPane) c) : new JScrollPane(c); }); } static public JTextArea wrappedTextArea(final JTextArea ta) { enableWordWrapForTextArea(ta); return ta; } static public JTextArea wrappedTextArea() { return wrappedTextArea(jtextarea()); } static public JTextArea wrappedTextArea(String text) { JTextArea ta = wrappedTextArea(); setText(ta, text); return ta; } static public int roundToInt(double d) { return (int) Math.round(d); } static public void onUpdateAndNow(JComponent c, final Object r) { onUpdate(c, r); callF(r); } static public void onUpdateAndNow(List l, Object r) { for (JComponent c : l) onUpdate(c, r); callF(r); } static public long clockToSysTimeDiff() { return sysNow() - now(); } static public String rep(int n, char c) { return repeat(c, n); } static public String rep(char c, int n) { return repeat(c, n); } static public List rep(A a, int n) { return repeat(a, n); } static public List rep(int n, A a) { return repeat(n, a); } static public String decimalFormatEnglish(String format, double d) { return decimalFormatEnglish(format).format(d); } static public java.text.DecimalFormat decimalFormatEnglish(String format) { return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)); } static public String hfulltag(String tag) { return hfulltag(tag, ""); } static public String hfulltag(String tag, Object contents, Object... params) { return hopeningTag(tag, params) + str(contents) + ""; } static public Set asSet(Object[] array) { HashSet set = new HashSet(); for (Object o : array) if (o != null) set.add(o); return set; } static public Set asSet(String[] array) { TreeSet set = new TreeSet(); for (String o : array) if (o != null) set.add(o); return set; } static public 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 public Set asSet(MultiSet ms) { return ms == null ? null : ms.asSet(); } static public Complex complex(double re, double im) { return new Complex(re, im); } static public Complex complex(double re) { return new Complex(re, 0.0); } static public Complex complex(double[] reIm) { if (empty(reIm)) return null; if (l(reIm) != 2) throw fail("Need 2 doubles to make complex number"); return complex(reIm[0], reIm[1]); } static public int withMargin_defaultWidth = 6; static public JPanel withMargin(Component c) { return withMargin(withMargin_defaultWidth, c); } static public JPanel withMargin(int w, Component c) { return withMargin(w, w, c); } static public JPanel withMargin(int w, int h, Component c) { return withMargin(w, h, w, h, c); } static public JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = marginPanel(); 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 = marginPanel();\r\n p.setBorder(BorderFactory.createEmptyBorder(to..."; } }); } static public ClassLoader classLoaderForObject(Object o) { if (o instanceof ClassLoader) return ((ClassLoader) o); if (o == null) return null; return _getClass(o).getClassLoader(); } static public String classNameToVM(String name) { return name.replace(".", "$"); } static public String[] dropFirst(int n, String[] a) { return drop(n, a); } static public String[] dropFirst(String[] a) { return drop(1, a); } static public Object[] dropFirst(Object[] a) { return drop(1, a); } static public List dropFirst(List l) { return dropFirst(1, l); } static public List dropFirst(int n, Iterable i) { return dropFirst(n, toList(i)); } static public List dropFirst(Iterable i) { return dropFirst(toList(i)); } static public List dropFirst(int n, List l) { return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size())); } static public List dropFirst(List l, int n) { return dropFirst(n, l); } static public String dropFirst(int n, String s) { return substring(s, n); } static public String dropFirst(String s, int n) { return substring(s, n); } static public String dropFirst(String s) { return substring(s, 1); } static public int indexOfNonDigit(String s) { int n = l(s); for (int i = 0; i < n; i++) if (!isDigit(s.charAt(i))) return i; return -1; } static public Throwable getException(Runnable r) { try { callF(r); return null; } catch (Throwable e) { return e; } } static public List sortByCalculatedField(Iterable c, final Object f) { List l = cloneList(c); sort(l, new Comparator() { public int compare(A a, A b) { return stdcompare(callF(f, a), callF(f, b)); } }); return l; } static public int stdcompare(Number a, Number b) { return cmp(a, b); } static public int stdcompare(String a, String b) { return cmp(a, b); } static public int stdcompare(long a, long b) { return a < b ? -1 : a > b ? 1 : 0; } static public int stdcompare(Object a, Object b) { return cmp(a, b); } static public String renderVars_str(Object... params) { List l = new ArrayList(); int i = 0; if (odd(l(params))) { l.add(strOrNull(first(params))); ++i; } for (; i + 1 < l(params); i += 2) l.add(params[i] + "=" + params[i + 1]); return trim(joinWithComma(l)); } static public A[] arrayOfType(Class type, int n) { return makeArray(type, n); } static public A[] arrayOfType(int n, Class type) { return arrayOfType(type, n); } static public boolean swic(String a, String b) { return startsWithIgnoreCase(a, b); } static public 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 public boolean containsNewLines(String s) { return containsNewLine(s); } static public String jlabel_textAsHTML_center(String text) { return "
" + replace(htmlencode2(text), "\n", "
") + "
"; } static public int lCommonPrefix(String a, String b) { int i = 0, n = Math.min(l(a), l(b)); while (i < n && a.charAt(i) == b.charAt(i)) ++i; return i; } static public String joinStrings(String sep, Object... strings) { return joinStrings(sep, Arrays.asList(strings)); } static public String joinStrings(String sep, Iterable strings) { StringBuilder buf = new StringBuilder(); for (Object o : unnull(strings)) { String s = strOrNull(o); if (nempty(s)) { if (nempty(buf)) buf.append(sep); buf.append(s); } } return str(buf); } static public int identityHashCode(Object o) { return System.identityHashCode(o); } static public
A repaint(A c) { if (c != null) c.repaint(); return c; } static public void imageSurface_unpixelated(ImageSurface imageSurface) { if (imageSurface == null) return; imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_BILINEAR; repaint(imageSurface); } static public boolean sameSnippetID(String a, String b) { if (!isSnippetID(a) || !isSnippetID(b)) return false; return parseSnippetID(a) == parseSnippetID(b); } static public BufferedImage copyImage(Image img) { if (img == null) return null; if (img instanceof BufferedImage) return copyImage((BufferedImage) img); int w = img.getWidth(null), h = img.getHeight(null); BufferedImage bi = newBufferedImage(w, h); drawImage(bi, img); return bi; } static public BufferedImage copyImage(BufferedImage bi) { if (bi == null) return null; ColorModel cm = bi.getColorModel(); boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); WritableRaster raster = bi.copyData(bi.getRaster().createCompatibleWritableRaster()); return new BufferedImage(cm, raster, isAlphaPremultiplied, null); } static public boolean isImageFile(File f) { return isImageFileName(fileName(f)) && isFile(f); } static public BufferedImage loadBufferedImageFile(File file) { try { return isFile(file) ? ImageIO.read(file) : null; } catch (Exception __e) { throw rethrow(__e); } } static public String actualUserHome_value; static public String actualUserHome() { if (actualUserHome_value == null) { if (isAndroid()) actualUserHome_value = "/storage/emulated/0/"; else actualUserHome_value = System.getProperty("user.home"); } return actualUserHome_value; } static public File actualUserHome(String sub) { return newFile(new File(actualUserHome()), sub); } static public File userDir() { return new File(userHome()); } static public File userDir(String path) { return new File(userHome(), path); } static public void closeRandomAccessFile(RandomAccessFile f) { if (f != null) try { f.close(); callJavaX("dropIO", f); } catch (Throwable e) { printStackTrace(e); } } static public RandomAccessFile newRandomAccessFile(File path, String mode) { try { boolean forWrite = mode.indexOf('w') >= 0; if (forWrite) mkdirsForFile(path); RandomAccessFile f = new RandomAccessFile(path, mode); callJavaX("registerIO", f, path, forWrite); return f; } catch (Exception __e) { throw rethrow(__e); } } static public boolean deleteFile(File file) { return file != null && file.delete(); } static public String trim(String s) { return s == null ? null : s.trim(); } static public String trim(StringBuilder buf) { return buf.toString().trim(); } static public String trim(StringBuffer buf) { return buf.toString().trim(); } static public CloseableIterableIterator linesFromFile(File f) { return linesFromFile(f, null); } static public CloseableIterableIterator linesFromFile(File f, IResourceHolder resourceHolder) { try { if (!f.exists()) return emptyCloseableIterableIterator(); if (ewic(f.getName(), ".gz")) return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)), resourceHolder); return linesFromReader(utf8bufferedReader(f), resourceHolder); } catch (Exception __e) { throw rethrow(__e); } } static public CloseableIterableIterator linesFromFile(String path) { return linesFromFile(path, null); } static public CloseableIterableIterator linesFromFile(String path, IResourceHolder resourceHolder) { return linesFromFile(newFile(path), resourceHolder); } static public String f2s(File f) { return f == null ? null : f.getAbsolutePath(); } static public String f2s(String s) { return f2s(newFile(s)); } static public String f2s(java.nio.file.Path p) { return p == null ? null : f2s(p.toFile()); } static public void copyStream(InputStream in, OutputStream out) { try { byte[] buf = new byte[65536]; while (true) { int n = in.read(buf); if (n <= 0) return; out.write(buf, 0, n); } } catch (Exception __e) { throw rethrow(__e); } } static public void _registerIO(Object object, String path, boolean opened) { } static public String formatWithThousandsSeparator(long l) { return NumberFormat.getInstance(new Locale("en_US")).format(l); } static public int boolToInt(boolean b) { return b ? 1 : 0; } static public A findConceptWhere(Class c, Object... params) { return findConceptWhere(db_mainConcepts(), c, params); } static public A findConceptWhere(Concepts concepts, Class c, Object... params) { ping(); params = expandParams(c, params); if (concepts.fieldIndices != null) for (int i = 0; i < l(params); i += 2) { IFieldIndex index = concepts.getFieldIndex(c, (String) params[i]); if (index != null) { for (A x : index.getAll(params[i + 1])) if (checkConceptFields(x, params)) return x; return null; } } for (A x : concepts.list(c)) if (checkConceptFields(x, params)) return x; return null; } static public Concept findConceptWhere(Concepts concepts, String c, Object... params) { for (Concept x : concepts.list(c)) if (checkConceptFields(x, params)) return x; return null; } static public AutoCloseable tempLock(Lock lock) { return tempLock("", lock); } static public AutoCloseable tempLock(String purpose, 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 public String singleFieldName(Class c) { Set l = listFields(c); if (l(l) != 1) throw fail("No single field found in " + c + " (have " + n(l(l), "fields") + ")"); return first(l); } static public void warnIfOddCount(Object... list) { if (odd(l(list))) printStackTrace("Odd list size: " + list); } static public List findBackRefs(Collection concepts, Class type) { IdentityHashMap l = new IdentityHashMap(); for (Concept c : concepts) if (c.backRefs != null) for (Concept.Ref r : c.backRefs) if (instanceOf(r.concept(), type)) l.put((A) r.concept(), true); return asList(keys(l)); } static public List findBackRefs(Concept c, Class type) { IdentityHashMap l = new IdentityHashMap(); if (c != null && c.backRefs != null) for (Concept.Ref r : c.backRefs) if (instanceOf(r.concept(), type)) l.put((A) r.concept(), true); return asList(keys(l)); } static public List findBackRefs(Class type, Concept c) { return findBackRefs(c, type); } static public Collection findBackRefs(Concept c) { return findBackRefs(c, Concept.class); } static public boolean checkConceptFieldsIC(Concept x, Object... data) { for (int i = 0; i < l(data); i += 2) if (!eqicOrEq(cget(x, (String) data[i]), deref(data[i + 1]))) return false; return true; } static public Object nuObject(String className, Object... args) { try { return nuObject(classForName(className), args); } catch (Exception __e) { throw rethrow(__e); } } static public A nuObject(Class c, Object... args) { try { if (args == null || args.length == 0) return nuObjectWithoutArguments(c); Constructor m = nuObject_findConstructor(c, args); makeAccessible(m); return (A) m.newInstance(args); } catch (Exception __e) { throw rethrow(__e); } } static public 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 public 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 public HashMap findClass_cache = new HashMap(); static public Class findClass(String name) { synchronized (findClass_cache) { if (findClass_cache.containsKey(name)) return findClass_cache.get(name); if (!isJavaIdentifier(name)) return null; Class c; try { c = Class.forName("main$" + name); } catch (ClassNotFoundException e) { c = null; } findClass_cache.put(name, c); return c; } } static public File getProgramDir() { return programDir(); } static public File getProgramDir(String snippetID) { return programDir(snippetID); } static public int typeConversionScoreWithUnboxing(Class a, Class b) { int score = typeConversionScore(a, b); if (score == 0 || score == 1) return score; Class aPrim = boxedToPrimitiveType(a); if (aPrim != null) { int score2 = typeConversionScore(aPrim, b); if (score2 == 0) return 1; else if (score2 != Integer.MAX_VALUE) return score2; } return score; } static public Object convertPrimitiveIfNecessary(Object o, Class b) { if (b.isPrimitive()) { if (o instanceof Character) { char x = (char) (((Character) o)); if (b == int.class) return Integer.valueOf(x); if (b == long.class) return Long.valueOf(x); if (b == float.class) return Float.valueOf(x); if (b == double.class) return Double.valueOf(x); } else if (o instanceof Number) { if (b == char.class) return Character.valueOf((char) ((Number) o).intValue()); if (b == short.class) return ((Number) o).shortValue(); if (b == int.class) return ((Number) o).intValue(); if (b == long.class) return ((Number) o).longValue(); if (b == float.class) return ((Number) o).floatValue(); } } return o; } static public boolean isSubclassOf(Class a, Class b) { return isSubclass(a, b); } static public _MethodCache getMethodCache(Class c) { return callOpt_getCache(c); } static public boolean isTrueOrYes(Object o) { return isTrueOpt(o) || o instanceof String && (eqicOneOf(((String) o), "1", "t", "true") || isYes(((String) o))); } static public 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 public TreeMap revTreeMap() { return new TreeMap(reverseComparator()); } static public 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 public List replace(A a, A b, List l) { return replace(l, a, b); } static public String replace(String s, String a, String b) { return s == null ? null : a == null || b == null ? s : s.replace(a, b); } static public String replace(String s, char a, char b) { return s == null ? null : s.replace(a, b); } static public int indexOfIC_underscore(String a, String b) { int la = l(a), lb = l(b); if (la < lb) return -1; int n = la - lb; elsewhere: for (int i = 0; i <= n; i++) { for (int j = 0; j < lb; j++) { char c2 = b.charAt(j); if (c2 == '_' || eqic(c2, a.charAt(i + j))) { } else continue elsewhere; } return i; } return -1; } static public List lambdaMap(IF1 f, Iterable l) { return map(l, f); } static public List lambdaMap(IF1 f, A[] l) { return map(l, f); } static public B secondOfPair(Pair p) { return p == null ? null : p.b; } static public F1 toF1(final Object f) { return functionToF1(f); } static public IterableIterator emptyIterableIterator_instance = new IterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; static public IterableIterator emptyIterableIterator() { return emptyIterableIterator_instance; } static public IterableIterator iff(Object f) { return iteratorFromFunction_withEndMarker(f); } static public IterableIterator iff(F0 f) { return iteratorFromFunction_withEndMarker(f); } static public IterableIterator iff(IF0 f) { return iteratorFromFunction_withEndMarker(f); } static public Object endMarker() { return iteratorFromFunction_endMarker; } static public ThreadLocal> holdInstance_l = new ThreadLocal(); static public AutoCloseable holdInstance(Object o) { if (o == null) return null; listThreadLocalAdd(holdInstance_l, o); return new AutoCloseable() { public void close() { listThreadLocalPopLast(holdInstance_l); } }; } static public void messageBox(final String msg) { if (headless()) print(msg); else { swing(() -> { JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE); }); } } static public void messageBox(Throwable e) { printStackTrace(e); messageBox(hideCredentials(innerException2(e))); } static public JMenuItem jMenuItem(final String text) { return jmenuItem(text); } static public JMenuItem jMenuItem(String text, Object r) { return jmenuItem(text, r); } static public 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 public JMenuItem disableMenuItem(final JMenuItem mi) { if (mi != null) { swing(() -> { mi.setEnabled(false); }); } return mi; } static public ActionListener actionListenerInNewThread(final Object runnable) { return actionListenerInNewThread(runnable, null); } static public ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) { if (runnable instanceof ActionListener) return (ActionListener) runnable; return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { startThread("Action Listener", new Runnable() { public void run() { try { AutoCloseable __1 = holdInstance(instanceToHold); try { callF(runnable); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __1 = holdInstance(instanceToHold); try {\r\n callF(runnable..."; } }); } catch (Throwable __e) { messageBox(__e); } } }; } static public JMenuItem directJMenuItem(Action a) { return new JMenuItem(a) { public Dimension getMaximumSize() { return new Dimension(super.getPreferredSize().width, super.getMaximumSize().height); } }; } static public JMenuItem directJMenuItem(String text, Object action) { return directJMenuItem(abstractAction(text, action)); } static public JMenuBar addMenuBar(final Component c) { return swing(new F0() { public JMenuBar get() { try { RootPaneContainer f = getPossiblyInternalFrame(c); if (f == null) return null; JMenuBar bar = (JMenuBar) (call(f, "getJMenuBar")); if (bar == null) { setMenuBar(f, bar = new JMenuBar()); revalidate((Component) f); } return bar; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "RootPaneContainer f = getPossiblyInternalFrame(c);\r\n if (f == null) null;\r..."; } }); } static public boolean zipFileContains_falseOnError(File inZip, String fileName) { try { return zipFileContains(inZip, fileName); } catch (Throwable e) { return false; } } static public File javaHome() { return envJavaHome(); } static public File javaHome(String sub) { return newFile(envJavaHome(), sub); } static public File jigsawModuleFile(String moduleName) { return jigsawModuleFile(moduleName, javaHome()); } static public File jigsawModuleFile(String moduleName, File javaHome) { return new File(javaHome, "jmods/" + moduleName + ".jmod"); } static public List wrapAsList(A[] a) { return wrapArrayAsList(a); } static public IMeta initMetaOfJComponent(JComponent c) { if (c == null) return null; IMeta meta = (IMeta) (c.getClientProperty(IMeta.class)); if (meta == null) c.putClientProperty(IMeta.class, meta = new Meta()); return meta; } static public A optCast(Class c, Object o) { return isInstance(c, o) ? (A) o : null; } static public List synchroList() { return synchroList(new ArrayList()); } static public List synchroList(List l) { return Collections.synchronizedList(l); } static public void assertFalse(Object o) { if (!(eq(o, false))) throw fail(str(o)); } static public boolean assertFalse(boolean b) { if (b) throw fail("oops"); return b; } static public boolean assertFalse(String msg, boolean b) { if (b) throw fail(msg); return b; } static public boolean _inCore() { return false; } static public List hotwire_copyOver_after = synchroList(); static public void hotwire_copyOver(Class c) { 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 public Object[] dropEntryFromParams(Object[] params, int i) { int n = l(params); if (i < 0 || i >= n) return params; if (n == 2) return null; Object[] p = new Object[n - 2]; System.arraycopy(params, 0, p, 0, i); System.arraycopy(params, i + 2, p, i, n - i - 2); return p; } static public boolean checkConceptFields(Concept x, Object... data) { for (int i = 0; i < l(data); i += 2) if (neq(cget(x, (String) data[i]), deref(data[i + 1]))) return false; return true; } static public List filterConcepts(List list, Object... params) { if (empty(params)) return list; List l = new ArrayList(); for (A x : list) if (checkConceptFields(x, params)) l.add(x); return l; } static public int cmpAlphaNum(String a, String b) { return alphaNumComparator().compare(a, b); } static public String roundBracket(String s) { return "(" + s + ")"; } static public String roundBracket(Object s) { return roundBracket(str(s)); } static public A printHidingCredentials(A o) { print(hideCredentials(str(o))); return o; } static public void logQuotedWithDate(String s) { logQuotedWithTime(s); } static public void logQuotedWithDate(String logFile, String s) { logQuotedWithTime(logFile, s); } static public void logQuotedWithDate(File logFile, String s) { logQuotedWithTime(logFile, s); } static public File infoBoxesLogFile() { return new File(javaxDataDir(), "Logs/infoBoxes.txt"); } static public JWindow makeWindow(final Component c) { return swing(new F0() { public JWindow get() { try { JWindow w = new JWindow(); w.add(wrap(c)); return w; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new JWindow w;\r\n w.add(wrap(c));\r\n ret w;"; } }); } static public JPanel infoMessage_makePanel(String text) { final JTextArea ta = wrappedTextArea(text); onClick(ta, new Runnable() { public void run() { try { disposeWindow(ta); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disposeWindow(ta)"; } }); int size = 14; if (l(text) <= 50) size *= 2; else if (l(text) < 100) size = iround(size * 1.5); ta.setFont(typeWriterFont(size)); JScrollPane sp = jscroll(ta); return withMargin(sp); } static public int moveToTopRightCorner_inset = 20; static public A moveToTopRightCorner(A a) { return moveToTopRightCorner(moveToTopRightCorner_inset, moveToTopRightCorner_inset, a); } static public A moveToTopRightCorner(int insetX, int insetY, A a) { { swing(() -> { Window w = getWindow(a); if (w != null) { var bounds = preferredScreenBounds(); w.setLocation(bounds.x2() - w.getWidth() - insetX, bounds.y1() + insetY); } }); } return a; } static public boolean vmBus_noObjections(String msg, Object... args) { return !vmBus_anyFalse(msg, args); } static public A disposeWindowAfter(int delay, final A w) { if (w != null) swingLater(delay, new Runnable() { public void run() { try { w.dispose(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "w.dispose();"; } }); return w; } static public A disposeWindowAfter(A w, double seconds) { return disposeWindowAfter(toMS_int(seconds), w); } static public A disposeWindowAfter(double seconds, A w) { return disposeWindowAfter(w, seconds); } static public List sorted(Collection c, Object comparator) { List l = cloneList(c); sort(l, makeComparator(comparator)); return l; } static public List sorted(Collection c) { List l = cloneList(c); sort(l); return l; } static public List sorted(Comparator comparator, Collection c) { List l = cloneList(c); sort(l, comparator); return l; } static public List methodsStartingWith(Object o, final String prefix) { return filter(allMethodNames(o), new F1() { public Object get(String s) { try { return startsWith(s, prefix); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "startsWith(s, prefix)"; } }); } static volatile public PersistableThrowable _handleException_lastException; static public List _handleException_onException = synchroList(ll((IVF1) (__1 -> printStackTrace2(__1)))); static public boolean _handleException_showThreadCancellations = false; static public 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) { if (_handleException_showThreadCancellations) System.out.println(getStackTrace_noRecord(e2)); return; } for (Object f : cloneList(_handleException_onException)) try { callF(f, e); } catch (Throwable e3) { try { printStackTrace2(e3); } catch (Throwable e4) { System.out.println(getStackTrace(e3)); System.out.println(getStackTrace(e4)); } } } static public boolean interruptThread_verbose = false; static public void interruptThread(Thread t) { if (t == null) return; if (interruptThread_verbose) print("Interrupting thread " + t); vm_threadInterruptionReasonsMap().put(t, getStackTrace()); 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) { printStackTrace(__e); } } } static public boolean isJavaXClassLoader(ClassLoader cl) { return startsWithOneOf(className(cl), "main$JavaXClassLoader", "x30$JavaXClassLoader"); } static public void setOptAll(Object o, Map fields) { if (fields == null) return; for (String field : keys(fields)) setOpt(o, field, fields.get(field)); } static public void setOptAll(Object o, Object... values) { warnIfOddCount(values); for (int i = 0; i + 1 < l(values); i += 2) { String field = (String) values[i]; Object value = values[i + 1]; setOpt(o, field, value); } } static public Object derefRef(Object o) { if (o instanceof Concept.Ref) o = ((Concept.Ref) o).get(); return o; } static public A derefRef(Concept.Ref r) { return r == null ? null : r.get(); } static public int lastIndexOf(String a, String b) { return a == null || b == null ? -1 : a.lastIndexOf(b); } static public int lastIndexOf(String a, char b) { return a == null ? -1 : a.lastIndexOf(b); } static public int lastIndexOf(List l, int i, A a) { if (l == null) return -1; for (i = min(l(l), i) - 1; i >= 0; i--) if (eq(l.get(i), a)) return i; return -1; } static public int lastIndexOf(List l, A a) { if (l == null) return -1; for (int i = l(l) - 1; i >= 0; i--) if (eq(l.get(i), a)) return i; return -1; } static public void lock(Lock lock) { try { ping(); if (lock == null) return; try { vmBus_send("locking", lock, "thread", currentThread()); lock.lockInterruptibly(); vmBus_send("locked", lock, "thread", currentThread()); } catch (InterruptedException e) { Object reason = vm_threadInterruptionReasonsMap().get(currentThread()); print("Locking interrupted! Reason: " + strOr(reason, "Unknown")); printStackTrace(e); rethrow(e); } } catch (Exception __e) { throw rethrow(__e); } } static public void lock(Lock lock, String msg) { print("Locking: " + msg); lock(lock); } static public void lock(Lock lock, String msg, long timeout) { print("Locking: " + msg); lockOrFail(lock, timeout); } static public ReentrantLock lock() { return fairLock(); } static public String getCanonicalPath(File f) { try { return f == null ? null : f.getCanonicalPath(); } catch (Exception __e) { throw rethrow(__e); } } static public String getCanonicalPath(String path) { return getCanonicalPath(newFile(path)); } static public void unlock(Lock lock, String msg) { if (lock == null) return; lock.unlock(); vmBus_send("unlocked", lock, "thread", currentThread()); print("Unlocked: " + msg); } static public void unlock(Lock lock) { if (lock == null) return; lock.unlock(); vmBus_send("unlocked", lock, "thread", currentThread()); } static public AutoCloseable tempCleaningUp() { AutoCloseable result = null; result = tempSetTL(ping_isCleanUpThread, true); return result; } static public void closeAllWriters(Collection l) { for (Writer w : unnull(l)) { try { w.close(); } catch (Throwable __e) { printStackTrace(__e); } } } static public File prepareProgramFile(String name) { return mkdirsForFile(getProgramFile(name)); } static public File prepareProgramFile(String progID, String name) { return mkdirsForFile(getProgramFile(progID, name)); } static public boolean isMenuSeparatorIndicator(Object o) { return eqOneOf(o, "***", "---", "===", ""); } static public int menuItemCount(JMenu menu) { return menu == null ? 0 : swing(() -> menu.getItemCount()); } static public 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 public String unCurlyBracket(String s) { return tok_unCurlyBracket(s); } static public boolean isCurlyBracketed(String s) { return isCurlyBraced(s); } static public void caretToHome(JTextComponent c) { setCaret(c, 0); } static public Font typeWriterFont() { return typeWriterFont(iround(14 * getSwingFontScale())); } static public Font typeWriterFont(int size) { return new Font("Courier", Font.PLAIN, size); } static public JPanel centerAndEast(final Component c, final Component e) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.CENTER, wrap(c)); panel.add(BorderLayout.EAST, wrap(e)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT..."; } }); } static public int withLeftMargin_defaultWidth = 6; static public JPanel withLeftMargin(Component c) { return withLeftMargin(withLeftMargin_defaultWidth, c); } static public JPanel withLeftMargin(final int margin, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createEmptyBorder(0, margin, 0, 0)); 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 public JScrollPane withoutViewportBorder(JScrollPane sp) { if (sp != null) { swing(() -> { sp.setViewportBorder(null); }); } return sp; } static public Dimension getPreferredSize(final Component c) { return c == null ? null : swing(new F0() { public Dimension get() { try { return c.getPreferredSize(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getPreferredSize();"; } }); } static public void setMetaAndVerify(IMeta o, Object key, Object value) { setMeta(o, key, value); assertSame(() -> str(key), value, metaGet(o, key)); } static public void setMetaAndVerify(Object o, Object key, Object value) { setMeta(o, key, value); assertSame(() -> str(key), value, metaGet(o, key)); } static public void setCaretPosition(final JTextComponent c, final int pos) { if (c != null) { swing(() -> { try { int _pos = max(0, min(l(c.getText()), pos)); c.setCaretPosition(_pos); } catch (Throwable __e) { printStackTrace(__e); } }); } } static public Timer installTimer(JComponent component, Object r, long delay) { return installTimer(component, r, delay, delay); } static public Timer installTimer(RootPaneContainer frame, long delay, Object r) { return installTimer(frame.getRootPane(), r, delay, delay); } static public Timer installTimer(JComponent component, long delay, Object r) { return installTimer(component, r, delay, delay); } static public Timer installTimer(JComponent component, long delay, long firstDelay, Object r) { return installTimer(component, r, delay, firstDelay); } static public Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) { return installTimer(component, r, delay, firstDelay, true); } static public Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) { if (component == null) return null; return (Timer) swingAndWait(new F0() { public Object get() { try { final Var timer = new Var(); timer.set(new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { AutoCloseable __1 = tempActivity(r); try { try { if (!allPaused()) if (isFalse(callF(r))) cancelTimer(timer.get()); } catch (Throwable __e) { printStackTrace(__e); } } finally { _close(__1); } } catch (Throwable __e) { messageBox(__e); } } })); timer.get().setInitialDelay(toInt(firstDelay)); timer.get().setRepeats(repeats); bindTimerToComponent(timer.get(), component); return timer.get(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new Var timer;\r\n timer.set(new Timer(toInt(delay), actionList..."; } }); } static public Timer installTimer(RootPaneContainer frame, long delay, long firstDelay, Object r) { return installTimer(frame.getRootPane(), delay, firstDelay, r); } static public JRootPane getRootPane(Component c) { Component f = (Component) getPossiblyInternalFrame(c); return f instanceof RootPaneContainer ? (JRootPane) swingCall(f, "getRootPane") : null; } static public int toInt_checked(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } static public A _recordNewSwingComponent(A c) { if (c != null) callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c); return c; } static public JComponent componentToJComponent(Component c) { if (c instanceof JComponent) return (JComponent) c; if (c instanceof JFrame) return ((JFrame) c).getRootPane(); if (c == null) return null; throw fail("boohoo " + getClassName(c)); } static public class jLiveValueSection_class extends SingleComponentPanel { public LiveValue liveValue; public String getTitle() { return strOrEmpty(liveValue.get()); } public jLiveValueSection_class(LiveValue lv, Component c) { super(c); bindLiveValueListenerToComponent(this, liveValue = lv, new Runnable() { public void run() { try { swingLater(new Runnable() { public void run() { try { setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED), getTitle())); revalidate(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setBorder(BorderFactory.createTitledBorder(\r\n BorderFactory.createBeve..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "swingLater(r {\r\n setBorder(BorderFactory.createTitledBorder(\r\n Bo..."; } }); } } static public JPanel jLiveValueSection(LiveValue lv, Component c) { return swingNu(jLiveValueSection_class.class, lv, c); } static public JButton basicJButton(String text) { return swing(() -> new JButton(text)); } static public A jtransparent(final A a) { { swing(() -> { a.setOpaque(false); }); } return a; } static public JPanel borderLayoutPanel() { return jpanel(new BorderLayout()); } static public boolean isCurrentThread(Thread t) { return t != null && t == currentThread(); } static public JButton jimageButtonScaledToWidth(int w, String imageID, Runnable action) { return jimageButtonScaledToWidth(w, imageID, "", action); } static public JButton jimageButtonScaledToWidth(int w, String imageID, String toolTip, Runnable action) { return jimageButton(scaleImageToWidth(w, imageID), toolTip, action); } static public String errorIconID() { return "#1101390"; } static public JComponent showErrorFrame(Throwable e) { return showText("Error", renderStackTrace((e))); } static public JLabel jlabel_noAutoToolTip() { return jlabel_noAutoToolTip(" "); } static public JLabel jlabel_noAutoToolTip(String text) { var lbl = swingConstruct(BetterLabel.class, text); lbl.autoToolTip = false; return lbl; } static public String exceptionType(Throwable e) { e = getInnerException(e); return shortClassName(e); } static public Set synchroSet() { return synchroHashSet(); } static public Set synchroSet(Set set) { return Collections.synchronizedSet(set); } static public Set newWeakHashSet() { return synchroWeakHashSet(); } static public A getAndClearThreadLocal(ThreadLocal tl) { A a = tl.get(); tl.set(null); return a; } static public void printStackTrace_inPossiblyCancelledThread(Throwable e) { AutoCloseable __1 = tempUncancelThread(); try { System.out.println(getStackTrace_noRecord(e)); } finally { _close(__1); } } static public List beforeDelegatingToThread_operations = synchroList(); static public void beforeDelegatingToThread(Thread t) { for (Object op : cloneList(beforeDelegatingToThread_operations)) pcallF(op, t); } static public void beforeDelegatingToThread_do(Object f) { setAdd(beforeDelegatingToThread_operations, f); } static public Either either2(B b) { return new Either(2, b); } static public Either either1(A a) { return new Either(1, a); } static public List afterDelegatingToThread_operations = synchroList(); static public void afterDelegatingToThread(Thread t) { for (Object op : cloneList(afterDelegatingToThread_operations)) pcallF(op, t); } static public void afterDelegatingToThread_do(Object f) { setAdd(afterDelegatingToThread_operations, f); } static public boolean activateFrame(final Component c, Object... __) { return swing(new F0() { public Boolean get() { try { Frame f = getAWTFrame(c); if (f == null) return false; if (!f.isVisible()) f.setVisible(true); boolean windowsHack = optPar("windowsHack", __, true); boolean iconified = f.getState() == Frame.ICONIFIED; boolean maximize = boolPar("maximize", __); if (iconified) f.setState(maximize ? Frame.MAXIMIZED_BOTH : Frame.NORMAL); if (windowsHack && !iconified && isWindows()) { boolean fullscreen = f.getExtendedState() == Frame.MAXIMIZED_BOTH; f.setExtendedState(JFrame.ICONIFIED); f.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL); } f.toFront(); return true; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Frame f = getAWTFrame(c);\r\n if (f == null) false;\r\n if (!f.isVisible())..."; } }); } static public Frame getAWTFrame(final Object _o) { return swing(new F0() { public Frame 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 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 public A withTypeWriterFont(A c) { return setFont(c, typeWriterFont()); } static public JTextArea jTextArea() { return jTextArea(""); } static public JTextArea jTextArea(final String text) { return jTextAreaWithUndo(text); } static public String programTitle() { return getProgramName(); } static public JFrame getFrame(final Object _o) { return swing(new F0() { public JFrame get() { try { Object o = _o; if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof JFrame) return (JFrame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; } }); } static public JFrame setFrameIconLater(Component c, final String imageID) { final JFrame frame = getFrame(c); if (frame != null) startThread("Loading Icon", new Runnable() { public void run() { try { final Image i = imageIcon(or2(imageID, "#1005557")).getImage(); swingLater(new Runnable() { public void run() { try { frame.setIconImage(i); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setIconImage(i);"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n swingL..."; } }); return frame; } static public void _initFrame(JFrame f) { myFrames_list.put(f, Boolean.TRUE); standardTitlePopupMenu(f); } static public Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400); static public Rectangle defaultNewFrameBounds() { return swing(new F0() { public Rectangle get() { try { defaultNewFrameBounds_r.translate(60, 20); var bounds = preferredScreenBounds(); if (!bounds.contains(defaultNewFrameBounds_r)) defaultNewFrameBounds_r.setLocation(centerX(bounds) + random_incl(-30, 30), centerY(bounds) + random_incl(-20, 20)); return new Rectangle(defaultNewFrameBounds_r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "defaultNewFrameBounds_r.translate(60, 20);\r\n var bounds = preferredScreenB..."; } }); } static public void hideConsole() { final JFrame frame = consoleFrame(); if (frame != null) { autoVMExit(); swingLater(new Runnable() { public void run() { try { frame.setVisible(false); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setVisible(false);"; } }); } } static public String getProgramTitle() { return getProgramName(); } static public TreeMap asCaseInsensitiveMap(Map map) { if (isCIMap(map)) return (TreeMap) map; TreeMap m = ciMap(); putAll(m, map); return m; } static public List countIteratorToList(int b) { return countIteratorToList(0, b); } static public List countIteratorToList(int a, int b) { return asList(countIterator(a, b)); } static public List countIteratorToList(int b, IF1 f) { return countIteratorToList(0, b, f); } static public List countIteratorToList(int a, int b, IF1 f) { return asList(countIterator(a, b, f)); } static public List countIteratorToList(int a, int b, int step) { return asList(countIterator(a, b, step)); } static public List countIteratorToList(double a, double b, double step, IF1 f) { return asList(countIterator(a, b, step, f)); } static public List countIteratorToList(double a, double b, double step) { return asList(countIterator(a, b, step)); } static public List countIteratorToList(IF1 f, double a, double b, double step) { return asList(countIterator(f, a, b, step)); } static public List countIteratorToList(IF1 f, int b) { return countIteratorToList(f, 0, b); } static public List countIteratorToList(IF1 f, int a, int b) { return asList(countIterator(f, a, b)); } static public List withoutNulls(Iterable l) { if (l instanceof List) if (!containsNulls((List) l)) return ((List) l); List l2 = new ArrayList(); for (A a : l) if (a != null) l2.add(a); return l2; } static public Map withoutNulls(Map map) { Map map2 = similarEmptyMap(map); for (A a : keys(map)) if (a != null) { B b = map.get(a); if (b != null) map2.put(a, b); } return map2; } static public List withoutNulls(A[] l) { List l2 = new ArrayList(); if (l != null) for (A a : l) if (a != null) l2.add(a); return l2; } static public IterableIterator countIterator_exclusive(int b) { return countIterator_exclusive(0, b); } static public IterableIterator countIterator_exclusive(int a, int b) { return new IterableIterator() { public int i = a; public boolean hasNext() { return i < b; } public Integer next() { return i++; } }; } static public IterableIterator countIterator_exclusive(int b, IF1 f) { return countIterator_exclusive(0, b, f); } static public IterableIterator countIterator_exclusive(int a, int b, IF1 f) { return mapI_if1(f, countIterator_exclusive(a, b)); } static public IterableIterator countIterator_exclusive_step(final int a, final int b, final int step) { assertTrue("step > 0", step > 0); return new IterableIterator() { public int i = a; public boolean hasNext() { return i < b; } public Integer next() { var j = i; i += step; return j; } }; } static public IterableIterator countIterator_exclusive_step(double a, double b, double step) { assertTrue("step > 0", step > 0); return new IterableIterator() { public double i = a; public boolean hasNext() { return i < b; } public Double next() { var j = i; i += step; return j; } }; } static public IterableIterator countIterator_exclusive_step(double a, double b, double step, IF1 f) { return mapI_if1(f, countIterator_exclusive_step(a, b, step)); } static public Rect screenBounds(GraphicsDevice screen) { return screen == null ? null : toRect(screen.getDefaultConfiguration().getBounds()); } static public Rect screenBounds(int iScreen) { return screenBounds(get(screenDevices(), iScreen)); } static public int screenCount() { return l(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()); } static public Rect boundsAsRect(Component c) { return boundsRect(c); } static public int indexOfMax(List l, IF1 f) { Best_comparable best = new Best_comparable(); for (int i = 0; i < l(l); i++) best.put(i, f.get(l.get(i))); return or(best.get(), -1); } static public List allScreenBounds() { return map(__64 -> screenBounds(__64), screenDevices()); } static public int area(Rect r) { return rectArea(r); } static public double area(DoubleRect r) { return r == null ? 0 : r.w * r.h; } static public Rect intersectRects(Rect a, Rect b) { int x = max(a.x, b.x), y = max(a.y, b.y); int x2 = min(a.x + a.w, b.x + b.w), y2 = min(a.y + a.h, b.y + b.h); return new Rect(x, y, x2 - x, y2 - y); } static public Rect intersectRects(Rect a, int x1, int y1, int w, int h) { if (a == null || a.x >= x1 && a.y >= y1 && a.x2() < x1 + w && a.y2() < y1 + h) return a; return rectFromPoints(max(a.x, x1), max(a.y, y1), min(a.x2(), x1 + w), min(a.y2(), y1 + h)); } static public TimeZone localTimeZone() { return getTimeZone(standardTimeZone()); } static public MouseAdapter leftClickMouseAdapter(final Object r) { return new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getButton() == 1) pcallF(r, new Pt(e.getPoint())); } }; } static public MouseAdapter leftClickMouseAdapter_noPt(final Object r) { return new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getButton() == 1) pcallF(r); } }; } static public int imageIcon_cacheSize = 10; static public boolean imageIcon_verbose = false; static public Map imageIcon_cache; static public Lock imageIcon_lock = lock(); static public ThreadLocal imageIcon_fixGIF = new ThreadLocal(); static public ImageIcon imageIcon(String imageID) { try { if (imageID == null) return null; Lock __0 = imageIcon_lock; lock(__0); try { if (imageIcon_cache == null) imageIcon_cache = new MRUCache(imageIcon_cacheSize); imageID = fsI(imageID); ImageIcon ii = imageIcon_cache.get(imageID); if (ii == null) { if (imageIcon_verbose) print("Loading image icon: " + imageID); File f = loadBinarySnippet(imageID); Boolean b = imageIcon_fixGIF.get(); if (!isFalse(b)) ii = new ImageIcon(loadBufferedImageFixingGIFs(f)); else ii = new ImageIcon(f.toURI().toURL()); } else imageIcon_cache.remove(imageID); imageIcon_cache.put(imageID, ii); return ii; } finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } } static public ImageIcon imageIcon(File f) { try { return new ImageIcon(f.toURI().toURL()); } catch (Exception __e) { throw rethrow(__e); } } static public ImageIcon imageIcon(Image img) { return img == null ? null : new ImageIcon(img); } static public ImageIcon imageIcon(RGBImage img) { return imageIcon(img.getBufferedImage()); } static public boolean charactersEqualIC(char c1, char c2) { if (c1 == c2) return true; char u1 = Character.toUpperCase(c1); char u2 = Character.toUpperCase(c2); if (u1 == u2) return true; return Character.toLowerCase(u1) == Character.toLowerCase(u2); } static public JPanel centerAndNorth(final Component c, final Component n) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.CENTER, wrap(c)); panel.add(BorderLayout.NORTH, wrap(n)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT..."; } }); } static public A bindJLabelToLiveValue(final A label, final LiveValue lv) { bindLiveValueListenerToComponent(label, lv, new Runnable() { public void run() { try { setText(label, strOrNull(lv.get())); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setText(label, strOrNull(lv!))"; } }); return label; } static public A bindJLabelToVar(A label, IVarWithNotify var) { bindListenerToComponent(label, var, () -> { try { setText(label, strOrNull(var.get())); } catch (Throwable e) { printStackTrace(e); setText(label, "Error"); } }); return label; } static public List childrenOfType(Component c, Class theClass) { List l = new ArrayList(); scanForComponents(c, theClass, l); return l; } static public List childrenOfType(Class theClass, Component c) { return childrenOfType(c, theClass); } static public void onFirstResize(final Component c, final Object r) { if (c != null && r != null) { swing(() -> { c.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { c.removeComponentListener(this); pcallF(r); } }); }); } } static public void awtLater(int delay, final Object r) { swingLater(delay, r); } static public void awtLater(int delay, Runnable r) { swingLater(delay, r); } static public void awtLater(Object r) { swingLater(r); } static public void awtLater(double delaySeconds, Runnable r) { swingLater(toMS(delaySeconds), r); } static public void awtLater(JComponent component, int delay, Object r) { installTimer(component, r, delay, delay, false); } static public void awtLater(JFrame frame, int delay, Object r) { awtLater(frame.getRootPane(), delay, r); } static public void clickButton(final JButton b) { if (b != null) { swing(() -> { if (b.isEnabled()) b.doClick(); }); } } static public KeyListener enterKeyListener(final Object action) { return new KeyAdapter() { public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_ENTER) pcallF(action); } }; } static public 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 public AbstractAction abstractAction(String name, final Object runnable) { return new AbstractAction(name) { public void actionPerformed(ActionEvent evt) { pcallF(runnable); } }; } static public String selectedItem(JList l) { return getSelectedItem(l); } static public String selectedItem(JComboBox cb) { return getSelectedItem(cb); } static public Map weakHashMap() { return newWeakHashMap(); } static public Set emptySet() { return new HashSet(); } static public TreeSet asTreeSet(Collection set) { return set == null ? null : set instanceof TreeSet ? (TreeSet) set : new TreeSet(set); } static public class getOpt_Map extends WeakHashMap { public getOpt_Map() { if (getOpt_special == null) getOpt_special = new HashMap(); clear(); } public void clear() { super.clear(); put(Class.class, getOpt_special); put(String.class, getOpt_special); } } static final public Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map())); static public HashMap getOpt_special; static public Map getOpt_getFieldMap(Object o) { Class c = _getClass(o); HashMap map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); return map; } static public Object getOpt_cached(Object o, String field) { try { if (o == null) return null; Map map = getOpt_getFieldMap(o); if (map == getOpt_special) { if (o instanceof Class) return getOpt((Class) o, field); if (o instanceof Map) return ((Map) o).get(field); } Field f = map.get(field); if (f != null) return f.get(o); if (o instanceof DynamicObject) return syncMapGet2(((DynamicObject) o).fieldValues, field); return null; } catch (Exception __e) { throw rethrow(__e); } } static public HashMap getOpt_makeCache(Class c) { HashMap map; if (isSubtypeOf(c, Map.class)) map = getOpt_special; else { map = new HashMap(); if (!reflection_classesNotToScan().contains(c.getName())) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) { makeAccessible(f); String name = f.getName(); if (!map.containsKey(name)) map.put(name, f); } _c = _c.getSuperclass(); } while (_c != null); } } if (getOpt_cache != null) getOpt_cache.put(c, map); return map; } static public int hashCode(Object a) { return a == null ? 0 : a.hashCode(); } static public int hashCode(long l) { return Long.hashCode(l); } static public A addMargin(final int top, final int left, final int bottom, final int right, final A c) { if (c != null) { swing(() -> { Border margin = BorderFactory.createEmptyBorder(top, left, bottom, right); c.setBorder(jCompoundBorder(c.getBorder(), margin)); }); } return c; } static public A addMargin(int w, A c) { return addMargin(w, w, w, w, c); } static public Component wrapForSmartAdd(Object o) { if (o == null) return jpanel(); if (o instanceof String) return jlabel((String) o); return wrap(o); } static public 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 public List newSubList(List l, int startIndex, int endIndex) { return cloneList(subList(l, startIndex, endIndex)); } static public List newSubList(List l, int startIndex) { return cloneList(subList(l, startIndex)); } static public JTextArea enableWordWrapForTextArea(JTextArea ta) { return enableWordWrapForTextArea(ta, true); } static public JTextArea enableWordWrapForTextArea(JTextArea ta, boolean enabled) { if (ta != null) { swing(() -> { ta.setLineWrap(enabled); ta.setWrapStyleWord(true); }); } return ta; } static public JTextArea jtextarea() { return jTextArea(); } static public JTextArea jtextarea(String text) { return jTextArea(text); } static public long sysNow() { ping(); return System.nanoTime() / 1000000; } static public String hopeningTag(String tag, Map params) { return hopeningTag(tag, mapToParams(params)); } static public String hopeningTag(String tag, Object... params) { StringBuilder buf = new StringBuilder(); buf.append("<" + tag); params = unrollParams(params); for (int i = 0; i < l(params); i += 2) { String name = (String) get(params, i); Object val = get(params, i + 1); if (nempty(name) && val != null) { if (eqOneOf(val, html_valueLessParam(), true)) buf.append(" " + name); else { String s = str(val); if (!empty(s)) buf.append(" " + name + "=" + htmlQuote(s)); } } } buf.append(">"); return str(buf); } static public Object iteratorFromFunction_endMarker = new Object(); static public IterableIterator iteratorFromFunction_withEndMarker(final Object f) { class IFF extends IterableIterator { public A a; public boolean have, done; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; have = false; return _a; } public void getNext() { if (done || have) return; Object o = callF(f); if (o == iteratorFromFunction_endMarker) { done = true; return; } a = (A) o; have = true; } } ; return new IFF(); } static public IterableIterator iteratorFromFunction_withEndMarker(final F0 f) { return iteratorFromFunction_withEndMarker_f0(f); } static public Map myFrames_list = weakHashMap(); static public List myFrames() { return swing(new F0>() { public List get() { try { return keysList(myFrames_list); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return keysList(myFrames_list);"; } }); } static public String[] drop(int n, String[] a) { n = Math.min(n, a.length); String[] b = new String[a.length - n]; System.arraycopy(a, n, b, 0, b.length); return b; } static public Object[] drop(int n, Object[] a) { n = Math.min(n, a.length); Object[] b = new Object[a.length - n]; System.arraycopy(a, n, b, 0, b.length); return b; } static public ArrayList toList(A[] a) { return asList(a); } static public ArrayList toList(int[] a) { return asList(a); } static public ArrayList toList(Set s) { return asList(s); } static public ArrayList toList(Iterable s) { return asList(s); } static public A[] makeArray(Class type, int n) { return (A[]) Array.newInstance(type, n); } static public boolean startsWithIgnoreCase(String a, String b) { return regionMatchesIC(a, 0, b, 0, b.length()); } static public String htmlencode2(String s) { return htmlencode_noQuotes(s); } static public BufferedImage newBufferedImage(int w, int h) { return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); } static public BufferedImage newBufferedImage(int w, int h, RGB rgb) { return newBufferedImage(w, h, rgb.getColor()); } static public BufferedImage newBufferedImage(int w, int h, Color color) { BufferedImage img = newBufferedImage(w, h); Graphics2D g = img.createGraphics(); g.setColor(or(color, Color.white)); g.fillRect(0, 0, w, h); return img; } static public BufferedImage newBufferedImage(Pt p, Color color) { return newBufferedImage(p.x, p.y, color); } static public BufferedImage newBufferedImage(int w, int h, int[] pixels) { return intArrayToBufferedImage(pixels, w, h); } static public BufferedImage drawImage(BufferedImage canvas, Image img, Pt p) { return drawImageOnImage(img, canvas, p.x, p.y); } static public void drawImage(BufferedImage g, Image img) { drawImage(graphics(g), img); } static public void drawImage(Graphics2D g, Image img) { drawImage(g, img, 0, 0); } static public void drawImage(Graphics2D g, Image img, Pt p) { drawImage(g, img, p.x, p.y); } static public void drawImage(Graphics2D g, Image img, int x, int y) { { if (g != null) g.drawImage(img, x, y, null); } } static public boolean isImageFileName(String s) { return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif"); } static public Object callJavaX(String method, Object... args) { return callOpt(getJavaX(), method, args); } static public CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; static public CloseableIterableIterator emptyCloseableIterableIterator() { return emptyCloseableIterableIterator_instance; } static public CloseableIterableIterator linesFromReader(Reader r) { return linesFromReader(r, null); } static public CloseableIterableIterator linesFromReader(Reader r, IResourceHolder resourceHolder) { final BufferedReader br = bufferedReader(r); return holdResource(resourceHolder, iteratorFromFunction_f0_autoCloseable(new F0() { public String get() { try { return readLineFromReaderWithClose(br); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return readLineFromReaderWithClose(br);"; } }, _wrapIOCloseable(r))); } static public BufferedReader utf8bufferedReader(InputStream in) { try { return in == null ? null : bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in)); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedReader utf8bufferedReader(File f) { try { return utf8bufferedReader(newFileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } static public GZIPInputStream newGZIPInputStream(File f) { return gzInputStream(f); } static public GZIPInputStream newGZIPInputStream(InputStream in) { return gzInputStream(in); } static public Set listFields(Object c) { TreeSet fields = new TreeSet(); for (Field f : _getClass(c).getDeclaredFields()) fields.add(f.getName()); return fields; } static public String n(long l, String name) { return l + " " + trim(l == 1 ? singular(name) : getPlural(name)); } static public String n(Collection l, String name) { return n(l(l), name); } static public String n(Map m, String name) { return n(l(m), name); } static public String n(Object[] a, String name) { return n(l(a), name); } static public String n(MultiSet ms, String name) { return n(l(ms), name); } static public 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 public boolean instanceOf(Object o, Class c) { if (c == null) return false; return c.isInstance(o); } static public boolean instanceOf(Class c, Object o) { return instanceOf(o, c); } static public boolean eqicOrEq(Object a, Object b) { return a instanceof String && b instanceof String ? eqic((String) a, (String) b) : eq(a, b); } static public Object deref(Object o) { if (o instanceof IRef) return ((IRef) o).get(); return o; } static public Map classForName_cache = synchroHashMap(); static public Class classForName(String name) { return classForName(name, null); } static public Class classForName(String name, Object classFinder) { if (classForName_cache == null || classFinder != null) return classForName_uncached(name, classFinder); Class c = classForName_cache.get(name); if (c == null) classForName_cache.put(name, c = classForName_uncached(name, null)); return c; } static public Class classForName_uncached(String name, Object classFinder) { try { if (classFinder != null) return (Class) callF(classFinder, name); return Class.forName(name); } catch (Exception __e) { throw rethrow(__e); } } static public Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap(); static public Object nuObjectWithoutArguments(String className) { try { return nuObjectWithoutArguments(classForName(className)); } catch (Exception __e) { throw rethrow(__e); } } static public A nuObjectWithoutArguments(Class c) { try { if (nuObjectWithoutArguments_cache == null) 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 public Constructor nuObjectWithoutArguments_findConstructor(Class c) { for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) { makeAccessible(m); return m; } throw fail("No default constructor found in " + c.getName()); } static public List getClasses(Object[] array) { List l = emptyList(l(array)); for (Object o : array) l.add(_getClass(o)); return l; } static public int typeConversionScore(Class a, Class b) { if (a == b) return 0; if (b.isPrimitive()) { if (a.isPrimitive()) { if (b == boolean.class) return Integer.MAX_VALUE; if (b == byte.class) return Integer.MAX_VALUE; if (b == char.class) return a == byte.class ? -2 : Integer.MAX_VALUE; if (b == short.class) return a == byte.class ? -2 : Integer.MAX_VALUE; if (b == int.class) return a == byte.class || a == char.class || a == short.class ? -2 : Integer.MAX_VALUE; if (b == long.class) return a == byte.class || a == char.class || a == short.class || a == int.class ? -2 : Integer.MAX_VALUE; if (b == float.class) return a == byte.class || a == char.class || a == short.class || a == int.class ? -2 : Integer.MAX_VALUE; return a != boolean.class ? -2 : Integer.MAX_VALUE; } else { return primitiveToBoxedType(b) == a ? 1 : Integer.MAX_VALUE; } } else { if (a.isPrimitive()) return primitiveToBoxedType(a) == b ? 1 : Integer.MAX_VALUE; return b.isAssignableFrom(a) ? 1 : Integer.MAX_VALUE; } } static public Class boxedToPrimitiveType(Class type) { if (type == Boolean.class) return boolean.class; if (type == Integer.class) return int.class; if (type == Long.class) return long.class; if (type == Float.class) return float.class; if (type == Short.class) return short.class; if (type == Character.class) return char.class; if (type == Byte.class) return byte.class; if (type == Double.class) return double.class; return null; } static public boolean isSubclass(Class a, Class b) { return a != null && b != null && b.isAssignableFrom(a); } static public boolean isTrueOpt(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); return false; } static public boolean isTrueOpt(String field, Object o) { return isTrueOpt(getOpt(field, o)); } static public boolean eqicOneOf(String s, String... l) { for (String x : l) if (eqic(s, x)) return true; return false; } static public List isYes_yesses = litlist("y", "yes", "yeah", "y", "yup", "yo", "corect", "sure", "ok", "afirmative"); static public boolean isYes(String s) { return isYes_yesses.contains(collapseWord(toLowerCase(firstWord2(s)))); } static public Comparator reverseComparator(Comparator c) { return (a, b) -> c.compare(b, a); } static public Comparator reverseComparator() { return (a, b) -> cmp(b, a); } static public F1 functionToF1(final Object f) { if (isString(f)) return mainFunctionToF1((String) f); if (f instanceof F1) return (F1) f; return new F1() { public Object get(Object a) { try { return callF(f, a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret callF(f, a);"; } }; } static public void listThreadLocalAdd(ThreadLocal> tl, A a) { List l = tl.get(); if (l == null) tl.set(l = new ArrayList()); l.add(a); } static public 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 public boolean headless() { return isHeadless(); } static public Throwable innerException2(Throwable e) { if (e == null) return null; while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause(); return e; } static public boolean isLetterOrDigit(char c) { return Character.isLetterOrDigit(c); } static public RootPaneContainer getPossiblyInternalFrame(Component c) { JInternalFrame f = getInternalFrame(c); if (f != null) return f; return optCast(RootPaneContainer.class, getWindow(c)); } static public void setMenuBar(final JMenuBar mb, final RootPaneContainer f) { { swing(() -> { call(f, "setJMenuBar", mb); revalidate((Component) f); }); } } static public void setMenuBar(RootPaneContainer f, JMenuBar mb) { setMenuBar(mb, f); } static public boolean zipFileContains(File inZip, String fileName) { try { ZipFile zip = new ZipFile(inZip); try { return zipFileContains(zip, fileName); } finally { zip.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public boolean zipFileContains(ZipFile zip, String fileName) { try { return zip.getEntry(fileName) != null; } catch (Exception __e) { throw rethrow(__e); } } static public File envJavaHome() { return newFile(System.getProperty("java.home")); } static public List wrapArrayAsList(A[] a) { return a == null ? null : Arrays.asList(a); } static public boolean isInstance(Class type, Object arg) { return type.isInstance(arg); } static public void setOptIfNotNull(Object o, String field, Object value) { if (value != null) setOpt(o, field, value); } static public Object mainBot; static public Object getMainBot() { return mainBot; } static public AlphanumComparator alphaNumComparator_instance; static public Comparator alphaNumComparator() { if (alphaNumComparator_instance == null) alphaNumComparator_instance = new AlphanumComparator(); return alphaNumComparator_instance; } static public void logQuotedWithTime(String s) { logQuotedWithTime(standardLogFile(), s); } static public void logQuotedWithTime(File logFile, String s) { logQuoted(logFile, logQuotedWithTime_format(s)); } static public void logQuotedWithTime(String logFile, String s) { logQuoted(logFile, logQuotedWithTime_format(s)); } static public String logQuotedWithTime_format(String s) { return (now()) + " " + s; } static public A onClick(final A c, final Object runnable) { if (c != null) { swing(() -> { c.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { callF(runnable, e); } }); }); } return c; } static public void onClick(JButton btn, final Object runnable) { onEnter(btn, runnable); } static public void disposeWindow(final Window window) { if (window != null) { swing(() -> { window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); myFrames_list.remove(window); window.dispose(); }); } } static public void disposeWindow(final Component c) { disposeWindow(getWindow(c)); } static public void disposeWindow(Object o) { if (o != null) disposeWindow(((Component) o)); } static public void disposeWindow() { disposeWindow(heldInstance(Component.class)); } static public Rect preferredScreenBounds() { return screenBounds_safe(preferredScreen()); } static public boolean vmBus_anyFalse(String msg, Object... args) { return contains(vmBus_queryAll(msg, args), false); } static public void swingLater(long delay, final Object r) { javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r))); timer.setRepeats(false); timer.start(); } static public void swingLater(Object r) { SwingUtilities.invokeLater(toRunnable(r)); } static public Comparator makeComparator(final Object f) { if (f instanceof Comparator) return (Comparator) f; return new Comparator() { public int compare(Object a, Object b) { return (Integer) callF(f, a, b); } }; } static public Throwable printStackTrace2(Throwable e) { print(getStackTrace2(e)); return e; } static public void printStackTrace2() { printStackTrace2(new Throwable()); } static public void printStackTrace2(String msg) { printStackTrace2(new Throwable(msg)); } static public Throwable innerException(Throwable e) { return getInnerException(e); } static public Map vm_threadInterruptionReasonsMap() { return vm_generalWeakSubMap("Thread interruption reasons"); } static public Map vm_generalSubMap(Object name) { synchronized (vm_generalMap()) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = synchroMap()); return map; } } static public String strOr(Object o, String ifNull) { return o == null ? ifNull : str(o); } static public void lockOrFail(Lock lock, long timeout) { try { ping(); vmBus_send("locking", lock, "thread", currentThread()); 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); } vmBus_send("locked", lock, "thread", currentThread()); ping(); } catch (Exception __e) { throw rethrow(__e); } } static public ReentrantLock fairLock() { return new ReentrantLock(true); } static public AutoCloseable tempSetTL(ThreadLocal tl, A a) { return tempSetThreadLocal(tl, a); } static public boolean hasMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args) != null; } static public String tok_unCurlyBracket(String s) { return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s; } static public boolean isCurlyBraced(String s) { List tok = tok_combineCurlyBrackets_keep(javaTok(s)); return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}"); } static public void setCaret(final JTextComponent c, final int pos) { if (c != null) { swing(() -> { c.setCaretPosition(pos); }); } } static public float getSwingFontScale() { return or((Float) vm_generalMap_get("swingFontScale_value"), 1f); } static public void setMeta(IMeta o, Object key, Object value) { metaMapPut(o, key, value); } static public void setMeta(Object o, Object key, Object value) { metaMapPut(o, key, value); } static public AutoCloseable tempActivity(Object r) { return null; } static public boolean allPaused() { return ping_pauseAll; } static public void cancelTimer(javax.swing.Timer timer) { if (timer != null) timer.stop(); } static public void cancelTimer(java.util.Timer timer) { if (timer != null) timer.cancel(); } static public 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) { printStackTrace(__e); } } } static public void bindTimerToComponent(final Timer timer, JFrame f) { bindTimerToComponent(timer, f.getRootPane()); } static public 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 public String strOrEmpty(Object o) { return o == null ? "" : str(o); } static public JButton jimageButton(String imageID, Object action) { JButton btn = jbutton("", action); btn.setIcon(imageIcon(imageID)); return btn; } static public JButton jimageButton(String imageID) { return jimageButton(imageID, null); } static public JButton jimageButton(Image img) { return jimageButton(img, null, null); } static public JButton jimageButton(String imageID, String toolTip, Runnable action) { return jimageButton(imageIcon(imageID), toolTip, action); } static public JButton jimageButton(Image img, String toolTip, Runnable action) { var btn = jbutton("", action); setButtonImage(btn, img); return setToolTip(toolTip, btn); } static public JButton jimageButton(ImageIcon img, String toolTip, Runnable action) { var btn = jbutton("", action); setButtonImage(btn, img); return setToolTip(toolTip, btn); } static public BufferedImage scaleImageToWidth(BufferedImage img, int newW) { return resizeImage(img, newW); } static public BufferedImage scaleImageToWidth(int newW, BufferedImage img) { return scaleImageToWidth(img, newW); } static public BufferedImage scaleImageToWidth(int newW, String imageID) { return scaleImageToWidth(newW, loadImage2(imageID)); } static public String renderStackTrace(StackTraceElement[] st) { return stackTraceToString(st); } static public String renderStackTrace(Throwable e) { return stackTraceToString(e); } static public String renderStackTrace(String msg) { return renderStackTrace(new Throwable(msg)); } static public Set synchroHashSet() { return synchronizedSet(new HashSet()); } static public Set synchroWeakHashSet() { return Collections.newSetFromMap((Map) newWeakHashMap()); } static public AutoCloseable tempUncancelThread() { return tempRemove(ping_actions, Thread.currentThread()); } static public boolean setAdd(Collection c, A a) { if (c == null || c.contains(a)) return false; c.add(a); return true; } static public boolean boolPar(ThreadLocal tl) { return boolOptParam(tl); } static public boolean boolPar(Object[] __, String name) { return boolOptParam(__, name); } static public boolean boolPar(String name, Object[] __) { return boolOptParam(__, name); } static public boolean boolPar(String name, Map __) { return boolOptParam(name, __); } static public boolean boolPar(String name, Object[] params, boolean defaultValue) { return optParam(params, name, defaultValue); } public static boolean isWindows() { return System.getProperty("os.name").contains("Windows"); } static public List buttonsInGroup(ButtonGroup g) { if (g == null) return ll(); return asList(g.getElements()); } static public A setFont(final Font font, final A a) { if (a != null) { swing(() -> { a.setFont(font); }); } return a; } static public A setFont(A a, Font font) { return setFont(font, a); } static public A setFont(final String fontID, float fontSize, final A a) { return setFont(loadFont_cached(fontID, fontSize), a); } static public JTextArea jTextAreaWithUndo() { return jTextAreaWithUndo(""); } static public JTextArea jTextAreaWithUndo(final String text) { return jenableUndoRedo(swingNu(JTextArea.class, text)); } static public String getProgramName_cache; static public String getProgramName() { Lock __0 = downloadLock(); lock(__0); try { if (getProgramName_cache == null) getProgramName_cache = getSnippetTitleOpt(programID()); return getProgramName_cache; } finally { unlock(__0); } } static public void _onLoad_getProgramName() { { startThread(new Runnable() { public void run() { try { getProgramName(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getProgramName();"; } }); } } static public void standardTitlePopupMenu(final JFrame frame) { if (!isSubstanceLAF()) return; titlePopupMenu(frame, new VF1() { public void get(JPopupMenu menu) { try { boolean alwaysOnTop = frame.isAlwaysOnTop(); menu.add(jmenuItem("Restart Program", new Runnable() { public void run() { try { restart(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "restart();"; } })); menu.add(jmenuItem("Duplicate Program", new Runnable() { public void run() { try { duplicateThisProgram(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "duplicateThisProgram();"; } })); menu.add(jmenuItem("Show Console", new Runnable() { public void run() { try { showConsole(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showConsole();"; } })); menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() { public void run() { try { toggleAlwaysOnTop(frame); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "toggleAlwaysOnTop(frame)"; } })); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n ifndef standardTitlePopupMenu_..."; } }); } static public Integer centerX(Rect r) { return rectCenterX(r); } static public int random_incl(int min, int max) { return random_incl(min, max, defaultRandomizer()); } static public int random_incl(int min, int max, Random random) { return random(min, max + 1, random); } static public int random_incl(int max) { return random(0, max + 1); } static public Integer centerY(Rect r) { return rectCenterY(r); } static public JFrame consoleFrame() { return (JFrame) getOpt(get(getJavaX(), "console"), "frame"); } static public void autoVMExit() { call(getJavaX(), "autoVMExit"); } static public boolean isCIMap(Map m) { return m instanceof TreeMap && ((TreeMap) m).comparator() == caseInsensitiveComparator(); } static public TreeMap ciMap() { return caseInsensitiveMap(); } static public boolean containsNulls(Collection c) { return contains(c, null); } static public Map similarEmptyMap(Map m) { if (m instanceof TreeMap) return new TreeMap(((TreeMap) m).comparator()); if (m instanceof LinkedHashMap) return new LinkedHashMap(); return new HashMap(); } static public Map similarEmptyMap(Iterable m) { if (m instanceof TreeSet) return new TreeMap(((TreeSet) m).comparator()); if (m instanceof LinkedHashSet) return new LinkedHashMap(); return new HashMap(); } static public class mapI_if1_It extends IterableIterator { public IF1 f; public Iterator i; public mapI_if1_It() { } public mapI_if1_It(IF1 f, Iterator i) { this.i = i; this.f = f; } public boolean hasNext() { return i.hasNext(); } public B next() { return f.get(i.next()); } public String toString() { return formatFunctionCall("mapI_if1", f, i); } } static public IterableIterator mapI_if1(IF1 f, Iterable i) { return new mapI_if1_It(f, i.iterator()); } static public IterableIterator mapI_if1(Iterable i, IF1 f) { return mapI_if1(f, i); } static public List screenDevices() { return asList(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()); } static public Rect boundsRect(Component c) { return toRect(getBounds(c)); } static public int rectArea(Rect r) { return r == null ? 0 : r.w * r.h; } static public Rect rectFromPoints(int x1, int y1, int x2, int y2) { return pointsRect(x1, y1, x2, y2); } static public Rect rectFromPoints(Pt a, Pt b) { return pointsRect(a.x, a.y, b.x, b.y); } static public TimeZone getTimeZone(String name) { return TimeZone.getTimeZone(name); } static public String standardTimeZone_name = "Europe/Berlin"; static public String standardTimeZone() { return standardTimeZone_name; } static public String fsI(String id) { return formatSnippetID(id); } static public String fsI(long id) { return formatSnippetID(id); } static public File loadBinarySnippet(String snippetID) { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadLibrary(snippetID); return loadBinarySnippet_noResourceLoader(snippetID); } static public File loadBinarySnippet_noResourceLoader(String snippetID) { try { long id = parseSnippetID(snippetID); if (isImageServerSnippet(id)) return loadImageAsFile(snippetID); File f = DiskSnippetCache_getLibrary(id); if (fileSize(f) == 0) f = loadDataSnippetToFile_noResourceLoader(snippetID); return f; } catch (Exception __e) { throw rethrow(__e); } } static public boolean loadBufferedImageFixingGIFs_debug = false; static public ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal(); static public Image loadBufferedImageFixingGIFs(File file) { try { if (!file.exists()) return null; if (!isGIF(file)) return ImageIO.read(file); if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": checking gif"); ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next(); reader.setInput(ImageIO.createImageInputStream(file)); int numImages = reader.getNumImages(true); IIOMetadata imageMetaData = reader.getImageMetadata(0); String metaFormatName = imageMetaData.getNativeMetadataFormatName(); boolean foundBug = false; for (int i = 0; i < numImages && !foundBug; i++) { IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName); int nNodes = root.getLength(); for (int j = 0; j < nNodes; j++) { org.w3c.dom.Node node = root.item(j); if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) { String delay = ((IIOMetadataNode) node).getAttribute("delayTime"); if (Integer.parseInt(delay) == 0) { foundBug = true; } break; } } } if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug); Image image; if (!foundBug) { image = Toolkit.getDefaultToolkit().createImage(f2s(file)); } else { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); { ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream); try { ImageWriter writer = ImageIO.getImageWriter(reader); writer.setOutput(ios); writer.prepareWriteSequence(null); for (int i = 0; i < numImages; i++) { BufferedImage frameIn = reader.read(i); IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName); int nNodes = root.getLength(); for (int j = 0; j < nNodes; j++) { org.w3c.dom.Node node = root.item(j); if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) { String delay = ((IIOMetadataNode) node).getAttribute("delayTime"); if (Integer.parseInt(delay) == 0) { ((IIOMetadataNode) node).setAttribute("delayTime", "10"); } break; } } IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null); metadata.setFromTree(metadata.getNativeMetadataFormatName(), root); IIOImage frameOut = new IIOImage(frameIn, null, metadata); writer.writeToSequence(frameOut, writer.getDefaultWriteParam()); } writer.endWriteSequence(); } finally { _close(ios); } } byte[] data = baoStream.toByteArray(); setVar(loadBufferedImageFixingGIFs_output.get(), data); if (loadBufferedImageFixingGIFs_debug) print("Data size: " + l(data)); image = Toolkit.getDefaultToolkit().createImage(data); } return image; } catch (Exception __e) { throw rethrow(__e); } } static public A bindListenerToComponent(A component, IHasChangeListeners source, Runnable listener) { if (source != null && listener != null) bindToComponent(component, new Runnable() { public void run() { try { source.onChangeAndNow(listener); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "source.onChangeAndNow(listener);"; } }, new Runnable() { public void run() { try { source.removeChangeListener(listener); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "source.removeChangeListener(listener)"; } }); return component; } static public void scanForComponents(final Component c, final Class theClass, final List l) { if (theClass.isInstance(c)) l.add((A) c); if (c instanceof Container) { swing(() -> { for (Component comp : ((Container) c).getComponents()) scanForComponents(comp, theClass, l); }); } } static public String getSelectedItem(JList l) { return (String) l.getSelectedValue(); } static public String getSelectedItem(JComboBox cb) { return strOrNull(cb.getSelectedItem()); } static public void clear(Collection c) { if (c != null) c.clear(); } static public void clear(Map map) { if (map != null) map.clear(); } static public List _registerDangerousWeakMap_preList; static public A _registerDangerousWeakMap(A map) { return _registerDangerousWeakMap(map, null); } static public A _registerDangerousWeakMap(A map, Object init) { callF(init, map); if (init instanceof String) { final String f = (String) init; init = new VF1() { public void get(Map map) { try { callMC(f, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callMC(f, map)"; } }; } if (javax() == null) { if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList(); _registerDangerousWeakMap_preList.add(pair(map, init)); return map; } call(javax(), "_registerDangerousWeakMap", map, init); return map; } static public void _onLoad_registerDangerousWeakMap() { assertNotNull(javax()); if (_registerDangerousWeakMap_preList == null) return; for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b); _registerDangerousWeakMap_preList = null; } static public Map synchroMap() { return synchroHashMap(); } static public Map synchroMap(Map map) { return Collections.synchronizedMap(map); } static public B syncMapGet2(Map map, A a) { if (map == null) return null; synchronized (collectionMutex(map)) { return map.get(a); } } static public B syncMapGet2(A a, Map map) { return syncMapGet2(map, a); } static public boolean isSubtypeOf(Class a, Class b) { return a != null && b != null && b.isAssignableFrom(a); } static public Set reflection_classesNotToScan_value = litset("jdk.internal.loader.URLClassPath"); static public Set reflection_classesNotToScan() { return reflection_classesNotToScan_value; } static public Border jCompoundBorder(Border inner, Border outer) { if (inner == null) return outer; if (outer == null) return inner; return BorderFactory.createCompoundBorder(inner, outer); } static public Object[] asObjectArray(Collection l) { return toObjectArray(l); } static public Object[] mapToParams(Map map) { return mapToObjectArray(map); } static public Object[] unrollParams(Object[] params) { if (l(params) == 1 && params[0] instanceof Map) return mapToParams((Map) params[0]); return params; } static public Object html_valueLessParam_cache; static public Object html_valueLessParam() { if (html_valueLessParam_cache == null) html_valueLessParam_cache = html_valueLessParam_load(); return html_valueLessParam_cache; } static public Object html_valueLessParam_load() { return new Object(); } static public String htmlQuote(String s) { return "\"" + htmlencode_forParams(s) + "\""; } static public IterableIterator iteratorFromFunction_withEndMarker_f0(final F0 f) { class IFF2 extends IterableIterator { public A a; public boolean have, done; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; have = false; return _a; } public void getNext() { if (done || have) return; Object o = f.get(); if (o == iteratorFromFunction_endMarker) { done = true; return; } a = (A) o; have = true; } } ; return new IFF2(); } static public List keysList(Map map) { return cloneListSynchronizingOn(keys(map), map); } static public List keysList(MultiSet ms) { return ms == null ? null : keysList(ms.map); } static public String htmlencode_noQuotes(String s) { if (s == null) return ""; int n = s.length(); StringBuilder out = null; for (int i = 0; i < n; i++) { char c = s.charAt(i); if (c == '<') { if (out == null) out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s)); out.append("<"); } else if (c == '>') { if (out == null) out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s)); out.append(">"); } else if (c > 127 || c == '&') { int cp = s.codePointAt(i); if (out == null) out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s)); out.append("&#x"); out.append(intToHex_flexLength(cp)); out.append(';'); i += Character.charCount(cp) - 1; } else { if (out != null) out.append(c); } } return out == null ? s : out.toString(); } static public BufferedImage intArrayToBufferedImage(int[] pixels, int w, int h) { int[] bitMasks = new int[] { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 }; SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, w, h, bitMasks); DataBufferInt db = new DataBufferInt(pixels, pixels.length); WritableRaster wr = Raster.createWritableRaster(sm, db, new Point()); return new BufferedImage(ColorModel.getRGBdefault(), wr, false, null); } static public BufferedImage drawImageOnImage(Image img, BufferedImage canvas, int x, int y) { createGraphics(canvas).drawImage(img, x, y, null); return canvas; } static public BufferedImage drawImageOnImage(Image img, BufferedImage canvas) { return drawImageOnImage(img, canvas, 0, 0); } static public Graphics2D graphics(BufferedImage img) { return imageGraphics(img); } static public String fileExtension(File f) { if (f == null) return null; return fileExtension(f.getName()); } static public String fileExtension(String s) { return substring(s, smartLastIndexOf(s, '.')); } static public BufferedReader bufferedReader(Reader r) { return bufferedReader(r, 8192); } static public BufferedReader bufferedReader(Reader r, int bufSize) { if (r == null) return null; return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r, bufSize), r); } static public A holdResource(IResourceHolder holder, A a) { { if (holder != null) holder.add(a); } return a; } static public CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) { class IFF2 extends CloseableIterableIterator { public A a; public boolean done = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } public 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 public String readLineFromReaderWithClose(BufferedReader r) { try { String s = r.readLine(); if (s == null) r.close(); return s; } catch (Exception __e) { throw rethrow(__e); } } static public 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 public A _registerIOWrap(A wrapper, Object wrapped) { return wrapper; } static public FileInputStream newFileInputStream(File path) throws IOException { return newFileInputStream(path.getPath()); } static public FileInputStream newFileInputStream(String path) throws IOException { FileInputStream f = new FileInputStream(path); _registerIO(f, path, true); return f; } static public int gzInputStream_defaultBufferSize = 65536; static public GZIPInputStream gzInputStream(File f) { try { return gzInputStream(new FileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } static public GZIPInputStream gzInputStream(File f, int bufferSize) { try { return gzInputStream(new FileInputStream(f), bufferSize); } catch (Exception __e) { throw rethrow(__e); } } static public GZIPInputStream gzInputStream(InputStream in) { return gzInputStream(in, gzInputStream_defaultBufferSize); } static public GZIPInputStream gzInputStream(InputStream in, int bufferSize) { try { return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in); } catch (Exception __e) { throw rethrow(__e); } } static public Map singular_specials = litmap("children", "child", "images", "image", "chess", "chess"); static public Set singular_specials2 = litciset("time", "machine", "line", "rule"); static public String singular(String s) { if (s == null) return null; { String __1 = singular_specials.get(s); if (!empty(__1)) return __1; } if (singular_specials2.contains(dropSuffix("s", afterLastSpace(s)))) return dropSuffix("s", s); if (s.endsWith("ness")) return s; if (s.endsWith("ges")) return dropSuffix("s", s); if (endsWith(s, "bases")) return dropLast(s); s = dropSuffix("es", s); s = dropSuffix("s", s); return s; } static public Set getPlural_specials = litciset("sheep", "fish"); static public String getPlural(String s) { if (contains(getPlural_specials, s)) return s; if (ewic(s, "y")) return dropSuffixIgnoreCase("y", s) + "ies"; if (ewicOneOf(s, "ss", "ch")) return s + "es"; if (ewic(s, "s")) return s; return s + "s"; } static public Map synchroHashMap() { return synchronizedMap(new HashMap()); } static public Class primitiveToBoxedType(Class type) { if (type == boolean.class) return Boolean.class; if (type == int.class) return Integer.class; if (type == long.class) return Long.class; if (type == float.class) return Float.class; if (type == short.class) return Short.class; if (type == char.class) return Character.class; if (type == byte.class) return Byte.class; if (type == double.class) return Double.class; return null; } static public ArrayList litlist(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } static public List toLowerCase(List strings) { List x = new ArrayList(); for (String s : strings) x.add(s.toLowerCase()); return x; } static public String[] toLowerCase(String[] strings) { String[] x = new String[l(strings)]; for (int i = 0; i < l(strings); i++) x[i] = strings[i].toLowerCase(); return x; } static public String toLowerCase(String s) { return s == null ? "" : s.toLowerCase(); } static public String firstWord2(String s) { s = xltrim(s); if (empty(s)) return ""; if (isLetterOrDigit(first(s))) return takeCharsWhile(__65 -> isLetterOrDigit(__65), s); else return "" + first(s); } static public boolean isString(Object o) { return o instanceof String; } static public F1 mainFunctionToF1(final String fname) { return new F1() { public Object get(Object a) { try { return callMC(fname, a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callMC(fname, a)"; } }; } static public A popLast(List l) { return liftLast(l); } static public List popLast(int n, List l) { return liftLast(n, l); } static public JInternalFrame getInternalFrame(final Object _o) { return _o == null ? null : swing(new F0() { public JInternalFrame get() { try { Object o = _o; if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof JInternalFrame) return (JInternalFrame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; } }); } static public File standardLogFile() { return getProgramFile("log"); } static public void logQuoted(String logFile, String line) { logQuoted(getProgramFile(logFile), line); } static public void logQuoted(File logFile, String line) { appendToFile(logFile, quote(line) + "\n"); } static public 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 public IF0 preferredScreen; static public int preferredScreen() { return preferredScreen != null ? preferredScreen.get() : preferredScreen_base(); } final static public int preferredScreen_fallback(IF0 _f) { return _f != null ? _f.get() : preferredScreen_base(); } static public int preferredScreen_base() { return 0; } static public List vmBus_queryAll(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); List out = new ArrayList(); for (Object o : unnullForIteration(vm_busListeners_live())) addIfNotNull(out, pcallF(o, msg, arg)); for (Object o : unnullForIteration(vm_busListenersByMessage_live().get(msg))) addIfNotNull(out, pcallF(o, msg, arg)); return out; } static public String getStackTrace2(Throwable e) { return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n"); } static public AutoCloseable tempSetThreadLocalIfNecessary(ThreadLocal tl, A a) { if (tl == null) return null; A prev = tl.get(); if (eq(prev, a)) return null; tl.set(a); return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); } }; } static public List dropFirstThreeAndLastThree(List l) { return dropFirstAndLast(3, l); } static public List tok_combineCurlyBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eq(t, "{")) { int j = findEndOfCurlyBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } static public boolean startsWithAndEndsWith(String s, String prefix, String suffix) { return startsWith(s, prefix) && endsWith(s, suffix); } static public JButton setButtonImage(Icon img, JButton btn) { btn.setIcon(img); return btn; } static public JButton setButtonImage(Image img, JButton btn) { btn.setIcon(imageIcon(img)); return btn; } static public A setButtonImage(Image img, A btn) { btn.setIcon(imageIcon(img)); return btn; } static public A setButtonImage(A btn, Image img) { return setButtonImage(img, btn); } static public A setButtonImage(A btn, String imageID) { btn.setIcon(imageIcon(imageID)); return btn; } static public JButton setButtonImage(JButton btn, Image img) { return setButtonImage(img, btn); } static public JButton setButtonImage(JButton btn, Icon img) { return setButtonImage(img, btn); } static public BufferedImage resizeImage(BufferedImage img, int newW, int newH) { return resizeImage(img, newW, newH, Image.SCALE_SMOOTH); } static public BufferedImage resizeImage(BufferedImage img, int newW, int newH, int scaleType) { if (newW == img.getWidth() && newH == img.getHeight()) return img; Image tmp = img.getScaledInstance(newW, newH, scaleType); BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = dimg.createGraphics(); g2d.drawImage(tmp, 0, 0, null); g2d.dispose(); return dimg; } static public BufferedImage resizeImage(BufferedImage img, int newW) { int newH = iround(img.getHeight() * (double) newW / img.getWidth()); return resizeImage(img, newW, newH); } static public BufferedImage resizeImage(int newW, BufferedImage img) { return resizeImage(img, newW); } static public BufferedImage loadImage2(String snippetIDOrURL) { return loadBufferedImage(snippetIDOrURL); } static public BufferedImage loadImage2(File file) { return loadBufferedImage(file); } static public String stackTraceToString(StackTraceElement[] st) { return lines(st); } static public String stackTraceToString(Throwable e) { return getStackTrace_noRecord(e); } static public Set synchronizedSet() { return synchroHashSet(); } static public Set synchronizedSet(Set set) { return Collections.synchronizedSet(set); } static public AutoCloseable tempRemove(Map map, A key) { if (map == null || !map.containsKey(key)) return null; B b = map.get(key); map.remove(key); return new AutoCloseable() { public String toString() { return "map.put(key, b);"; } public void close() throws Exception { map.put(key, b); } }; } static public boolean boolOptParam(ThreadLocal tl) { return isTrue(optPar(tl)); } static public boolean boolOptParam(Object[] __, String name) { return isTrue(optParam(__, name)); } static public boolean boolOptParam(String name, Object[] __) { return boolOptParam(__, name); } static public boolean boolOptParam(String name, Map __) { return isTrue(optPar(name, __)); } static public Map loadFont_cached_cache = new HashMap(); static synchronized public 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 public Font loadFont_cached(String snippetID, float size) { try { return loadFont_cached(snippetID).deriveFont(size); } catch (Exception __e) { throw rethrow(__e); } } static public A jenableUndoRedo(final A textcomp) { { swing(() -> { 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"); }); } return textcomp; } static public Lock downloadLock_lock = fairLock(); static public Lock downloadLock() { return downloadLock_lock; } static public String getSnippetTitleOpt(String s) { try { return isSnippetID(s) ? getSnippetTitle(s) : s; } catch (Throwable __e) { printStackTrace(__e); } return s; } static public boolean isSubstanceLAF() { return substanceLookAndFeelEnabled(); } static public boolean titlePopupMenu(final Component c, final Object menuMaker) { JComponent titleBar = getTitlePaneComponent(getPossiblyInternalFrame(c)); if (titleBar == null) { print("Can't add title right click!"); return false; } else { componentPopupMenu(titleBar, menuMaker); return true; } } static public void restart() { Object j = getJavaX(); call(j, "cleanRestart", get(j, "fullArgs")); } static public void duplicateThisProgram() { nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs")))); } static public void showConsole() { callOpt(get(javax(), "console"), "showConsole"); } static public JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) { final JCheckBoxMenuItem mi = swing(() -> 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 public JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, IVF1 r) { return jCheckBoxMenuItem(text, checked, (Object) r); } static public void toggleAlwaysOnTop(Window frame) { if (frame == null) return; { swing(() -> { frame.setAlwaysOnTop(!frame.isAlwaysOnTop()); }); } } static public Integer rectCenterX(Rect r) { return r == null ? null : r.x + r.w / 2; } static public Random defaultRandomizer() { return defaultRandomGenerator(); } static public int random(int n) { return random(n, defaultRandomGenerator()); } static public int random(int n, Random r) { return random(r, n); } static public int random(Random r, int n) { return n <= 0 ? 0 : getRandomizer(r).nextInt(n); } static public double random(double max) { return random() * max; } static public double random() { return defaultRandomGenerator().nextInt(100001) / 100000.0; } static public double random(double min, double max) { return min + random() * (max - min); } static public int random(int min, int max) { return min + random(max - min); } static public int random(int min, int max, Random r) { return random(r, min, max); } static public int random(Random r, int min, int max) { return min + random(r, max - min); } static public A random(List l) { return oneOf(l); } static public A random(Collection c) { if (c instanceof List) return random((List) c); int i = random(l(c)); return collectionGet(c, i); } static public int random(IntRange r) { return random(r.start, r.end); } static public Pair random(Map map) { return entryToPair(random(entries(map))); } static public Integer rectCenterY(Rect r) { return r == null ? null : r.y + r.h / 2; } static public Comparator caseInsensitiveComparator() { return betterCIComparator(); } static public TreeMap caseInsensitiveMap() { return new TreeMap(caseInsensitiveComparator()); } static public Rectangle getBounds(final Component c) { return c == null ? null : swing(new F0() { public Rectangle get() { try { return c.getBounds(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getBounds();"; } }); } static public Rect pointsRect(int x1, int y1, int x2, int y2) { return new Rect(x1, y1, x2 - x1, y2 - y1); } static public IResourceLoader vm_getResourceLoader() { return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader")); } static public boolean isImageServerSnippet(long id) { return id >= 1100000 && id < 1200000; } static public File loadImageAsFile(String snippetIDOrURL) { try { if (isURL(snippetIDOrURL)) throw fail("not implemented"); if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL); String snippetID = "" + parseSnippetID(snippetIDOrURL); File file = imageSnippetCacheFile(snippetID); if (fileSize(file) > 0) return file; String imageURL = snippetImageURL_noHttps(snippetID); System.err.println("Loading image: " + imageURL); byte[] data = loadBinaryPage(imageURL); saveBinaryFile(file, data); return file; } catch (Exception __e) { throw rethrow(__e); } } static public File DiskSnippetCache_file(long snippetID) { return new File(getGlobalCache(), "data_" + snippetID + ".jar"); } public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException { File file = DiskSnippetCache_file(snippetID); return file.exists() ? file : null; } public static File DiskSnippetCache_getLibrary(String snippetID) { try { return DiskSnippetCache_getLibrary(psI(snippetID)); } catch (Exception __e) { throw rethrow(__e); } } public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { saveBinaryFile(DiskSnippetCache_file(snippetID), data); } static public byte[] loadDataSnippetImpl(String snippetID) throws IOException { byte[] data; try { URL url = new URL(dataSnippetLink(snippetID)); print("Loading library: " + hideCredentials(url)); try { data = loadBinaryPage(url.openConnection()); } catch (RuntimeException e) { data = null; } if (data == null || data.length == 0) { url = new URL(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID)); print("Loading library: " + hideCredentials(url)); data = loadBinaryPage(url.openConnection()); } print("Bytes loaded: " + data.length); } catch (FileNotFoundException e) { throw new IOException("Binary snippet #" + snippetID + " not found or not public"); } return data; } static public long fileSize(String path) { return getFileSize(path); } static public long fileSize(File f) { return getFileSize(f); } static public File loadDataSnippetToFile(String snippetID) { try { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadLibrary(snippetID); return loadDataSnippetToFile_noResourceLoader(snippetID); } catch (Exception __e) { throw rethrow(__e); } } static public File loadDataSnippetToFile_noResourceLoader(String snippetID) { try { snippetID = fsI(snippetID); File f = DiskSnippetCache_file(parseSnippetID(snippetID)); List urlsTried = new ArrayList(); List errors = new ArrayList(); try { URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID))); print("Loading library: " + hideCredentials(url)); try { loadBinaryPageToFile(openConnection(url), f); if (fileSize(f) == 0) throw fail(); } catch (Throwable e) { errors.add(e); url = addAndReturn(urlsTried, new URL(tb_mainServer() + "/blobs/" + psI(snippetID))); print(e); print("Trying other server: " + hideCredentials(url)); loadBinaryPageToFile(openConnection(url), f); print("Got bytes: " + fileSize(f)); } if (fileSize(f) == 0) throw fail(); System.err.println("Bytes loaded: " + fileSize(f)); } catch (Throwable e) { errors.add(e); throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors)); } return f; } catch (Exception __e) { throw rethrow(__e); } } static public byte[] isGIF_magic = bytesFromHex("47494638"); static public boolean isGIF(byte[] data) { return byteArrayStartsWith(data, isGIF_magic); } static public boolean isGIF(File f) { return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic))); } static public void setVar(IVar v, A value) { if (v != null) v.set(value); } static public IVF1 setVar(IVar v) { return a -> { if (v != null) v.set(a); }; } static public HashSet litset(A... items) { return lithashset(items); } static public Object[] mapToObjectArray(Map map) { List l = new ArrayList(); for (Object o : keys(map)) { l.add(o); l.add(map.get(o)); } return toObjectArray(l); } static public Object[] mapToObjectArray(Object f, Collection l) { int n = l(l); Object[] array = new Object[n]; if (n != 0) { Iterator it = iterator(l); for (int i = 0; i < n; i++) array[i] = callF(f, it.next()); } return array; } static public Object[] mapToObjectArray(Object f, Object[] l) { int n = l(l); Object[] array = new Object[n]; for (int i = 0; i < n; i++) array[i] = callF(f, l[i]); return array; } static public Object[] mapToObjectArray(Collection l, IF1 f) { return mapToObjectArray(f, l); } static public Object[] mapToObjectArray(A[] l, IF1 f) { return mapToObjectArray(f, l); } static public Object[] mapToObjectArray(IF1 f, A[] l) { int n = l(l); Object[] array = new Object[n]; for (int i = 0; i < n; i++) array[i] = f.get(l[i]); return array; } static public Object[] mapToObjectArray(IF1 f, Collection l) { int n = l(l); Object[] array = new Object[n]; if (n != 0) { Iterator it = iterator(l); for (int i = 0; i < n; i++) array[i] = callF(f, it.next()); } return array; } static public ThreadLocal htmlencode_forParams_useV2 = new ThreadLocal(); static public String htmlencode_forParams(String s) { if (s == null) return ""; if (isTrue(htmlencode_forParams_useV2.get())) return htmlencode_forParams_v2(s); StringBuilder out = new StringBuilder(Math.max(16, s.length())); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c > 127 || c == '"' || c == '<' || c == '>') { out.append("&#"); out.append((int) c); out.append(';'); } else out.append(c); } return out.toString(); } static public boolean loadBufferedImage_useImageCache = true; static public BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try { ping(); if (snippetIDOrURLOrFile == null) return null; if (isURL(snippetIDOrURLOrFile)) return imageIO_readURL(snippetIDOrURLOrFile); if (isSnippetID(snippetIDOrURLOrFile)) { String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile); IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return loadBufferedImage(rl.loadLibrary(snippetID)); File dir = imageSnippetsCacheDir(); if (loadBufferedImage_useImageCache) { dir.mkdirs(); File file = new File(dir, snippetID + ".png"); if (file.exists() && file.length() != 0) try { return ImageIO.read(file); } catch (Throwable e) { e.printStackTrace(); } } String imageURL = snippetImageURL_http(snippetID); print("Loading image: " + imageURL); BufferedImage image = imageIO_readURL(imageURL); if (loadBufferedImage_useImageCache) { File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis()); ImageIO.write(image, "png", tempFile); tempFile.renameTo(new File(dir, snippetID + ".png")); } return image; } else return loadBufferedImage(new File(snippetIDOrURLOrFile)); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedImage loadBufferedImage(File file) { return loadBufferedImageFile(file); } static public ArrayList cloneListSynchronizingOn(Collection l, Object mutex) { if (l == null) return new ArrayList(); synchronized (mutex) { return new ArrayList(l); } } static public String intToHex_flexLength(int i) { return Integer.toHexString(i); } static public Map createGraphics_modulators = synchroIdentityHashMap(); static public Graphics2D createGraphics(BufferedImage img) { Graphics2D g = img.createGraphics(); Object mod = createGraphics_modulators.get(img); if (mod != null) callF(mod, g); return g; } static public void createGraphics_modulate(BufferedImage img, Object mod) { mapPut2(createGraphics_modulators, img, mod); } static public ThreadLocal imageGraphics_antiAlias = new ThreadLocal(); static public Graphics2D imageGraphics(BufferedImage img) { return !isFalse(imageGraphics_antiAlias.get()) ? antiAliasGraphics(img) : createGraphics(img); } static public int smartLastIndexOf(String s, char c) { if (s == null) return 0; int i = s.lastIndexOf(c); return i >= 0 ? i : l(s); } static public int smartLastIndexOf(List l, A sub) { int i = lastIndexOf(l, sub); return i < 0 ? l(l) : i; } static public TreeSet litciset(String... items) { TreeSet set = caseInsensitiveSet(); for (String a : items) set.add(a); return set; } static public TreeSet litciset(Symbol... items) { TreeSet set = treeSet(); for (Symbol a : items) set.add(a); return set; } static public String afterLastSpace(String s) { return s == null ? null : substring(s, s.lastIndexOf(' ') + 1); } static public String dropSuffixIgnoreCase(String suffix, String s) { return ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } static public boolean ewicOneOf(String s, String... l) { if (s != null) for (String x : l) if (ewic(s, x)) return true; return false; } static public Map synchronizedMap() { return synchroMap(); } static public Map synchronizedMap(Map map) { return synchroMap(map); } static public String xltrim(String s) { int i = 0, n = l(s); while (i < n && contains(" \t\r\n", s.charAt(i))) ++i; return substr(s, i); } static public String takeCharsWhile(String s, Object pred) { int i = 0; while (i < l(s) && isTrue(callF(pred, s.charAt(i)))) ++i; return substring(s, 0, i); } static public String takeCharsWhile(IF1 f, String s) { return takeCharsWhile(s, f); } static public A liftLast(List l) { if (empty(l)) return null; int i = l(l) - 1; A a = l.get(i); l.remove(i); return a; } static public List liftLast(int n, List l) { int i = l(l) - n; List part = cloneSubList(l, i); removeSubList(l, i); return part; } static public boolean isInstanceOf(Object o, Class type) { return type.isInstance(o); } static public boolean addIfNotNull(Collection l, A a) { return a != null && l != null & l.add(a); } static public void addIfNotNull(MultiSet ms, A a) { if (a != null && ms != null) ms.add(a); } static public 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 public List dropFirstAndLast(int n, List l) { return cloneSubList(l, n, l(l) - n); } static public List dropFirstAndLast(int m, int n, List l) { return cloneSubList(l, m, l(l) - n); } static public List dropFirstAndLast(List l) { return dropFirstAndLast(1, l); } static public String dropFirstAndLast(String s) { return substring(s, 1, l(s) - 1); } static public int findEndOfCurlyBracketPart(List cnc, int i) { int j = i + 2, level = 1; while (j < cnc.size()) { if (eq(cnc.get(j), "{")) ++level; else if (eq(cnc.get(j), "}")) --level; if (level == 0) return j + 1; ++j; } return cnc.size(); } static public Font loadFont(String snippetID) { try { return loadFont(snippetID, 12f); } catch (Exception __e) { throw rethrow(__e); } } static public Font loadFont(InputStream in) { try { return Font.createFont(Font.TRUETYPE_FONT, in); } catch (Exception __e) { throw rethrow(__e); } } static public Font loadFont(String snippetID, float fontSize) { return loadFont(loadLibrary(snippetID), fontSize); } static public Font loadFont(File f, float fontSize) { try { return Font.createFont(Font.TRUETYPE_FONT, f).deriveFont(fontSize); } catch (Exception __e) { throw rethrow(__e); } } static public Font loadFont(InputStream in, float fontSize) { try { return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(fontSize); } catch (Exception __e) { throw rethrow(__e); } } static public Set vm_generalWeakSet(Object name) { synchronized (vm_generalMap()) { Set set = (Set) (vm_generalMap_get(name)); if (set == null) vm_generalMap_put(name, set = newWeakHashSet()); return set; } } static public String getSnippetTitle(String id) { if (id == null) return null; if (!isSnippetID(id)) return "?"; IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.getSnippetTitle(id); return getSnippetTitle_noResourceLoader(id); } static public String getSnippetTitle_noResourceLoader(String id) { try { if (isLocalSnippetID(id)) return localSnippetTitle(id); long parsedID = parseSnippetID(id); String url; if (isImageServerSnippet(parsedID)) url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery(); else if (isGeneralFileServerSnippet(parsedID)) url = "http://butter.botcompany.de:8080/files/name/" + parsedID; else url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies(); String title = trim(loadPageSilently(url)); if (title != null) try { saveTextFileIfChanged(snippetTitle_cacheFile(id), title); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } return or(title, "?"); } catch (Exception __e) { throw rethrow(__e); } } static public String getSnippetTitle(long id) { return getSnippetTitle(fsI(id)); } static public boolean substanceLookAndFeelEnabled() { return startsWith(getLookAndFeel(), "org.pushingpixels."); } static public JComponent getTitlePaneComponent(RootPaneContainer window) { if (window instanceof JInternalFrame) return getInternalFrameTitlePaneComponent((JInternalFrame) window); if (!substanceLookAndFeelEnabled() || window == null) return null; JRootPane rootPane = window.getRootPane(); if (rootPane != null) { Object ui = rootPane.getUI(); return (JComponent) call(ui, "getTitlePane"); } return null; } static public void nohupJavax(final String javaxargs) { { startThread(new Runnable() { public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs);"; } }); } } static public void nohupJavax(final String javaxargs, final String vmArgs) { { startThread(new Runnable() { public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs, vmArgs);"; } }); } } static public String smartJoin(String[] args) { if (empty(args)) return ""; if (args.length == 1) return args[0]; String[] a = new String[args.length]; for (int i = 0; i < a.length; i++) a[i] = !isJavaIdentifier(args[i]) && !isQuoted(args[i]) ? quote(args[i]) : args[i]; return join(" ", a); } static public String smartJoin(List args) { return smartJoin(toStringArray(args)); } static public boolean isChecked(JCheckBox checkBox) { return checkBox != null && (boolean) swing(new F0() { public Boolean get() { try { return checkBox.isSelected(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return checkBox.isSelected();"; } }); } static public boolean isChecked(JCheckBoxMenuItem mi) { return mi != null && (boolean) swing(new F0() { public Boolean get() { try { return mi.isSelected(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return mi.isSelected();"; } }); } static public boolean isChecked(JRadioButton rb) { return rb != null && (boolean) swing(() -> rb.isSelected()); } static public Random defaultRandomGenerator() { { Random r = customRandomizerForThisThread(); if (r != null) return r; } return ThreadLocalRandom.current(); } static public Random getRandomizer(Random r) { return r != null ? r : defaultRandomGenerator(); } static public A oneOf(List l) { if (empty(l)) return null; int n = l.size(); return n == 1 ? first(l) : l.get(defaultRandomizer().nextInt(n)); } static public char oneOf(String s) { return empty(s) ? '?' : s.charAt(random(l(s))); } static public String oneOf(String... l) { return oneOf(asList(l)); } static public A collectionGet(Collection c, int idx) { if (c == null || idx < 0 || idx >= l(c)) return null; if (c instanceof List) return listGet((List) c, idx); Iterator it = c.iterator(); for (int i = 0; i < idx; i++) if (it.hasNext()) it.next(); else return null; return it.hasNext() ? it.next() : null; } static public Pair entryToPair(Map.Entry e) { return mapEntryToPair(e); } static public Set> entries(Map map) { return _entrySet(map); } static public betterCIComparator_C betterCIComparator_instance; static public betterCIComparator_C betterCIComparator() { if (betterCIComparator_instance == null) betterCIComparator_instance = new betterCIComparator_C(); return betterCIComparator_instance; } final static public class betterCIComparator_C implements Comparator { public int compare(String s1, String s2) { if (s1 == null) return s2 == null ? 0 : -1; if (s2 == null) return 1; int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) { return c1 - c2; } } } } return n1 - n2; } } static public A proxy(Class intrface, final Object target) { if (target == null) return null; if (isInstance(intrface, target)) return (A) target; return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new proxy_InvocationHandler(target)); } static public A proxy(Object target, Class intrface) { return proxy(intrface, target); } static public boolean isURL(String s) { return startsWithOneOf(s, "http://", "https://", "file:"); } static public File imageSnippetCacheFile(String snippetID) { File dir = imageSnippetsCacheDir(); if (!loadBufferedImage_useImageCache) return null; return new File(dir, parseSnippetID(snippetID) + ".png"); } static public String snippetImageURL_noHttps(String snippetID) { return snippetImageURL_noHttps(snippetID, "png"); } static public String snippetImageURL_noHttps(String snippetID, String contentType) { return snippetImageURL(snippetID, contentType).replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/").replace("https://botcompany.de/", "http://botcompany.de/"); } static public ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal(); static public ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal(); static public byte[] loadBinaryPage(String url) { try { print("Loading " + url); return loadBinaryPage(loadPage_openConnection(new URL(url))); } catch (Exception __e) { throw rethrow(__e); } } static public byte[] loadBinaryPage(URLConnection con) { try { Map extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders); setHeaders(con); for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key)); return loadBinaryPage_noHeaders(con); } catch (Exception __e) { throw rethrow(__e); } } static public byte[] loadBinaryPage_noHeaders(URLConnection con) { try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); InputStream inputStream = con.getInputStream(); loadBinaryPage_responseHeaders.set(con.getHeaderFields()); long len = 0; try { len = con.getContentLength(); } catch (Throwable e) { printStackTrace(e); } int n = 0; while (true) { int ch = inputStream.read(); if (ch < 0) break; buf.write(ch); if (++n % 100000 == 0) println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded."); } inputStream.close(); return buf.toByteArray(); } catch (Exception __e) { throw rethrow(__e); } } public static byte[] saveBinaryFile(String fileName, byte[] contents) { try { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = newFileOutputStream(tempFileName); fileOutputStream.write(contents); fileOutputStream.close(); if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); vmBus_send("wroteFile", file); return contents; } catch (Exception __e) { throw rethrow(__e); } } static public byte[] saveBinaryFile(File fileName, byte[] contents) { return saveBinaryFile(fileName.getPath(), contents); } static public File getGlobalCache() { File file = new File(javaxCachesDir(), "Binary Snippets"); file.mkdirs(); return file; } static public long psI(String snippetID) { return parseSnippetID(snippetID); } static public String dataSnippetLink(String snippetID) { long id = parseSnippetID(snippetID); if (id >= 1100000 && id < 1200000) return imageServerURL() + id; if (id >= 1200000 && id < 1300000) { String pw = muricaPassword(); if (empty(pw)) throw fail("Please set 'murica password by running #1008829"); return "https://botcompany.de/files/" + id + "?_pass=" + pw; } return fileServerURL() + "/" + id; } static public String tb_mainServer_default = "https://code.botcompany.de:9898"; static public Object tb_mainServer_override; static public String tb_mainServer() { if (tb_mainServer_override != null) return (String) callF(tb_mainServer_override); return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default)); } static public File tb_mainServer_file() { return getProgramFile("#1001638", "mainserver.txt"); } static public boolean tb_mainServer_isDefault() { return eq(tb_mainServer(), tb_mainServer_default); } static public A addAndReturn(Collection c, A a) { if (c != null) c.add(a); return a; } static public void loadBinaryPageToFile(String url, File file) { try { print("Loading " + url); loadBinaryPageToFile(openConnection(new URL(url)), file); } catch (Exception __e) { throw rethrow(__e); } } static public void loadBinaryPageToFile(URLConnection con, File file) { try { setHeaders(con); loadBinaryPageToFile_noHeaders(con, file); } catch (Exception __e) { throw rethrow(__e); } } static public void loadBinaryPageToFile_noHeaders(URLConnection con, File file) { try { File ftemp = new File(f2s(file) + "_temp"); FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp)); try { InputStream inputStream = con.getInputStream(); long len = 0; try { len = con.getContentLength(); } catch (Throwable e) { printStackTrace(e); } String pat = " {*}" + (len != 0 ? "/" + len : "") + " bytes loaded."; copyStreamWithPrints(inputStream, buf, pat); inputStream.close(); buf.close(); file.delete(); renameFile_assertTrue(ftemp, file); } finally { if (buf != null) buf.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public URLConnection openConnection(String url) { try { return openConnection(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } static public URLConnection openConnection(URL url) { try { ping(); callOpt(javax(), "recordOpenURLConnection", str(url)); return url.openConnection(); } catch (Exception __e) { throw rethrow(__e); } } static public byte[] bytesFromHex(String s) { return hexToBytes(s); } static public boolean byteArrayStartsWith(byte[] a, byte[] b) { if (a == null || b == null) return false; if (a.length < b.length) return false; for (int i = 0; i < b.length; i++) if (a[i] != b[i]) return false; return true; } static public byte[] loadBeginningOfBinaryFile(File file, int maxBytes) { return loadBinaryFilePart(file, 0, maxBytes); } static public HashSet lithashset(A... items) { HashSet set = new HashSet(); for (A a : items) set.add(a); return set; } static public String htmlencode_forParams_v2(String s) { if (s == null) return ""; StringBuilder out = new StringBuilder(Math.max(16, s.length())); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') { out.append("&#"); out.append((int) c); out.append(';'); } else out.append(c); } return out.toString(); } static public BufferedImage imageIO_readURL(String url) { try { return ImageIO.read(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } static public File imageSnippetsCacheDir() { return javaxCachesDir("Image-Snippets"); } static public String snippetImageURL_http(String snippetID) { return snippetImageURL_http(snippetID, "png"); } static public String snippetImageURL_http(String snippetID, String contentType) { return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080"); } static public Map synchroIdentityHashMap() { return synchroMap(new IdentityHashMap()); } static public void mapPut2(Map map, A key, B value) { if (map != null && key != null) if (value != null) map.put(key, value); else map.remove(key); } static public Graphics2D antiAliasGraphics(BufferedImage img) { return antiAliasOn(createGraphics(img)); } static public TreeSet caseInsensitiveSet() { return caseInsensitiveSet_treeSet(); } static public TreeSet caseInsensitiveSet(Collection c) { return caseInsensitiveSet_treeSet(c); } static public TreeSet treeSet() { return new TreeSet(); } static public String substr(String s, int x) { return substring(s, x); } static public String substr(String s, int x, int y) { return substring(s, x, y); } static public void removeSubList(List l, int from, int to) { if (l != null) subList(l, from, to).clear(); } static public void removeSubList(List l, int from) { if (l != null) subList(l, from).clear(); } static public File loadLibrary(String snippetID) { return loadBinarySnippet(snippetID); } static public boolean isLocalSnippetID(String snippetID) { return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID)); } static public boolean isLocalSnippetID(long snippetID) { return snippetID >= 1000 && snippetID <= 9999; } static public String localSnippetTitle(String snippetID) { if (!isLocalSnippetID(snippetID)) return null; File f = localSnippetFile(snippetID); if (!f.exists()) return null; return or2(getFileInfoField(dropExtension(f), "Title"), "Unnamed"); } static public String imageServerURL() { return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/"); } static public String muricaCredentialsQuery() { return htmlQuery(muricaCredentials()); } static public boolean isGeneralFileServerSnippet(long id) { return id >= 1400000 && id < 1500000; } static public String standardCredentials_noCookies() { return standardCredentials() + "&noCookies=1"; } static public boolean saveTextFileIfChanged(File f, String contents) { return saveTextFileIfDifferent(f, contents); } static public File snippetTitle_cacheFile(String snippetID) { return javaxCachesDir("Snippet Titles/" + psI(snippetID)); } static public String getLookAndFeel() { return getClassName(UIManager.getLookAndFeel()); } static public JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) { return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane"); } static public Class hotwireOnce(String programID) { return hotwireCached(programID, false); } static public Random customRandomizerForThisThread() { return customRandomizerForThisThread_tl().get(); } static public A listGet(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } static public String snippetImageURL(long snippetID) { return snippetImageURL(fsI(snippetID)); } static public String snippetImageURL(String snippetID) { return snippetImageURL(snippetID, "png"); } static public String snippetImageURL(String snippetID, String contentType) { if (snippetID == null || isURL(snippetID)) return snippetID; long id = parseSnippetID(snippetID); String url; if (isImageServerSnippet(id)) url = imageServerLink(id); else url = "https://botcompany.de/img/" + id; return url; } static public int loadPage_defaultTimeout = 60000; static public ThreadLocal loadPage_charset = new ThreadLocal(); static public boolean loadPage_allowGzip = true, loadPage_debug; static public boolean loadPage_anonymous = false; static public int loadPage_verboseness = 100000; static public int loadPage_retries = 1; static public ThreadLocal loadPage_silent = new ThreadLocal(); static volatile public int loadPage_forcedTimeout; static public ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal(); static public ThreadLocal>> loadPage_responseHeaders = new ThreadLocal(); static public ThreadLocal> loadPage_extraHeaders = new ThreadLocal(); static public ThreadLocal loadPage_sizeLimit = new ThreadLocal(); public static String loadPageSilently(String url) { try { return loadPageSilently(new URL(loadPage_preprocess(url))); } catch (Exception __e) { throw rethrow(__e); } } public static String loadPageSilently(URL url) { try { if (!networkAllowanceTest(str(url))) throw fail("Not allowed: " + url); IOException e = null; for (int tries = 0; tries < loadPage_retries; tries++) try { URLConnection con = loadPage_openConnection(url); return loadPage(con, url); } catch (IOException _e) { e = _e; if (loadPage_debug) print(exceptionToStringShort(e)); if (tries < loadPage_retries - 1) sleepSeconds(1); } throw e; } catch (Exception __e) { throw rethrow(__e); } } static public String loadPage_preprocess(String url) { if (url.startsWith("tb/")) url = tb_mainServer() + "/" + url; if (url.indexOf("://") < 0) url = "http://" + url; return url; } static public String loadPage(String url) { try { url = loadPage_preprocess(url); if (!isTrue(loadPage_silent.get())) printWithTime("Loading: " + hideCredentials(url)); return loadPageSilently(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } static public String loadPage(URL url) { return loadPage(url.toExternalForm()); } static public String loadPage(URLConnection con, URL url) throws IOException { return loadPage(con, url, true); } static public String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException { Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders); Long limit = optPar(loadPage_sizeLimit); if (addHeaders) try { if (!loadPage_anonymous) setHeaders(con); if (loadPage_allowGzip) con.setRequestProperty("Accept-Encoding", "gzip"); con.setRequestProperty("X-No-Cookies", "1"); for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key)); } catch (Throwable e) { } vm_generalSubMap("URLConnection per thread").put(currentThread(), con); loadPage_responseHeaders.set(con.getHeaderFields()); InputStream in = null; try { in = urlConnection_getInputStream(con); if (loadPage_debug) print("Put stream in map: " + currentThread()); String contentType = con.getContentType(); if (contentType == null) { throw new IOException("Page could not be read: " + hideCredentials(url)); } String charset = loadPage_charset == null ? null : loadPage_charset.get(); if (charset == null) charset = loadPage_guessCharset(contentType); if ("gzip".equals(con.getContentEncoding())) { if (loadPage_debug) print("loadPage: Using gzip."); in = newGZIPInputStream(in); } Reader r; try { r = new InputStreamReader(in, unquote(charset)); } catch (UnsupportedEncodingException e) { print(toHex(utf8(charset))); throw e; } boolean silent = isTrue(loadPage_silent.get()); StringBuilder buf = new StringBuilder(); int n = 0; while (limit == null || n < limit) { ping(); int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; if (!silent && (n % loadPage_verboseness) == 0) print(" " + n + " chars read"); } return buf.toString(); } finally { if (loadPage_debug) print("loadPage done"); vm_generalSubMap("URLConnection per thread").remove(currentThread()); if (in != null) in.close(); } } static public String loadPage_guessCharset(String contentType) { Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType); String match = m.matches() ? m.group(1) : null; if (loadPage_debug) print("loadPage: contentType=" + contentType + ", match: " + match); return or(match, "UTF-8"); } static public URLConnection loadPage_openConnection(URL url) { URLConnection con = openConnection(url); int timeout = toInt(loadPage_forcedTimeout_byThread.get()); if (timeout == 0) timeout = loadPage_forcedTimeout; if (timeout != 0) setURLConnectionTimeouts(con, loadPage_forcedTimeout); else setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout); return con; } static public void setHeaders(URLConnection con) throws IOException { String computerID = getComputerID_quick(); if (computerID != null) try { con.setRequestProperty("X-ComputerID", computerID); con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version")); } catch (Throwable e) { } } static public A println(A a) { return print(a); } static public File javaxCachesDir_dir; static public File javaxCachesDir() { return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches"); } static public File javaxCachesDir(String sub) { return newFile(javaxCachesDir(), sub); } static volatile public boolean muricaPassword_pretendNotAuthed = false; static public String muricaPassword() { if (muricaPassword_pretendNotAuthed) return null; return trim(loadTextFile(muricaPasswordFile())); } static public String fileServerURL() { return "https://botcompany.de/files"; } public static File mkdirsFor(File file) { return mkdirsForFile(file); } static public void copyStreamWithPrints(InputStream in, OutputStream out, String pat) { try { byte[] buf = new byte[65536]; int total = 0; while (true) { int n = in.read(buf); if (n <= 0) return; out.write(buf, 0, n); if ((total + n) / 100000 > total / 100000) print(pat.replace("{*}", str(roundDownTo(100000, total)))); total += n; } } catch (Exception __e) { throw rethrow(__e); } } static public File renameFile_assertTrue(File a, File b) { try { if (a.equals(b)) return b; if (!a.exists()) throw fail("Source file not found: " + f2s(a)); if (b.exists()) throw fail("Target file exists: " + f2s(b)); mkdirsForFile(b); if (!a.renameTo(b)) throw fail("Can't rename " + f2s(a) + " to " + f2s(b)); return b; } catch (Exception __e) { throw rethrow(__e); } } static public byte[] hexToBytes(String s) { if (odd(l(s))) throw fail("Hex string has odd length: " + quote(shorten(10, s))); int n = l(s) / 2; byte[] bytes = new byte[n]; for (int i = 0; i < n; i++) { int a = parseHexChar(s.charAt(i * 2)); int b = parseHexChar(s.charAt(i * 2 + 1)); if (a < 0 || b < 0) throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s)); bytes[i] = (byte) ((a << 4) | b); } return bytes; } static public byte[] loadBinaryFilePart(File file, long start, long end) { try { RandomAccessFile raf = new RandomAccessFile(file, "r"); int n = toInt(min(raf.length(), end - start)); byte[] buffer = new byte[n]; try { raf.seek(start); raf.readFully(buffer, 0, n); return buffer; } finally { raf.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public Graphics2D antiAliasOn(Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); return g; } static public TreeSet caseInsensitiveSet_treeSet() { return new TreeSet(caseInsensitiveComparator()); } static public TreeSet caseInsensitiveSet_treeSet(Collection c) { return toCaseInsensitiveSet_treeSet(c); } static public File localSnippetFile(long snippetID) { return localSnippetsDir(snippetID + ".text"); } static public File localSnippetFile(String snippetID) { return localSnippetFile(parseSnippetID(snippetID)); } static public String getFileInfoField(File f, String field) { return getOneLineFileInfoField(f, field); } static public File dropExtension(File f) { return f == null ? null : fileInSameDir(f, dropExtension(f.getName())); } static public String dropExtension(String s) { return takeFirst(s, smartLastIndexOf(s, '.')); } static public String htmlQuery(Map params) { return empty(params) ? "" : "?" + makePostData(params); } static public String htmlQuery(Object... data) { return empty(data) ? "" : "?" + makePostData(data); } static public Object[] muricaCredentials() { String pass = muricaPassword(); return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0]; } static public String standardCredentials() { String user = standardCredentialsUser(); String pass = standardCredentialsPass(); if (nempty(user) && nempty(pass)) return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass); return ""; } static public boolean saveTextFileIfDifferent(File f, String contents) { if (eq(loadTextFile(f), contents)) return false; { saveTextFile(f, contents); return true; } } static public 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 public TreeMap hotwireCached_cache = new TreeMap(); static public Lock hotwireCached_lock = lock(); static public Class hotwireCached(String programID) { return hotwireCached(programID, true); } static public Class hotwireCached(String programID, boolean runMain) { return hotwireCached(programID, runMain, false); } static public Class hotwireCached(String programID, boolean runMain, boolean dependent) { Lock __0 = hotwireCached_lock; lock(__0); try { programID = formatSnippetID(programID); Class c = hotwireCached_cache.get(programID); if (c == null) { c = hotwire(programID); if (dependent) makeDependent(c); if (runMain) callMain(c); hotwireCached_cache.put(programID, c); } return c; } finally { unlock(__0); } } static public ThreadLocal customRandomizerForThisThread_tl = new ThreadLocal(); static public ThreadLocal customRandomizerForThisThread_tl() { return customRandomizerForThisThread_tl; } static public String imageServerLink(String md5OrID) { if (possibleMD5(md5OrID)) return "https://botcompany.de/images/md5/" + md5OrID; return imageServerLink(parseSnippetID(md5OrID)); } static public String imageServerLink(long id) { return "https://botcompany.de/images/" + id; } static public boolean networkAllowanceTest(String url) { return isAllowed("networkAllowanceTest", url); } static public A printWithTime(A a) { return printWithTime("", a); } static public A printWithTime(String s, A a) { print(hmsWithColons() + ": " + s, a); return a; } static public InputStream urlConnection_getInputStream(URLConnection con) throws IOException { return con.getInputStream(); } static public String toHex(byte[] bytes) { return bytesToHex(bytes); } static public String toHex(byte[] bytes, int ofs, int len) { return bytesToHex(bytes, ofs, len); } static public byte[] utf8(String s) { return toUtf8(s); } static public Matcher regexpMatcher(String pat, String s) { return compileRegexp(pat).matcher(unnull(s)); } static public Matcher regexpMatcher(java.util.regex.Pattern pat, String s) { return pat.matcher(unnull(s)); } static public URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) { con.setConnectTimeout(toInt(timeout)); con.setReadTimeout(toInt(timeout)); if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout) print("Warning: Timeouts not set by JDK."); return con; } static public URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) { if (con.getConnectTimeout() == 0) { con.setConnectTimeout(toInt(timeout)); if (con.getConnectTimeout() != timeout) print("Warning: URL connect timeout not set by JDK."); } if (con.getReadTimeout() == 0) { con.setReadTimeout(toInt(timeout)); if (con.getReadTimeout() != timeout) print("Warning: URL read timeout not set by JDK."); } return con; } static public String getComputerID_quick() { return computerID(); } static public File muricaPasswordFile() { return new File(javaxSecretDir(), "murica/muricaPasswordFile"); } static public int roundDownTo(int n, int x) { return x / n * n; } static public long roundDownTo(long n, long x) { return x / n * n; } static public int parseHexChar(char c) { if (c >= '0' && c <= '9') return charDiff(c, '0'); if (c >= 'a' && c <= 'f') return charDiff(c, 'a') + 10; if (c >= 'A' && c <= 'F') return charDiff(c, 'A') + 10; return -1; } static public TreeSet toCaseInsensitiveSet_treeSet(Iterable c) { if (isCISet(c)) return (TreeSet) c; TreeSet set = caseInsensitiveSet_treeSet(); addAll(set, c); return set; } static public TreeSet toCaseInsensitiveSet_treeSet(String... x) { TreeSet set = caseInsensitiveSet_treeSet(); addAll(set, x); return set; } static public File localSnippetsDir() { return javaxDataDir("Personal Programs"); } static public File localSnippetsDir(String sub) { return newFile(localSnippetsDir(), sub); } static public String getOneLineFileInfoField(File f, String field) { File infoFile = associatedInfosFile(f); List lines = lines(loadTextFile(infoFile)); return firstStartingWithIC_drop(lines, field + ": "); } static public File fileInSameDir(File f, String newName) { return newFile(parentFile(f), newName); } static public String makePostData(Map map) { StringBuilder buf = new StringBuilder(); for (Map.Entry e : castMapToMapO(map).entrySet()) { String key = (String) (e.getKey()); Object val = e.getValue(); if (val != null) { String value = str(val); if (nempty(buf)) buf.append("&"); buf.append(urlencode(key)).append("=").append(urlencode((value))); } } return str(buf); } static public String makePostData(Object... params) { StringBuilder buf = new StringBuilder(); int n = l(params); for (int i = 0; i + 1 < n; i += 2) { String key = (String) (params[i]); Object val = params[i + 1]; if (val != null) { String value = str(val); if (nempty(buf)) buf.append("&"); buf.append(urlencode(key)).append("=").append(urlencode((value))); } } return str(buf); } static public String standardCredentialsUser() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username")))); } static public String standardCredentialsPass() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass")))); } static public String urlencode(String x) { try { return URLEncoder.encode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } static public List getComponents(final Component c) { return !(c instanceof Container) ? emptyList() : asList(swing(new F0() { public Component[] get() { try { return ((Container) c).getComponents(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return ((Container) c).getComponents();"; } })); } static public Object makeDependent_postProcess; static public void makeDependent(Object c) { if (c == null) return; assertTrue("Not a class", c instanceof Class); dependentClasses(); hotwire_classes.add(new WeakReference(c)); Object local_log = getOpt(mc(), "local_log"); if (local_log != null) setOpt(c, "local_log", local_log); Object print_byThread = getOpt(mc(), "print_byThread"); if (print_byThread != null) setOpt(c, "print_byThread", print_byThread); callF(makeDependent_postProcess, c); } static public boolean possibleMD5(String s) { return isMD5(s); } static volatile public Object isAllowed_function; static volatile public boolean isAllowed_all = true; static public boolean isAllowed(String askingMethod, Object... args) { Object f = vm_generalMap_get("isAllowed_function"); if (f != null && !isTrue(callF(f, askingMethod, args))) return false; return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args)); } static public String hmsWithColons() { return hmsWithColons(now()); } static public String hmsWithColons(long time) { return new SimpleDateFormat("HH:mm:ss").format(time); } public static String bytesToHex(byte[] bytes) { return bytesToHex(bytes, 0, bytes.length); } public static String bytesToHex(byte[] bytes, int ofs, int len) { StringBuilder stringBuilder = new StringBuilder(len * 2); for (int i = 0; i < len; i++) { String s = "0" + Integer.toHexString(bytes[ofs + i]); stringBuilder.append(s.substring(s.length() - 2, s.length())); } return stringBuilder.toString(); } static public byte[] toUtf8(String s) { try { return s.getBytes(utf8charset()); } catch (Exception __e) { throw rethrow(__e); } } static public Map compileRegexp_cache = syncMRUCache(10); static public java.util.regex.Pattern compileRegexp(String pat) { java.util.regex.Pattern p = compileRegexp_cache.get(pat); if (p == null) { compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat)); } return p; } static public String _computerID; static public Lock computerID_lock = lock(); public static String computerID() { if (_computerID == null) { Lock __0 = computerID_lock; lock(__0); try { if (_computerID != null) return _computerID; File file = computerIDFile(); _computerID = loadTextFile(file.getPath()); if (_computerID == null) { _computerID = loadTextFile(userDir(".tinybrain/computer-id")); if (_computerID == null) _computerID = makeRandomID(12, new SecureRandom()); saveTextFile(file, _computerID); } } finally { unlock(__0); } } return _computerID; } static public File javaxSecretDir_dir; static public File javaxSecretDir() { return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret"); } static public File javaxSecretDir(String sub) { return newFile(javaxSecretDir(), sub); } static public int charDiff(char a, char b) { return (int) a - (int) b; } static public int charDiff(String a, char b) { return charDiff(stringToChar(a), b); } static public boolean isCISet(Iterable l) { return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator(); } static public File associatedInfosFile(File f) { return replaceExtension(f, ".infos"); } static public String firstStartingWithIC_drop(Collection l, final String prefix) { for (String s : unnull(l)) if (swic(s, prefix)) return substring(s, l(prefix)); return null; } static public String firstStartingWithIC_drop(String prefix, Collection l) { return firstStartingWithIC_drop(l, prefix); } static public File parentFile(File f) { return dirOfFile(f); } static public Map castMapToMapO(Map map) { return map; } static public File oneOfTheFiles(String... paths) { if (paths != null) for (String path : paths) if (fileExists(path)) return newFile(path); return null; } static public File oneOfTheFiles(File... files) { return oneOfTheFiles(asList(files)); } static public File oneOfTheFiles(Iterable files) { if (files != null) for (File f : files) if (fileExists(f)) return f; return null; } static public List dependentClasses() { return cleanUpAndGetWeakReferencesList(hotwire_classes); } static public boolean isMD5(String s) { return l(s) == 32 && isLowerHexString(s); } static public Charset utf8charset_cache; static public Charset utf8charset() { if (utf8charset_cache == null) utf8charset_cache = utf8charset_load(); return utf8charset_cache; } static public Charset utf8charset_load() { return Charset.forName("UTF-8"); } static public Map syncMRUCache(int size) { return synchroMap(new MRUCache(size)); } static public File computerIDFile() { return javaxDataDir("Basic Info/computer-id.txt"); } static public String makeRandomID(int length) { return makeRandomID(length, defaultRandomGenerator()); } static public String makeRandomID(int length, Random random) { char[] id = new char[length]; for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26)); return new String(id); } static public String makeRandomID(Random r, int length) { return makeRandomID(length, r); } static public char stringToChar(String s) { if (l(s) != 1) throw fail("bad stringToChar: " + s); return firstChar(s); } static public List> hotwire_classes = synchroList(); static public Class hotwireDependent(String src) { Class c = hotwire(src); makeDependent(c); return c; } static public File replaceExtension(File f, String extOld, String extNew) { return newFile(replaceExtension(f2s(f), extOld, extNew)); } static public File replaceExtension(File f, String extNew) { return replaceExtension(f, fileExtension(f), extNew); } static public String replaceExtension(String s, String extOld, String extNew) { s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s); return s + addPrefixOptIfNempty(".", extNew); } static public String replaceExtension(String name, String extNew) { return replaceExtension(name, fileExtension(name), extNew); } static public List cleanUpAndGetWeakReferencesList(List> l) { if (l == null) return null; synchronized (l) { List out = new ArrayList(); for (int i = 0; i < l(l); i++) { A a = l.get(i).get(); if (a == null) l.remove(i--); else out.add(a); } return out; } } static public boolean isLowerHexString(String s) { for (int i = 0; i < l(s); i++) { char c = s.charAt(i); if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { } else return false; } return true; } static public char firstChar(String s) { return s.charAt(0); } static public String dropSuffixIC(String suffix, String s) { return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } static public String addPrefixOptIfNempty(String prefix, String s) { return addPrefixIfNotEmpty2(prefix, s); } static public String addPrefixIfNotEmpty2(String prefix, String s) { return empty(s) ? "" : addPrefix(prefix, s); } static public String addPrefix(String prefix, String s) { return s.startsWith(prefix) ? s : prefix + s; } static public interface IResourceHolder { public A add(A a); public Collection takeAll(); } static public class JSection extends SingleComponentPanel { public JSection(Component c) { super(c); } public String getTitle() { Border border = getBorder(); if (border instanceof TitledBorder) return ((TitledBorder) border).getTitle(); return null; } } static public class SingleThread { public boolean running = false; public void run(Object r) { go(r); } synchronized public boolean go(final Object runnable) { if (running) return false; running = true; startThread("Single Thread", new Runnable() { public void run() { try { try { callF(runnable); } finally { _done(); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n callF(runnable);\r\n } finally {\r\n _done();\r\n }"; } }); return true; } synchronized public void _done() { running = false; } public boolean running() { return running; } } static public class Best_comparable { public A best; public Comparable score; public boolean verboseNewBest, replaceIfSameScore; transient public Object onChange; transient public Object stringifier; synchronized public boolean isNewBest(Comparable score) { return this.score == null || (replaceIfSameScore ? cmp(score, this.score) >= 0 : cmp(score, this.score) > 0); } synchronized public Comparable bestScore() { return score; } public Comparable score() { return bestScore(); } public Comparable getScore() { return bestScore(); } synchronized public float floatScoreOr(float defaultValue) { return best == null ? defaultValue : (float) score; } public boolean put(Pair p) { return p != null && put(p.a, p.b); } public boolean put(Best b) { return b != null && put(b.get(), b.score); } public boolean put(A a, Comparable score) { ping(); boolean change = false; if (a != null) synchronized (this) { if (isNewBest(score)) { best = a; this.score = score; change = true; } } if (change) { if (verboseNewBest) print("New best! " + this); pcallF(onChange); } return change; } synchronized public A get() { return best; } synchronized public boolean has() { return best != null; } synchronized public Pair pair() { return main.pair(best, bestScore()); } synchronized public A getIfScoreAbove(Comparable x) { return cmp(x, score()) >= 0 ? best : null; } public String toString() { return !has() ? "-" : "Score " + score + ": " + callStringifier(stringifier, best); } public boolean putAndPrintIfNewBest(A a, Comparable score) { if (!put(a, score)) return false; { print(this); return true; } } synchronized public void clear() { best = null; score = 0; } } static public class CompactHashMap extends CompactAbstractMap { final static public int INITIAL_SIZE = 3; final static public double LOAD_FACTOR = 0.6; final static public Object nullObject = new Object(); final static public Object deletedObject = new Object(); public int elements; public int freecells; public Object[] table; public CompactHashMap() { this(INITIAL_SIZE); } public CompactHashMap(int size) { table = new Object[(size == 0 ? 1 : size) * 2]; elements = 0; freecells = tableSize(); } public CompactHashMap(Map map) { this(0); if (map != null) putAll(map); } public synchronized int size() { return elements; } public synchronized boolean isEmpty() { return elements == 0; } public synchronized void clear() { elements = 0; for (int ix = 0; ix < tableSize(); ix++) { key(ix, null); value(ix, null); } freecells = tableSize(); } public synchronized boolean containsKey(Object k) { return key(findKeyIndex(k)) != null; } public synchronized boolean containsValue(Object v) { if (v == null) v = (V) nullObject; for (int ix = 0; ix < tableSize(); ix++) if (value(ix) != null && value(ix).equals(v)) return true; return false; } public synchronized Set> entrySet() { throw new UnsupportedOperationException(); } public synchronized V remove(Object k) { int index = findKeyIndex(k); if (key(index) != null) { V v = value(index); key(index, deletedObject); value(index, deletedObject); elements--; return v; } else return null; } public synchronized V put(K k, V v) { if (k == null) k = (K) nullObject; int hash = k.hashCode(); int index = (hash & 0x7FFFFFFF) % tableSize(); int offset = 1; int deletedix = -1; while (key(index) != null && !(key(index).hashCode() == hash && key(index).equals(k))) { if (key(index) == deletedObject) deletedix = index; index = ((index + offset) & 0x7FFFFFFF) % tableSize(); offset = offset * 2 + 1; if (offset == -1) offset = 2; } if (key(index) == null) { if (deletedix != -1) index = deletedix; else freecells--; elements++; key(index, k); value(index, v); if (1 - (freecells / (double) tableSize()) > LOAD_FACTOR) rehash(tableSize() * 2 + 1); return null; } else { V oldv = value(index); value(index, v); return oldv; } } public void rehash(int newCapacity) { int oldCapacity = tableSize(); Object[] newTable = new Object[newCapacity * 2]; for (int ix = 0; ix < oldCapacity; ix++) { Object k = key(ix); if (k == null || k == deletedObject) continue; int hash = k.hashCode(); int index = (hash & 0x7FFFFFFF) % newCapacity; int offset = 1; while (newTable[index * 2] != null) { index = ((index + offset) & 0x7FFFFFFF) % newCapacity; offset = offset * 2 + 1; if (offset == -1) offset = 2; } newTable[index * 2] = k; newTable[index * 2 + 1] = value(ix); } table = newTable; freecells = tableSize() - elements; } public synchronized V get(Object k) { return value(findKeyIndex(k)); } public synchronized Collection values() { return new ValueCollection(); } public synchronized Set keySet() { return new KeySet(); } final public int findKeyIndex(Object k) { if (k == null) k = nullObject; int hash = k.hashCode(); int index = (hash & 0x7FFFFFFF) % tableSize(); int offset = 1; while (key(index) != null && !(key(index).hashCode() == hash && key(index).equals(k))) { index = ((index + offset) & 0x7FFFFFFF) % tableSize(); offset = offset * 2 + 1; if (offset == -1) offset = 2; } return index; } public class KeySet extends AbstractSet { public synchronized int size() { return elements; } public synchronized boolean contains(Object k) { return containsKey(k); } public synchronized Iterator iterator() { return new KeyIterator(); } } public class KeyIterator implements Iterator { public int ix; public KeyIterator() { for (; ix < tableSize(); ix++) if (value(ix) != null && key(ix) != deletedObject) break; } public synchronized boolean hasNext() { return ix < tableSize(); } public synchronized void remove() { throw new UnsupportedOperationException("Collection is read-only"); } public synchronized K next() { if (ix >= tableSize()) throw new NoSuchElementException(); K key = (K) key(ix++); for (; ix < tableSize(); ix++) if (key(ix) != null && key(ix) != deletedObject) break; return key; } } public class ValueCollection extends AbstractCollection { public synchronized int size() { return elements; } public synchronized Iterator iterator() { return new ValueIterator(); } public synchronized boolean contains(Object v) { return containsValue(v); } } public class ValueIterator implements Iterator { public int ix; public ValueIterator() { for (; ix < table.length / 2; ix++) if (value(ix) != null && value(ix) != deletedObject) break; } public synchronized boolean hasNext() { return ix < tableSize(); } public synchronized void remove() { throw new UnsupportedOperationException("Collection is read-only"); } public synchronized V next() { if (ix >= tableSize()) throw new NoSuchElementException(); V value = (V) value(ix++); for (; ix < tableSize(); ix++) if (value(ix) != null && value(ix) != deletedObject) break; return value; } } public K key(int i) { return (K) table[i * 2]; } public void key(int i, Object key) { table[i * 2] = key; } public V value(int i) { return (V) table[i * 2 + 1]; } public void value(int i, Object value) { table[i * 2 + 1] = value; } public int tableSize() { return table.length / 2; } } static public interface IRef extends IF0 { public default void replaceValue(A oldValue, A newValue) { } } static public class DefunctClassLoader { } static public class LeftAlignedLine extends JPanel { public LeftAlignedLine(Component... components) { setLayout(LetterLayout.leftAlignedRow()); for (Component component : components) if (component != null) add(component); } public void add(String text) { add(new JLabel(text)); } } static public class DoubleRect { public double x, y, w, h; public DoubleRect() { } public DoubleRect(Rectangle r) { x = r.x; y = r.y; w = r.width; h = r.height; } public DoubleRect(double x, double y, double w, double h) { this.h = h; this.w = w; this.y = y; this.x = x; } public boolean eq(Object o) { if (!(o instanceof DoubleRect)) return false; if (o == this) return true; DoubleRect r = (DoubleRect) o; return x == r.x && y == r.y && w == r.w && h == r.h; } public String toString() { return x + "," + y + " / " + w + "," + h; } public double x1() { return x; } public double y1() { return y; } public double x2() { return x + w; } public double y2() { return y + h; } public boolean contains(Pt p) { return contains(p.x, p.y); } public boolean contains(double _x, double _y) { return _x >= x && _y >= y && _x < x + w && _y < y + h; } public boolean empty() { return w <= 0 || h <= 0; } } static public class Complex implements IFieldsToList { static final public String _fieldOrder = "re im"; public double re; public double im; public Complex() { } public Complex(double re, double im) { this.im = im; this.re = re; } public boolean equals(Object o) { if (!(o instanceof Complex)) return false; Complex __1 = (Complex) o; return re == __1.re && im == __1.im; } public int hashCode() { int h = -1679819632; h = boostHashCombine(h, _hashCode(re)); h = boostHashCombine(h, _hashCode(im)); return h; } public Object[] _fieldsToList() { return new Object[] { re, im }; } public double abs() { return sqrt(re * re + im * im); } public double re() { return re; } public double im() { return im; } final public double angle() { return phase(); } public double phase() { return Math.atan2(im, re); } public double fracAngle() { return fracNonNeg(angle() / twoPi()); } public String toString() { if (im != 0) return re == 0 ? im + "i" : re + plusPrefixUnlessMinus(str(im)) + "i"; else return str(re); } } static public class MRUCache extends LinkedHashMap { public int maxSize = 10; public MRUCache() { } public MRUCache(int maxSize) { this.maxSize = maxSize; } public boolean removeEldestEntry(Map.Entry eldest) { return size() > maxSize; } public Object _serialize() { return ll(maxSize, cloneLinkedHashMap(this)); } static public MRUCache _deserialize(List l) { MRUCache m = new MRUCache(); m.maxSize = (int) first(l); m.putAll((LinkedHashMap) second(l)); return m; } } static abstract public class CloseableIterableIterator extends IterableIterator implements AutoCloseable { public void close() throws Exception { } } static public interface IF2 { public C get(A a, B b); } static public class AlphanumComparator implements Comparator { public boolean ignoreCase = false; final public boolean isDigit(char ch) { return ((ch >= 48) && (ch <= 57)); } final public String getChunk(String s, int slength, int marker) { StringBuilder chunk = new StringBuilder(); char c = s.charAt(marker); chunk.append(c); marker++; if (isDigit(c)) while (marker < slength) { c = s.charAt(marker); if (!isDigit(c)) break; chunk.append(c); marker++; } else while (marker < slength) { c = s.charAt(marker); if (isDigit(c)) break; chunk.append(c); marker++; } return chunk.toString(); } public int compare(String s1, String s2) { if (s1 == null) return s2 == null ? 0 : -1; if (s2 == null) return 1; int thisMarker = 0; int thatMarker = 0; int s1Length = s1.length(); int s2Length = s2.length(); while (thisMarker < s1Length && thatMarker < s2Length) { String thisChunk = getChunk(s1, s1Length, thisMarker); thisMarker += thisChunk.length(); String thatChunk = getChunk(s2, s2Length, thatMarker); thatMarker += thatChunk.length(); int result = 0; if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { int thisChunkLength = thisChunk.length(); result = thisChunkLength - thatChunk.length(); if (result == 0) { for (int i = 0; i < thisChunkLength; i++) { result = thisChunk.charAt(i) - thatChunk.charAt(i); if (result != 0) { return result; } } } } else { result = thisChunk.compareTo(thatChunk); } if (result != 0) return result; } return s1Length - s2Length; } } static public class Lowest { public A best; public double score; transient public Object onChange; synchronized public boolean isNewBest(double score) { return best == null || score < this.score; } synchronized public double bestScore() { return best == null ? Double.NaN : score; } public double score() { return bestScore(); } synchronized public float floatScore() { return best == null ? Float.NaN : (float) score; } synchronized public float floatScoreOr(float defaultValue) { return best == null ? defaultValue : (float) score; } public boolean put(A a, double score) { boolean change = false; synchronized (this) { if (a != null && isNewBest(score)) { best = a; this.score = score; change = true; } } if (change) pcallF(onChange); return change; } synchronized public void clear() { best = null; score = 0; } synchronized public A get() { return best; } synchronized public boolean has() { return best != null; } synchronized public Pair pair() { return best == null ? null : new Pair(best, bestScore()); } public String toString() { return "Score " + formatDouble_significant2(score, 4) + ": " + best; } } static public interface IResourceLoader { public String loadSnippet(String snippetID); public String getTranspiled(String snippetID); public int getSnippetType(String snippetID); public String getSnippetTitle(String snippetID); public File loadLibrary(String snippetID); default public File pathToJavaXJar() { return pathToJavaxJar_noResourceLoader(); } default public File getSnippetJar(String snippetID, String transpiledSrc) { return null; } } static public class InstantNeverHideToolTip extends MouseAdapter { public JComponent component; public JToolTip toolTip; public Popup popup; public int x, y; public String text; public IF0 calculateText; public InstantNeverHideToolTip(IF0 calculateText, JComponent component) { this(component); this.calculateText = calculateText; } public InstantNeverHideToolTip(String text, JComponent component) { this(component); this.text = text; } public InstantNeverHideToolTip(JComponent component) { this.component = component; { swing(() -> { component.addMouseListener(InstantNeverHideToolTip.this); toolTip = component.createToolTip(); bindToComponent(component, null, () -> hideToolTip()); }); } } @Override public void mouseEntered(MouseEvent e) { x = e.getXOnScreen() + 2; y = e.getYOnScreen() + 2; showToolTip(); } public void updateText() { swing(() -> { if (calculateText != null) setText(calculateText.get()); }); } public void showToolTip() { updateText(); if (empty(text)) return; toolTip.setTipText(text); popup = PopupFactory.getSharedInstance().getPopup(component, toolTip, x, y); popup.show(); } public void mouseExited(MouseEvent e) { hideToolTip(); } public boolean toolTipShowing() { return popup != null; } public void hideToolTip() { if (popup != null) { popup.hide(); popup = null; } } public String getText() { return text; } public void setText(String text) { swing(() -> { if (eq(text, getText())) return; InstantNeverHideToolTip.this.text = text; if (toolTipShowing()) { hideToolTip(); showToolTip(); } }); } } static public class Either { public byte which; public Object value; public Either() { } public Either(int which, Object value) { this.which = (byte) which; this.value = value; } public boolean isA() { return which == 1; } public boolean isB() { return which == 2; } public A a() { if (which != 1) _failMe(); return (A) value; } public B b() { if (which != 2) _failMe(); return (B) value; } public A aOpt() { return which != 1 ? null : (A) value; } public B bOpt() { return which != 2 ? null : (B) value; } public void _failMe() { throw fail("Either object is of wrong type: " + shortClassName(value)); } public String toString() { return "Either" + (isA() ? "A" : "B") + "(" + value + ")"; } } static public class CompactLinkedHashSet extends AbstractSet { public UnsynchronizedCompactHashSet> entries = new UnsynchronizedCompactHashSet(); public Entry head, tail; static public class Entry { public A value; public Entry prev, next; public int hashCode() { return _hashCode(value); } public boolean equals(Object o) { return o == this || eq(value, o); } } public boolean add(A a) { if (entries.contains(a)) return false; Entry n = new Entry(); n.value = a; n.prev = tail; if (tail != null) tail.next = n; tail = n; if (head == null) head = n; entries.add(n); return true; } public boolean remove(Object a) { return remove(entries.find(a)); } public boolean remove(Entry node) { if (node == null) return false; if (node.next != null) node.next.prev = node.prev; else tail = node.prev; if (node.prev != null) node.prev.next = node.next; else head = node.next; entries.remove(node); return true; } public int size() { return entries.size(); } public IterableIterator iterator() { return new IterableIterator() { public Entry entry = head, prev = null; public boolean hasNext() { return entry != null; } public A next() { A a = entry.value; prev = entry; entry = entry.next; return a; } public void remove() { if (prev == null) throw new IllegalStateException(); CompactLinkedHashSet.this.remove(prev); prev = null; } }; } public void clear() { entries.clear(); head = tail = null; } public boolean contains(Object a) { return entries.contains(a); } public A find(Object o) { Entry e = entries.find(o); return e == null ? null : e.value; } public A prevElement(A a) { Entry e = entries.find(a); if (e == null || e.prev == null) return null; return e.prev.value; } public A nextElement(A a) { Entry e = entries.find(a); if (e == null || e.next == null) return null; return e.next.value; } public A first() { return head == null ? null : head.value; } public A last() { return tail == null ? null : tail.value; } public boolean removeIfSame(Object o) { A value = find(o); if (value == o) { remove(value); return true; } return false; } } static public class proxy_InvocationHandler implements InvocationHandler { public Object target; public proxy_InvocationHandler() { } public proxy_InvocationHandler(Object target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) { return call(target, method.getName(), unnull(args)); } } static public class NumPadFixingInputMap extends InputMap { public void put(KeyStroke keyStroke, Object actionMapKey) { super.put(keyStroke, actionMapKey); Integer code = rsyntaxTextArea_fixNumPad_map.get(keyStroke.getKeyCode()); if (code != null) put(KeyStroke.getKeyStroke(code, keyStroke.getModifiers()), actionMapKey); } public void replaceOn(JComponent c) { InputMap im = c.getInputMap(); setParent(im.getParent()); for (KeyStroke key : im.keys()) put(key, im.get(key)); c.setInputMap(JComponent.WHEN_FOCUSED, this); } } abstract static public class NotifyingSet extends NotifyingCollection implements Set { public Set set; public NotifyingSet() { } public NotifyingSet(Set set) { super(set); this.set = set; } } static public class ChangeTrigger implements Runnable, IFieldsToList { public ChangeTriggerable target; public ChangeTrigger() { } public ChangeTrigger(ChangeTriggerable target) { this.target = target; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + target + ")"; } public boolean equals(Object o) { if (!(o instanceof ChangeTrigger)) return false; ChangeTrigger __1 = (ChangeTrigger) o; return eq(target, __1.target); } public int hashCode() { int h = -1239972920; h = boostHashCombine(h, _hashCode(target)); return h; } public Object[] _fieldsToList() { return new Object[] { target }; } public void run() { try { { if (target != null) target.change(); } } catch (Exception __e) { throw rethrow(__e); } } } static public class TimeoutException extends RuntimeException implements IFieldsToList { public double timeoutSeconds; public Object function; public Thread thread; public TimeoutException() { } public TimeoutException(double timeoutSeconds, Object function, Thread thread) { this.thread = thread; this.function = function; this.timeoutSeconds = timeoutSeconds; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + timeoutSeconds + ", " + function + ", " + thread + ")"; } public Object[] _fieldsToList() { return new Object[] { timeoutSeconds, function, thread }; } @Override public String getMessage() { return "Timeout after " + iceil(timeoutSeconds) + "s by " + shorten_str(function); } } abstract static public class NotifyingCollection extends AbstractCollection implements Collection { public Collection c; public NotifyingCollection() { } public NotifyingCollection(Collection c) { this.c = c; } public int size() { synchronized (this) { return c.size(); } } public boolean isEmpty() { synchronized (this) { return c.isEmpty(); } } public boolean contains(Object o) { synchronized (this) { return c.contains(o); } } public Object[] toArray() { synchronized (this) { return c.toArray(); } } public T[] toArray(T[] a) { synchronized (this) { return c.toArray(a); } } public Iterator iterator() { return c.iterator(); } public boolean add(E e) { synchronized (this) { beforeChange(); if (!c.add(e)) return false; } change(); return true; } public boolean remove(Object o) { synchronized (this) { beforeChange(); if (!c.remove(o)) return false; } change(); return true; } public boolean containsAll(Collection coll) { synchronized (this) { return c.containsAll(coll); } } public boolean addAll(Collection coll) { synchronized (this) { beforeChange(); if (!c.addAll(coll)) return false; } change(); return true; } public boolean removeAll(Collection coll) { synchronized (this) { beforeChange(); if (!c.removeAll(coll)) return false; } change(); return true; } public boolean retainAll(Collection coll) { synchronized (this) { beforeChange(); if (!c.retainAll(coll)) return false; } change(); return true; } public void clear() { synchronized (this) { beforeChange(); c.clear(); } change(); } public String toString() { synchronized (this) { return c.toString(); } } @Override public Spliterator spliterator() { return c.spliterator(); } public void beforeChange() { } abstract public void change(); public Collection unwrap() { return c; } } abstract static public class CompactAbstractMap implements Map { public int size() { return entrySet().size(); } public boolean isEmpty() { return size() == 0; } public boolean containsValue(Object value) { Iterator> i = entrySet().iterator(); if (value == null) { while (i.hasNext()) { Entry e = i.next(); if (e.getValue() == null) return true; } } else { while (i.hasNext()) { Entry e = i.next(); if (value.equals(e.getValue())) return true; } } return false; } public boolean containsKey(Object key) { Iterator> i = entrySet().iterator(); if (key == null) { while (i.hasNext()) { Entry e = i.next(); if (e.getKey() == null) return true; } } else { while (i.hasNext()) { Entry e = i.next(); if (key.equals(e.getKey())) return true; } } return false; } public V get(Object key) { Iterator> i = entrySet().iterator(); if (key == null) { while (i.hasNext()) { Entry e = i.next(); if (e.getKey() == null) return e.getValue(); } } else { while (i.hasNext()) { Entry e = i.next(); if (key.equals(e.getKey())) return e.getValue(); } } return null; } public V put(K key, V value) { throw new UnsupportedOperationException(); } public V remove(Object key) { Iterator> i = entrySet().iterator(); Entry correctEntry = null; if (key == null) { while (correctEntry == null && i.hasNext()) { Entry e = i.next(); if (e.getKey() == null) correctEntry = e; } } else { while (correctEntry == null && i.hasNext()) { Entry e = i.next(); if (key.equals(e.getKey())) correctEntry = e; } } V oldValue = null; if (correctEntry != null) { oldValue = correctEntry.getValue(); i.remove(); } return oldValue; } public void putAll(Map m) { for (Entry e : m.entrySet()) put(e.getKey(), e.getValue()); } public void clear() { entrySet().clear(); } public Set keySet() { return new AbstractSet() { public Iterator iterator() { return new Iterator() { public Iterator> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public K next() { return i.next().getKey(); } public void remove() { i.remove(); } }; } public int size() { return CompactAbstractMap.this.size(); } public boolean isEmpty() { return CompactAbstractMap.this.isEmpty(); } public void clear() { CompactAbstractMap.this.clear(); } public boolean contains(Object k) { return CompactAbstractMap.this.containsKey(k); } }; } public Collection values() { return new AbstractCollection() { public Iterator iterator() { return new Iterator() { public Iterator> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public V next() { return i.next().getValue(); } public void remove() { i.remove(); } }; } public int size() { return CompactAbstractMap.this.size(); } public boolean isEmpty() { return CompactAbstractMap.this.isEmpty(); } public void clear() { CompactAbstractMap.this.clear(); } public boolean contains(Object v) { return CompactAbstractMap.this.containsValue(v); } }; } public abstract Set> entrySet(); public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Map)) return false; Map m = (Map) o; if (m.size() != size()) return false; try { for (Entry e : entrySet()) { K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(m.get(key) == null && m.containsKey(key))) return false; } else { if (!value.equals(m.get(key))) return false; } } } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } return true; } public int hashCode() { int h = 0; for (Entry entry : entrySet()) h += entry.hashCode(); return h; } public String toString() { Iterator> i = entrySet().iterator(); if (!i.hasNext()) return "{}"; StringBuilder sb = new StringBuilder(); sb.append('{'); for (; ; ) { Entry e = i.next(); K key = e.getKey(); V value = e.getValue(); sb.append(key == this ? "(this Map)" : key); sb.append('='); sb.append(value == this ? "(this Map)" : value); if (!i.hasNext()) return sb.append('}').toString(); sb.append(',').append(' '); } } public Object clone() throws CloneNotSupportedException { CompactAbstractMap result = (CompactAbstractMap) super.clone(); return result; } public static class SimpleEntry implements Entry, java.io.Serializable { @java.io.Serial static final public long serialVersionUID = -8499721149061103585L; @SuppressWarnings("serial") final public K key; @SuppressWarnings("serial") public V value; public SimpleEntry(K key, V value) { this.key = key; this.value = value; } public SimpleEntry(Entry entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Entry e = (Entry) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public String toString() { return key + "=" + value; } } public static class SimpleImmutableEntry implements Entry, java.io.Serializable { @java.io.Serial static final public long serialVersionUID = 7138329143949025153L; @SuppressWarnings("serial") final public K key; @SuppressWarnings("serial") final public V value; public SimpleImmutableEntry(K key, V value) { this.key = key; this.value = value; } public SimpleImmutableEntry(Entry entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { throw new UnsupportedOperationException(); } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Entry e = (Entry) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public String toString() { return key + "=" + value; } } } static public class UnsynchronizedCompactHashSet extends java.util.AbstractSet { final static public int INITIAL_SIZE = 3; public final static double LOAD_FACTOR = 0.75; final static public Object nullObject = new Object(); final static public Object deletedObject = new Object(); public int elements; public int freecells; public A[] objects; public int modCount; public UnsynchronizedCompactHashSet() { this(INITIAL_SIZE); } public UnsynchronizedCompactHashSet(int size) { objects = (A[]) new Object[(size == 0 ? 1 : size)]; elements = 0; freecells = objects.length; modCount = 0; } public UnsynchronizedCompactHashSet(Collection c) { this(c.size()); addAll(c); } @Override public Iterator iterator() { return new CompactHashIterator(); } @Override public int size() { return elements; } @Override public boolean isEmpty() { return elements == 0; } @Override public boolean contains(Object o) { return find(o) != null; } public A find(Object o) { if (o == null) o = nullObject; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) { index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset * 2 + 1; if (offset == -1) offset = 2; } return objects[index]; } public boolean removeIfSame(Object o) { A value = find(o); if (value == o) { remove(value); return true; } return false; } @Override public boolean add(Object o) { if (o == null) o = nullObject; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; int deletedix = -1; while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) { if (objects[index] == deletedObject) deletedix = index; index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset * 2 + 1; if (offset == -1) offset = 2; } if (objects[index] == null) { if (deletedix != -1) index = deletedix; else freecells--; modCount++; elements++; objects[index] = (A) o; if (1 - (freecells / (double) objects.length) > LOAD_FACTOR) rehash(); return true; } else return false; } @Override public boolean remove(Object o) { if (o == null) o = nullObject; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) { index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset * 2 + 1; if (offset == -1) offset = 2; } if (objects[index] != null) { objects[index] = (A) deletedObject; modCount++; elements--; return true; } else return false; } @Override public void clear() { elements = 0; for (int ix = 0; ix < objects.length; ix++) objects[ix] = null; freecells = objects.length; modCount++; } @Override public Object[] toArray() { Object[] result = new Object[elements]; Object[] objects = this.objects; int pos = 0; for (int i = 0; i < objects.length; i++) if (objects[i] != null && objects[i] != deletedObject) { if (objects[i] == nullObject) result[pos++] = null; else result[pos++] = objects[i]; } return result; } @Override public T[] toArray(T[] a) { int size = elements; if (a.length < size) a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); A[] objects = this.objects; int pos = 0; for (int i = 0; i < objects.length; i++) if (objects[i] != null && objects[i] != deletedObject) { if (objects[i] == nullObject) a[pos++] = null; else a[pos++] = (T) objects[i]; } return a; } public void rehash() { int garbagecells = objects.length - (elements + freecells); if (garbagecells / (double) objects.length > 0.05) rehash(objects.length); else rehash(objects.length * 2 + 1); } public void rehash(int newCapacity) { int oldCapacity = objects.length; @SuppressWarnings("unchecked") A[] newObjects = (A[]) new Object[newCapacity]; for (int ix = 0; ix < oldCapacity; ix++) { Object o = objects[ix]; if (o == null || o == deletedObject) continue; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % newCapacity; int offset = 1; while (newObjects[index] != null) { index = ((index + offset) & 0x7FFFFFFF) % newCapacity; offset = offset * 2 + 1; if (offset == -1) offset = 2; } newObjects[index] = (A) o; } objects = newObjects; freecells = objects.length - elements; } public class CompactHashIterator implements Iterator { public int index; public int lastReturned = -1; public int expectedModCount; @SuppressWarnings("empty-statement") public CompactHashIterator() { for (index = 0; index < objects.length && (objects[index] == null || objects[index] == deletedObject); index++) ; expectedModCount = modCount; } @Override public boolean hasNext() { return index < objects.length; } @SuppressWarnings("empty-statement") @Override public T next() { int length = objects.length; if (index >= length) { lastReturned = -2; throw new NoSuchElementException(); } lastReturned = index; for (index += 1; index < length && (objects[index] == null || objects[index] == deletedObject); index++) ; if (objects[lastReturned] == nullObject) return null; else return (T) objects[lastReturned]; } @Override public void remove() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (lastReturned == -1 || lastReturned == -2) throw new IllegalStateException(); if (objects[lastReturned] != null && objects[lastReturned] != deletedObject) { objects[lastReturned] = (A) deletedObject; elements--; modCount++; expectedModCount = modCount; } } } public int capacity() { return objects.length; } public boolean shrinkToFactor(double factor) { if (factor > LOAD_FACTOR) throw fail("Shrink factor must be equal to or smaller than load factor: " + factor + " / " + LOAD_FACTOR); int newCapacity = max(INITIAL_SIZE, iround(size() / factor)); if (newCapacity >= capacity()) return false; rehash(newCapacity); return true; } } static public class Best { public A best; public double score; public boolean verboseNewBest, replaceIfSameScore; transient public Object onChange; transient public Object stringifier; synchronized public boolean isNewBest(double score) { return best == null || !isNaN(score) && (replaceIfSameScore ? score >= this.score : score > this.score); } synchronized public double bestScore() { return best == null ? minusInfinity() : score; } public double score() { return bestScore(); } public double getScore() { return bestScore(); } synchronized public float floatScoreOr(float defaultValue) { return best == null ? defaultValue : (float) score; } public boolean put(Pair p) { return p != null && put(p.a, p.b); } public boolean put(Best b) { return b != null && put(b.get(), b.score); } public boolean put(A a, double score) { ping(); boolean change = false; if (a != null) synchronized (this) { if (isNewBest(score)) { best = a; this.score = score; change = true; } } if (change) { if (verboseNewBest) print("New best! " + this); pcallF(onChange); } return change; } synchronized public A get() { return best; } synchronized public boolean has() { return best != null; } synchronized public Pair pair() { return main.pair(best, bestScore()); } synchronized public Scored scored() { return best == null ? null : new Scored(best, bestScore()); } synchronized public A getIfScoreAbove(double x) { return score() >= x ? best : null; } public String toString() { return "Score " + formatDouble_significant2(score, 4) + ": " + callStringifier(stringifier, best); } public boolean putAndPrintIfNewBest(A a, double score) { if (!put(a, score)) return false; { print(this); return true; } } synchronized public void clear() { best = null; score = 0; } } static public class LetterLayout implements LayoutManager { public String[] lines; public Map map = new TreeMap(); public Map constraints = new HashMap(); public RC[] rows; public RC[] cols; public Cell[][] cells; public int spacingX = 10, spacingY = 10; public int insetTop, insetBottom, insetLeft, insetRight; public int template; public boolean formWideLeftSide, formWideRightSide; static final public int STALACTITE = 1, LEFT_ALIGNED_ROW = 2, CENTERED_ROW = 3, FORM = 4, RIGHT_ALIGNED_ROW = 5; public boolean debug = false; public void setLeftBorder(int border) { insetLeft = border; } public void setRightBorder(int border) { insetRight = border; } public static JComponent withBorder(JComponent component, int border) { JPanel panel = new JPanel(new LetterLayout("C").setBorder(border)); panel.add("C", component); return panel; } public static JPanel panel(String... lines) { return new JPanel(new LetterLayout(lines)); } public static JPanel stalactitePanel() { return new JPanel(stalactite()); } static public class DummyComponent extends JComponent { } static public class Cell { public boolean aux = false; public int minWidth, minHeight; public Component component; public int colspan, rowspan; public double weightX, weightY; } static public class RC { public int min; public double weightSum; public int start; public int minEnd; } public LetterLayout(int template) { this.template = template; } public LetterLayout(String... lines) { this.lines = lines; } public void layoutContainer(Container container) { prepareLayout(container); if (debug) System.out.println("Container size: " + container.getSize()); Insets insets = getInsets(container); for (int r = 0; r < rows.length; r++) { for (int i = 0; i < cols.length; ) { Cell cell = cells[i][r]; if (cell.aux) ++i; else { if (cell.component != null) { int x1 = cols[i].start; int y1 = rows[r].start; int x2 = i + cell.colspan < cols.length ? cols[i + cell.colspan].start - spacingX : container.getWidth() - insets.right; int y2 = r + cell.rowspan < rows.length ? rows[r + cell.rowspan].start - spacingY : container.getHeight() - insets.bottom; if (debug) System.out.println("Layouting (" + i + ", " + r + ", " + cell.component.getClass().getName() + "): " + x1 + " " + y1 + " " + x2 + " " + y2); cell.component.setBounds(x1, y1, x2 - x1, y2 - y1); } i += cells[i][r].colspan; } } } } final public void prepareLayout(Container container) { applyTemplate(container); int numRows = lines.length, numCols = lines[0].length(); for (int i = 1; i < numRows; i++) if (lines[i].length() != numCols) throw new IllegalArgumentException("Lines have varying length"); cells = new Cell[numCols][numRows]; rows = new RC[numRows]; cols = new RC[numCols]; for (int r = 0; r < numRows; r++) rows[r] = new RC(); for (int i = 0; i < numCols; i++) cols[i] = new RC(); for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r] = new Cell(); for (int r = 0; r < numRows; r++) { String line = lines[r]; for (int i = 0; i < numCols; ) { Cell cell = cells[i][r]; if (cell.aux) { ++i; continue; } char ch = line.charAt(i); int iNext = i; do ++iNext; while (iNext < numCols && ch == line.charAt(iNext)); int rNext = r; do ++rNext; while (rNext < numRows && ch == lines[rNext].charAt(i)); cell.weightX = numCols == 1 || iNext > i + 1 ? 1.0 : 0.0; cell.weightY = numRows == 1 || rNext > r + 1 ? 1.0 : 0.0; Component c = map.get(String.valueOf(ch)); cell.component = c; if (c != null) { cell.minWidth = c.getMinimumSize().width + spacingX; cell.minHeight = getMinimumHeight(c) + spacingY; } cell.colspan = iNext - i; cell.rowspan = rNext - r; if (cell.colspan == 1) cols[i].min = Math.max(cols[i].min, cell.minWidth); if (cell.rowspan == 1) rows[r].min = Math.max(rows[r].min, cell.minHeight); for (int r2 = r; r2 < rNext; r2++) for (int i2 = i; i2 < iNext; i2++) if (r2 != r || i2 != i) cells[i2][r2].aux = true; i = iNext; } } while (true) { for (int i = 0; i < numCols; i++) { int minStart = i == 0 ? 0 : cols[i - 1].minEnd; double weightStart = i == 0 ? 0.0 : cols[i - 1].weightSum; for (int r = 0; r < numRows; r++) { Cell cell = cells[i][r]; if (!cell.aux) { RC rc = cols[i + cell.colspan - 1]; rc.minEnd = Math.max(rc.minEnd, minStart + cell.minWidth); rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightX); } } } for (int r = 0; r < numRows; r++) { int minStart = r == 0 ? 0 : rows[r - 1].minEnd; double weightStart = r == 0 ? 0.0 : rows[r - 1].weightSum; for (int i = 0; i < numCols; i++) { Cell cell = cells[i][r]; if (!cell.aux) { RC rc = rows[r + cell.rowspan - 1]; rc.minEnd = Math.max(rc.minEnd, minStart + cell.minHeight); rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightY); } } } if (allWeightsZero(cols)) { for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightX = 1.0; continue; } if (allWeightsZero(rows)) { for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightY = 1.0; continue; } break; } Insets insets = getInsets(container); determineStarts(cols, insets.left, container.getWidth() - insets.left - insets.right + spacingX, spacingX); determineStarts(rows, insets.top, container.getHeight() - insets.top - insets.bottom + spacingY, spacingY); } final public boolean allWeightsZero(RC[] rcs) { for (int i = 0; i < rcs.length; i++) if (rcs[i].weightSum != 0.0) return false; return true; } static public int getMinimumHeight(Component c) { return c.getMinimumSize().height; } final public void applyTemplate(Container container) { if (template == STALACTITE) { Component[] components = container.getComponents(); lines = new String[components.length + 2]; map.clear(); for (int i = 0; i < components.length; i++) { String s = String.valueOf(makeIndexChar(i)); map.put(s, components[i]); lines[i] = s; } lines[components.length] = lines[components.length + 1] = " "; } else if (template == FORM) { Component[] components = container.getComponents(); int numRows = components.length / 2; lines = new String[numRows + 2]; map.clear(); for (int row = 0; row < numRows; row++) { String lower = String.valueOf(makeIndexChar(row)); String upper = String.valueOf(makeAlternateIndexChar(row)); Component rightComponent = components[row * 2 + 1]; if (rightComponent instanceof DummyComponent) upper = lower; lines[row] = (formWideLeftSide ? lower + lower : lower) + (formWideRightSide ? upper + upper : upper); map.put(lower, components[row * 2]); if (!(rightComponent instanceof DummyComponent)) map.put(upper, rightComponent); } lines[numRows] = lines[numRows + 1] = (formWideLeftSide ? " " : " ") + (formWideRightSide ? " " : " "); } else if (template == LEFT_ALIGNED_ROW) { lines = new String[] { makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR }; } else if (template == CENTERED_ROW) { lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR }; } else if (template == RIGHT_ALIGNED_ROW) { lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) }; } } final public String makeSingleRow(Container container) { Component[] components = container.getComponents(); StringBuffer buf = new StringBuffer(); map.clear(); for (int i = 0; i < components.length; i++) { var c = components[i]; String s = constraints.get(c); if (isOneOfSingleChars(s, LEFT_CHAR, RIGHT_CHAR)) continue; s = str(makeAlternateIndexChar(i)); setConstraints(c, s); buf.append(s); } return buf.toString(); } static public void determineStarts(RC[] rcs, int start, int totalSize, int spacing) { int minTotal = rcs[rcs.length - 1].minEnd; double weightSum = rcs[rcs.length - 1].weightSum; int spare = (int) ((totalSize - minTotal) / (weightSum == 0.0 ? 1.0 : weightSum)); int x = start, minSum = 0; double prevWeightSum = 0.0; for (int i = 0; i < rcs.length; i++) { int width = rcs[i].minEnd - minSum + (int) ((rcs[i].weightSum - prevWeightSum) * spare) - spacing; rcs[i].start = x; x += width + spacing; prevWeightSum = rcs[i].weightSum; minSum = rcs[i].minEnd; } } public void addLayoutComponent(String s, Component component) { setConstraints(component, s); } public void setConstraints(Component component, String s) { mapPutOrRemove(map, s, component); mapPutOrRemove(constraints, component, s); } public void removeLayoutComponent(Component component) { map.values().remove(component); constraints.remove(component); } public Dimension minimumLayoutSize(Container container) { prepareLayout(container); Insets insets = getInsets(container); Dimension result = new Dimension(insets.left + cols[cols.length - 1].minEnd + insets.right - spacingX, insets.top + rows[rows.length - 1].minEnd + insets.bottom - spacingY); return result; } final public Insets getInsets(Container container) { Insets insets = container.getInsets(); return new Insets(insets.top + insetTop, insets.left + insetLeft, insets.bottom + insetBottom, insets.right + insetRight); } public Dimension preferredLayoutSize(Container container) { return minimumLayoutSize(container); } public LetterLayout setSpacing(int x, int y) { spacingX = x; spacingY = y; return this; } public LetterLayout setSpacing(int spacing) { return setSpacing(spacing, spacing); } public LetterLayout setBorder(int top, int left, int bottom, int right) { insetTop = top; insetLeft = left; insetBottom = bottom; insetRight = right; return this; } public LetterLayout setBorder(int inset) { return setBorder(inset, inset, inset, inset); } public LetterLayout setTopBorder(int inset) { insetTop = inset; return this; } public static LetterLayout stalactite() { return new LetterLayout(STALACTITE); } public static LetterLayout leftAlignedRow() { return new LetterLayout(LEFT_ALIGNED_ROW); } public static LetterLayout leftAlignedRow(int spacing) { return leftAlignedRow().setSpacing(spacing); } public static LetterLayout centeredRow() { return new LetterLayout(CENTERED_ROW); } public static LetterLayout rightAlignedRow() { return new LetterLayout(RIGHT_ALIGNED_ROW); } public static JPanel rightAlignedRowPanel(JComponent... components) { return makePanel(new LetterLayout(RIGHT_ALIGNED_ROW), components); } static public JPanel makePanel(LetterLayout letterLayout, JComponent[] components) { JPanel panel = new JPanel(letterLayout); for (JComponent component : components) { panel.add(component); } return panel; } public static LetterLayout form() { LetterLayout letterLayout = new LetterLayout(FORM); letterLayout.formWideLeftSide = true; letterLayout.formWideRightSide = true; return letterLayout; } public static LetterLayout formWideRightSide() { LetterLayout letterLayout = new LetterLayout(FORM); letterLayout.formWideRightSide = true; return letterLayout; } public static Component getDummyComponent() { return new DummyComponent(); } public static JPanel newPanel(String... lines) { return new JPanel(new LetterLayout(lines)); } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public static char makeIndexChar(int idx) { return (char) ('a' + idx * 2); } public static char makeAlternateIndexChar(int idx) { return (char) ('b' + idx * 2); } public static char LEFT_CHAR = ',', RIGHT_CHAR = '.'; public static void main(String[] args) { System.out.println((int) makeIndexChar(0)); System.out.println((int) makeAlternateIndexChar(0)); System.out.println((int) makeIndexChar(32000)); System.out.println((int) makeAlternateIndexChar(32000)); System.out.println((int) LEFT_CHAR); System.out.println((int) RIGHT_CHAR); } } static public GlobalID aGlobalIDObjUnlessLoading() { return dynamicObjectIsLoading() ? null : aGlobalIDObj(); } static public Border getBorder(final JComponent c) { return c == null ? null : swing(new F0() { public Border get() { try { return c.getBorder(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getBorder();"; } }); } static public float getScore(Scored s) { return s == null ? 0 : s.score; } static public boolean has(String a, String b, String c) { return false; } static public boolean has(T3 t) { return false; } static public String callStringifier(Object stringifier, Object o) { return stringifier != null ? str(callF(stringifier, o)) : str(o); } static public Value value(A a) { return new Value(a); } static public double sqrt(double x) { return Math.sqrt(x); } static public double fracNonNeg(double d) { return frac_nonNeg(d); } static public double twoPi() { return Math.PI * 2; } static public String plusPrefixUnlessMinus(String s) { return startsWith(s, "-") ? s : "+" + s; } static public LinkedHashMap cloneLinkedHashMap(Map map) { return map == null ? new LinkedHashMap() : new LinkedHashMap(map); } static public A second(List l) { return get(l, 1); } static public A second(Iterable l) { if (l == null) return null; Iterator it = iterator(l); if (!it.hasNext()) return null; it.next(); return it.hasNext() ? it.next() : null; } static public A second(A[] bla) { return bla == null || bla.length <= 1 ? null : bla[1]; } static public B second(Pair p) { return p == null ? null : p.b; } static public B second(T3 t) { return t == null ? null : t.b; } static public char second(String s) { return charAt(s, 1); } static public B second(Either e) { return e == null ? null : e.bOpt(); } static public String formatDouble_significant2(double d, int digits) { try { digits -= max(0, Math.floor(Math.log10(abs(d)) + 1)); return formatDouble(d, digits); } catch (Throwable _e) { print("Had number: " + d + ", digits: " + digits); throw rethrow(_e); } } static public File pathToJavaxJar() { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.pathToJavaXJar(); return pathToJavaxJar_noResourceLoader(); } static public File pathToJavaxJar_noResourceLoader() { try { int x = latestInstalledJavaX(); File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar"); if (!xfile.isFile()) { print("Saving " + f2s(xfile)); String url = x30JarServerURL(); byte[] data = loadBinaryPage(url); if (data.length < 1000000) throw fail("Could not load " + url); saveBinaryFile(xfile.getPath(), data); } return xfile; } catch (Exception __e) { throw rethrow(__e); } } static public String b(Object contents, Object... params) { return tag("b", contents, params); } static public boolean isA(Either e) { return eitherIsA(e); } static public String find(String pattern, String text) { Matcher matcher = Pattern.compile(pattern).matcher(text); if (matcher.find()) return matcher.group(1); return null; } static public A find(Collection c, Object... data) { for (A x : c) if (checkFields(x, data)) return x; return null; } static public int iceil(double d) { return (int) Math.ceil(d); } static public JComponent unwrap(JComponent c) { return c instanceof JScrollPane ? unwrapScrollPane((JScrollPane) c) : c; } static public boolean isNaN(double d) { return Double.isNaN(d); } static public boolean isNaN(float f) { return Float.isNaN(f); } static public double minusInfinity() { return negativeInfinity(); } static public Scored scored(A a, float score) { return new Scored(a, score); } static public Scored scored(A a, double score) { return new Scored(a, (float) score); } static public Scored scored(A a, Scored scored) { return new Scored(a, getScore(scored)); } static public Scored scored(double score, A a) { return scored(a, score); } static public JPanel withBorder(javax.swing.border.Border border, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(new BorderLayout()); p.setBorder(border); 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(border);\r\n p.add..."; } }); } static public int getMinimumHeight(final Component c) { return getMinimumSize(c).height; } static public boolean isOneOfSingleChars(String s, char... chars) { if (l(s) != 1) return false; char real = s.charAt(0); for (char c : unnullForIteration(chars)) if (real == c) return true; return false; } static public String form(Object contents, Object... params) { return hform(contents, params); } static public GlobalID aGlobalIDObj() { return asGlobalID(randomID(16)); } static public GlobalID aGlobalIDObj(Random random) { return asGlobalID(randomID(random, 16)); } static public double frac_nonNeg(double d) { return mod(d, 1); } static public char charAt(String s, int i) { return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0'; } static public int latestInstalledJavaX() { File[] files = new File(userHome(), ".javax").listFiles(); int v = 0; if (files != null) for (File f : files) { Matcher m = regexpMatcher("x(\\d\\d\\d?)\\.jar", f.getName()); if (m.matches()) v = Math.max(v, Integer.parseInt(m.group(1))); } return v; } static public String x30JarServerURL() { return "http://botcompany.de:8081/x30.jar"; } static public String tag(String tag) { return htag(tag); } static public String tag(String tag, Object contents, Object... params) { return htag(tag, str(contents), params); } static public String tag(String tag, StringBuilder contents, Object... params) { return htag(tag, contents, params); } static public String tag(String tag, StringBuffer contents, Object... params) { return htag(tag, contents, params); } static public boolean eitherIsA(Either e) { return e != null && e.isA(); } static public boolean checkFields(Object x, Object... data) { for (int i = 0; i < l(data); i += 2) if (neq(getOpt(x, (String) data[i]), data[i + 1])) return false; return true; } static public JComponent unwrapScrollPane(JScrollPane sp) { return sp == null ? null : (JComponent) sp.getViewport().getView(); } static public double negativeInfinity() { return Double.NEGATIVE_INFINITY; } static public Dimension getMinimumSize(final Component c) { return c == null ? null : swing(new F0() { public Dimension get() { try { return c.getMinimumSize(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getMinimumSize();"; } }); } static public String hform(Object contents, Object... params) { return htag("form", contents, params); } static public GlobalID asGlobalID(String id) { return id == null ? null : new GlobalID(id); } static public int randomID_defaultLength = 12; static public String randomID(int length) { return makeRandomID(length); } static public String randomID(Random r, int length) { return makeRandomID(r, length); } static public String randomID() { return randomID(randomID_defaultLength); } static public String randomID(Random r) { return randomID(r, randomID_defaultLength); } static public int mod(int n, int m) { return (n % m + m) % m; } static public long mod(long n, long m) { return (n % m + m) % m; } static public BigInteger mod(BigInteger n, int m) { return n.mod(bigint(m)); } static public double mod(double n, double m) { return (n % m + m) % m; } static public String htag(String tag) { return htag(tag, ""); } static public String htag(String tag, Object contents, Object... params) { String openingTag = hopeningTag(tag, params); String s = str(contents); if (empty(s) && neqic(tag, "script")) return dropLast(openingTag) + "/>"; return openingTag + s + ""; } static public boolean neqic(String a, String b) { return !eqic(a, b); } static public boolean neqic(char a, char b) { return !eqic(a, b); } static public class Value implements IF0, IFieldsToList { public A value; public Value() { } public Value(A value) { this.value = value; } public boolean equals(Object o) { if (!(o instanceof Value)) return false; Value __1 = (Value) o; return eq(value, __1.value); } public int hashCode() { int h = 82420049; h = boostHashCombine(h, _hashCode(value)); return h; } public Object[] _fieldsToList() { return new Object[] { value }; } public A get() { return value; } public String toString() { return str(get()); } } static public class T3 { public A a; public B b; public C c; public T3() { } public T3(A a, B b, C c) { this.c = c; this.b = b; this.a = a; } public T3(T3 t) { a = t.a; b = t.b; c = t.c; } public int hashCode() { return _hashCode(a) + 2 * _hashCode(b) - 4 * _hashCode(c); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof T3)) return false; T3 t = (T3) o; return eq(a, t.a) && eq(b, t.b) && eq(c, t.c); } public String toString() { return "(" + quoteBorderless(a) + ", " + quoteBorderless(b) + ", " + quoteBorderless(c) + ")"; } } static public String quoteBorderless(Object o) { if (o == null) return "null"; return quoteBorderless(str(o)); } static public String quoteBorderless(String s) { if (s == null) return "null"; StringBuilder out = new StringBuilder((int) (l(s) * 1.5)); quoteBorderless_impl(s, out); return out.toString(); } static public void quoteBorderless_impl(String s, StringBuilder out) { int l = s.length(); for (int i = 0; i < l; i++) { char c = s.charAt(i); if (c == '\\' || c == '"') out.append('\\').append(c); else if (c == '\r') out.append("\\r"); else if (c == '\n') out.append("\\n"); else out.append(c); } } }