import java.util.*; import java.util.zip.*; import java.util.List; import java.util.regex.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.table.*; import java.io.*; import java.net.*; import java.lang.reflect.*; import java.lang.ref.*; import java.lang.management.*; import java.security.*; import java.security.spec.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import java.math.*; 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.empty; import static x30_pkg.x30_util.nempty; import static x30_pkg.x30_util.fail; import static x30_pkg.x30_util.indexOf; import static x30_pkg.x30_util.getOpt; 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.get_raw; 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 static x30_pkg.x30_util.asList; import loadableUtils.utils; import static loadableUtils.utils.print_byThread; import static loadableUtils.utils._threadInfo; import static loadableUtils.utils._threadInheritInfo; import static loadableUtils.utils.dm_currentModule; import static loadableUtils.utils.dm_current_mandatory; import static loadableUtils.utils.match; import static loadableUtils.utils.getOpt_raw; import static loadableUtils.utils.setOpt; import static loadableUtils.utils.setOpt_raw; import static loadableUtils.utils.getField; import static loadableUtils.utils.fieldType; 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.struct; import static loadableUtils.utils.structure; import static loadableUtils.utils.loadPage; import static loadableUtils.utils.loadPageSilentlyWithTimeout; import static loadableUtils.utils.loadPageSilently; import static loadableUtils.utils.loadSnippet; import static loadableUtils.utils.loadSnippetQuietly; import static loadableUtils.utils.sendToLocalBot; import static loadableUtils.utils.componentPopupMenu; import static loadableUtils.utils.componentPopupMenu_top; import static loadableUtils.utils.listPopupMenu; import static loadableUtils.utils.tablePopupMenu; import static loadableUtils.utils.sexyTableWithoutDrag; import static loadableUtils.utils.dm_current_generic; import static loadableUtils.utils.dm_current_mandatory_generic; import static loadableUtils.utils.cset; import static loadableUtils.utils.DynamicObject_loading; import static loadableUtils.utils.concepts_unlisted; import static loadableUtils.utils.makePopupMenuConditional; import loadableUtils.utils.F0; import loadableUtils.utils.F1; import loadableUtils.utils.Matches; import loadableUtils.utils.BetterLabel; import loadableUtils.utils.SingleComponentPanel; import loadableUtils.utils.Snippet; import loadableUtils.utils.Q; import loadableUtils.utils.ImageSurface; import loadableUtils.utils.structure_Data; import loadableUtils.utils.RGBImage; import loadableUtils.utils.BWImage; import loadableUtils.utils.MakesBufferedImage; import loadableUtils.utils.DynamicObject; import loadableUtils.utils.Concept; import loadableUtils.utils.Concepts; import loadableUtils.utils.IConceptIndex; import loadableUtils.utils.IFieldIndex; import loadableUtils.utils.Derefable; import loadableUtils.utils.ImageSurfaceSelector; import loadableUtils.utils.DynModule; import loadableUtils.utils.DynPrintLog; import loadableUtils.utils.DynObjectTable; import loadableUtils.utils.DynImageSurface; import loadableUtils.utils.DynCalculatedList; import java.text.NumberFormat; import javax.swing.undo.UndoManager; import java.awt.datatransfer.Transferable; import javax.swing.event.AncestorListener; import javax.swing.event.AncestorEvent; import javax.swing.Timer; import java.awt.datatransfer.StringSelection; import javax.imageio.metadata.*; import javax.imageio.stream.*; import javax.net.ssl.*; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; class main { public static class Entry extends Concept { public static String _fieldOrder = "question moduleID"; public String question; public String moduleID; } public static boolean _moduleClass_Question2Module; public static class Question2Module extends DynCRUD { public Question2Module() { super(Entry.class); } public void start() { super.start(); dbIndexing(Entry.class, "question"); loadMechLists(); } public void loadMechLists() { dm_useLocalMechListCopies(); for (String listName : mechListNamesStartingWith("Questions leading to module ")) { String moduleID = firstSnippetID(listName); for (String question : mL(listName)) uniq_sync(Entry.class, "question", question, "moduleID", moduleID); } } } public static A callF(Object f, Object... args) { try { if (f instanceof String) return (A) callMC((String) f, args); return (A) x30_util.callF(f, args); } catch (Exception __e) { throw rethrow(__e); } } public static Object callMC(String method, Object... args) { return call(mc(), method, args); } public static Object call(Object o) { return callF(o); } public static A call(Object o, String method, Object... args) { return x30_util.call(o, method, args); } public static void _onLoad_initUtils() { utils.__javax = javax(); } public static void _onLoad_defaultClassFinder() { setDefaultClassFinder(new F1() { public Class get(String name) { try { Class c = findClass_fullName(name); if (c != null) return c; if (startsWith(name, "main$")) return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + substring(name, 4)); return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Class c = findClass_fullName(name);\r\n if (c != null) ret c;\r\n if (start..."; } }); } public static String programID() { return getProgramID(); } public static String programID(Object o) { return getProgramID(o); } public static volatile StringBuffer local_log = new StringBuffer(); public static volatile Appendable print_log = local_log; public static volatile int print_log_max = 1024 * 1024; public static volatile int local_log_max = 100 * 1024; public static boolean print_silent; public static Object print_byThread_lock = new Object(); public static volatile ThreadLocal print_byThread; public static volatile Object print_allThreads; public static void print() { print(""); } public static A print(String s, A o) { print((endsWithLetterOrDigit(s) ? s + ": " : s) + o); return o; } public static A print(A o) { ping_okInCleanUp(); if (print_silent) return o; String s = String.valueOf(o) + "\n"; print_noNewLine(s); return o; } public static void print_noNewLine(String s) { Object f = print_byThread == null ? null : print_byThread.get(); if (f == null) f = print_allThreads; if (f != null) if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s))) return; print_raw(s); } public static void print_raw(String 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); System.out.print(s); } public static void dbIndexing(Object... params) { db(); for (int i = 0; i < l(params); i += 2) indexConceptField((Class) params[i], (String) params[i + 1]); } public static void dm_useLocalMechListCopies() { dm_useLocallyCopiedMechLists(); } public static List mechListNamesStartingWith(String prefix) { return startingWithIC(mechListNames(), prefix); } public static String firstSnippetID(String s) { return regexpExtract("#\\d+", s); } public static List mL(String name) { return mechList_opt(name); } public static A uniq_sync(final Class c, final Object... params) { return withDBLock(new F0() { public A get() { try { return uniq(c, params); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret uniq(c, params);"; } }); } public static RuntimeException rethrow(Throwable t) { if (t instanceof Error) _handleError((Error) t); throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } public static Class mc() { return main.class; } public static Class javax() { return getJavaX(); } public static void setDefaultClassFinder(Object cf) { _defaultClassFinder_value = cf; } public static HashMap findClass_fullName_cache = new HashMap(); public static 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; } } public static boolean startsWith(String a, String b) { return a != null && a.startsWith(b); } public static boolean startsWith(String a, char c) { return nemptyString(a) && a.charAt(0) == c; } public static boolean startsWith(String a, String b, Matches m) { if (!startsWith(a, b)) return false; m.m = new String[] { substring(a, strL(b)) }; return true; } public static boolean startsWith(List a, List b) { if (a == null || listL(b) > listL(a)) return false; for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i))) return false; return true; } public static String substring(String s, int x) { return substring(s, x, strL(s)); } public static String substring(String s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; if (x >= s.length()) return ""; if (y < x) y = x; if (y > s.length()) y = s.length(); return s.substring(x, y); } public static Object _defaultClassFinder_value; public static Object _defaultClassFinder() { return _defaultClassFinder_value; } public static String programID; public static String getProgramID() { return nempty(programID) ? formatSnippetIDOpt(programID) : "?"; } public static String getProgramID(Class c) { String id = (String) getOpt(c, "programID"); if (nempty(id)) return formatSnippetID(id); return "?"; } public static String getProgramID(Object o) { return getProgramID(getMainClass(o)); } public static boolean endsWithLetterOrDigit(String s) { return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1)); } public static void ping_okInCleanUp() { if (ping_pauseAll || ping_anyActions) ping_impl(true); } public static boolean isFalse(Object o) { return eq(false, o); } public static String fixNewLines(String s) { int i = indexOf(s, '\r'); if (i < 0) return s; int l = s.length(); StringBuilder out = new StringBuilder(l); out.append(s, 0, i); for (; i < l; i++) { char c = s.charAt(i); if (c != '\r') out.append(c); else { out.append('\n'); if (i + 1 < l && s.charAt(i + 1) == '\n') ++i; } } return out.toString(); } public static void print_append(Appendable _buf, String s, int max) { try { synchronized (_buf) { _buf.append(s); if (!(_buf instanceof StringBuilder)) return; StringBuilder buf = (StringBuilder) (_buf); max /= 2; if (buf.length() > max) try { int newLength = max / 2; int ofs = buf.length() - newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } } } catch (Exception __e) { throw rethrow(__e); } } public static void db() { conceptsAndBot(); } public static void db(Integer autoSaveInterval) { conceptsAndBot(autoSaveInterval); } public static void indexConceptField(Class c, String field) { if (!isConceptFieldIndexed(c, field)) new ConceptFieldIndex(c, field); } public static void dm_useLocallyCopiedMechLists() { dm_requireModule("#1016073/MechLists"); useLocalMechListCopies(true); setOptMC("serverMechList_raw_fresh_verbose", true); setOptMC("mechList_goToCreator_dont", true); } public static List startingWithIC(Collection l, final String prefix) { return filter(unnull(l), new F1() { public Boolean get(String s) { try { return swic(s, prefix); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "swic(s, prefix)"; } }); } public static List startingWithIC(String prefix, Collection l) { return startingWithIC(l, prefix); } public static TimedCache> mechListNames_cache = new TimedCache(10.0); public static Set mechListNames() { return mechListNames_cache.get(new F0() { public Object get() { try { return asCISet(mechListNames_fresh()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret asCISet(mechListNames_fresh());"; } }); } public static String regexpExtract(String pat, String s) { if (s == null) return null; Matcher m = regexpMatcher(pat, s); return m.find() ? m.group() : null; } public static List mechList_opt(String name) { return mechList_opt_tlft(name); } public static Object withDBLock(Object r) { Lock __23 = db_mainConcepts().lock; lock(__23); try { return callF(r); } finally { unlock(__23); } } public static A withDBLock(F0 r) { return (A) withDBLock((Object) r); } public static A uniq(Class c, Object... params) { return uniqueConcept(c, params); } public static A uniq(Concepts cc, Class c, Object... params) { return uniqueConcept(cc, c, params); } public static void _handleError(Error e) { call(javax(), "_handleError", e); } public static Class __javax; public static Class getJavaX() { try { return __javax; } catch (Exception __e) { throw rethrow(__e); } } public static boolean nemptyString(String s) { return s != null && s.length() > 0; } public static int strL(String s) { return s == null ? 0 : s.length(); } public static int listL(Collection l) { return l == null ? 0 : l.size(); } public static boolean neq(Object a, Object b) { return !eq(a, b); } public static String formatSnippetIDOpt(String s) { return isSnippetID(s) ? formatSnippetID(s) : s; } public static String formatSnippetID(String id) { return "#" + parseSnippetID(id); } public static String formatSnippetID(long id) { return "#" + id; } public static Class getMainClass() { return mc(); } public static Class getMainClass(Object o) { try { if (o == null) return null; if (o instanceof Class && eq(((Class) o).getName(), "x30")) return (Class) o; return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main"); } catch (Exception __e) { throw rethrow(__e); } } public static volatile boolean ping_pauseAll; public static int ping_sleep = 100; public static volatile boolean ping_anyActions; public static Map ping_actions = newWeakHashMap(); public static ThreadLocal ping_isCleanUpThread = new ThreadLocal(); public static boolean ping() { if (ping_pauseAll || ping_anyActions) ping_impl(true); return true; } public static 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); } } public static boolean eq(Object a, Object b) { return a == null ? b == null : a == b || b != null && a.equals(b); } public static volatile boolean conceptsAndBot_running; public static void conceptsAndBot() { conceptsAndBot(null); } public static void conceptsAndBot(Integer autoSaveInterval) { if (conceptsAndBot_running) return; conceptsAndBot_running = true; try { ensureDBNotRunning(dbBotStandardName()); } catch (Throwable _e) { db_mainConcepts().dontSave = true; throw rethrow(_e); } if (autoSaveInterval != null) db_mainConcepts().persist(autoSaveInterval); else db_mainConcepts().persist(); dbBot(); } public static boolean isConceptFieldIndexed(Class c, String field) { return mainConcepts.getFieldIndex(c, field) != null; } public static String dm_requireModule(String moduleLibID) { return dm_makeModule(moduleLibID); } public static boolean useLocalMechListCopies_flag; public static boolean useLocalMechListCopies() { return useLocalMechListCopies_flag; } public static void useLocalMechListCopies(boolean flag) { useLocalMechListCopies_flag = flag; if (flag) mechMode().readMode = "localCopies"; } public static void setOptMC(String field, Object value) { setOpt(mc(), field, value); } public static List filter(Iterable c, Object pred) { if (pred instanceof F1) return filter(c, (F1) pred); List x = new ArrayList(); if (c != null) for (Object o : c) if (isTrue(callF(pred, o))) x.add(o); return x; } public static List filter(Object pred, Iterable c) { return filter(c, pred); } public static List filter(Iterable c, F1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o).booleanValue()) x.add(o); return x; } public static List filter(F1 pred, Iterable c) { return filter(c, pred); } public static String unnull(String s) { return s == null ? "" : s; } public static Collection unnull(Collection l) { return l == null ? emptyList() : l; } public static List unnull(List l) { return l == null ? emptyList() : l; } public static Map unnull(Map l) { return l == null ? emptyMap() : l; } public static Iterable unnull(Iterable i) { return i == null ? emptyList() : i; } public static A[] unnull(A[] a) { return a == null ? (A[]) new Object[0] : a; } public static BitSet unnull(BitSet b) { return b == null ? new BitSet() : b; } public static Pt unnull(Pt p) { return p == null ? new Pt() : p; } public static boolean swic(String a, String b) { return startsWithIgnoreCase(a, b); } public static boolean swic(String a, String b, Matches m) { if (!swic(a, b)) return false; m.m = new String[] { substring(a, l(b)) }; return true; } public static TreeSet asCISet(Collection c) { return toCaseInsensitiveSet(c); } public static TreeSet asCISet(String... x) { return toCaseInsensitiveSet(x); } public static List mechListNames_fresh() { boolean useLocal = false, useRemote = true; if (mergeLocalAndRemoteMechLists()) useLocal = true; else if (useLocalMechLists()) { useLocal = true; useRemote = false; } List l = null; if (useRemote) if (useLocalMechListCopies()) l = namesOfLocalMechListCopies(); else l = serverMechListNames_fresh(); if (useLocal) l = concatLists_conservative(l, localMechListNames()); return l; } public static Matcher regexpMatcher(String pat, String s) { return compileRegexp(pat).matcher(unnull(s)); } public static List mechList_opt_tlft(String name) { return tlft(mechList_opt_raw(name)); } public static volatile Concepts mainConcepts; public static Concepts db_mainConcepts() { if (mainConcepts == null) { mainConcepts = new Concepts(getDBProgramID()); mainConcepts.classFinder = _defaultClassFinder(); } return mainConcepts; } public static void lock(Lock lock) { try { ping(); if (lock == null) return; try { lock.lockInterruptibly(); } catch (InterruptedException e) { print("Locking interrupted! I probably deadlocked, oops."); printStackTrace(e); rethrow(e); } ping(); } catch (Exception __e) { throw rethrow(__e); } } public static void lock(Lock lock, String msg) { print("Locking: " + msg); lock(lock); } public static void lock(Lock lock, String msg, long timeout) { print("Locking: " + msg); lockOrFail(lock, timeout); } public static ReentrantLock lock() { return fairLock(); } public static void unlock(Lock lock, String msg) { if (lock == null) return; print("Unlocking: " + msg); lock.unlock(); } public static void unlock(Lock lock) { if (lock == null) return; lock.unlock(); } public static A uniqueConcept(Class c, Object... params) { return uniqueConcept(mainConcepts, c, params); } public static A uniqueConcept(Concepts cc, Class c, Object... params) { params = expandParams(c, params); A x = findConceptWhere(cc, c, params); if (x == null) { x = unlisted(c); csetAll(x, params); cc.register(x); } return x; } 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; } public static boolean isAWTThread() { if (isAndroid()) return false; if (isHeadless()) return false; return isAWTThread_awt(); } public static boolean isAWTThread_awt() { return SwingUtilities.isEventDispatchThread(); } public static void failIfUnlicensed() { assertTrue("license off", licensed()); } public static Thread currentThread() { return Thread.currentThread(); } public static String str(Object o) { return o == null ? "null" : o.toString(); } public static String str(char[] c) { return new String(c); } public static void ensureDBNotRunning(String name) { if (hasBot(name)) { try { String id = fsI(dropAfterSpace(name)); String framesBot = id + " Frames"; print("Trying to activate frames of running DB: " + id); if (isOK(sendOpt(framesBot, "activate frames")) && isMainProgram()) cleanKill(); } catch (Throwable __e) { _handleException(__e); } throw fail("Already running: " + name); } } public static void ensureDBNotRunning() { ensureDBNotRunning(dbBotStandardName()); } public static String dbBotStandardName() { String home = userHome(); String name = dbBotName(getDBProgramID()); if (neq(home, actualUserHome())) name += " " + quote(home); return name + "."; } public static volatile Android3 dbBot_instance; public static Android3 dbBot() { return dbBot(dbBotStandardName()); } public static Android3 dbBot(String name) { ensureDBNotRunning(name); assertNotNull(mainConcepts); return dbBot_instance = methodsBot2(name, mainConcepts, db_standardExposedMethods(), mainConcepts.lock); } public static String dm_makeModule(String moduleLibID) { return (String) callCreator("makeModule", moduleLibID); } public static MechMode mechMode_value = new MechMode(); public static MechMode mechMode() { return mechMode_value; } public static ArrayList emptyList() { return new ArrayList(); } public static ArrayList emptyList(int capacity) { return new ArrayList(max(0, capacity)); } public static ArrayList emptyList(Iterable l) { return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList(); } public static ArrayList emptyList(Class c) { return new ArrayList(); } public static Map emptyMap() { return new HashMap(); } public static boolean startsWithIgnoreCase(String a, String b) { return regionMatchesIC(a, 0, b, 0, b.length()); } public static TreeSet toCaseInsensitiveSet(Collection c) { if (isCISet(c)) return (TreeSet) c; TreeSet set = caseInsensitiveSet(); if (c != null) set.addAll(c); return set; } public static TreeSet toCaseInsensitiveSet(String... x) { TreeSet set = caseInsensitiveSet(); addAll(set, x); return set; } public static boolean mergeLocalAndRemoteMechLists_flag; public static boolean mergeLocalAndRemoteMechLists() { return mergeLocalAndRemoteMechLists_flag; } public static void mergeLocalAndRemoteMechLists(boolean flag) { mergeLocalAndRemoteMechLists_flag = flag; if (flag) { setOptMC("mechList_goToCreator_dont", true); mechMode().readMode = "mergeLocalAndRemote"; } } public static boolean useLocalMechLists_flag; public static boolean useLocalMechLists() { return useLocalMechLists_flag; } public static void useLocalMechLists(boolean flag) { useLocalMechLists_flag = flag; if (flag) mechMode().readMode = "local"; } public static List namesOfLocalMechListCopies() { return map(new F1() { public String get(File f) { try { return getString(safeUnstructMap(loadTextFile(f)), "Name"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getString(safeUnstructMap(loadTextFile(f)), 'Name)"; } }, listFilesWithExtension(remoteMechListMirrorsDir(), ".meta")); } public static List serverMechListNames_fresh() { return (List) jsonDecode(postPageSilently("http://butter.botcompany.de:8080/mech/raw/list-names", muricaCredentials())); } public static List concatLists_conservative(List a, List b) { if (empty(a)) return b; if (empty(b)) return a; return concatLists(a, b); } public static List localMechListNames() { return map("loadTextFile", listFilesWithExtension(localMechListsDir(), ".name")); } public static Map compileRegexp_cache = syncMRUCache(10); public static 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; } public static List tlft(String s) { return toLinesFullTrim(s); } public static List tlft(File f) { return toLinesFullTrim(f); } public static String mechList_opt_raw(String name) { try { Lock __60 = mechList_raw_lock; lock(__60); try { if (mechList_goToCreator() || eq(mechMode().readMode, "creator")) return (String) call(creator(), "mechList_opt_raw", name); String src = mechList_raw_cache.get(name); if (src != null) return src; src = mechList_opt_raw_fresh(name); mechList_raw_cache.put(name, unnull(src)); return src; } finally { unlock(__60); } } catch (Exception __e) { throw rethrow(__e); } } public static void _onLoad_mechList_opt_raw() { _registerAutoCloseable(vmBus_onMessage("mechList_clearCache", new VF1() { public void get(String listName) { try { if (!isTrue(mechList_clearCache_inFunction.get())) mechList_clearCache_noSend(listName); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!isTrue(mechList_clearCache_inFunction!))\r\n mechList_clearCache_noSe..."; } })); } public static String getDBProgramID_id; public static String getDBProgramID() { return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase(); } public static Throwable printStackTrace(Throwable e) { print(getStackTrace(e)); return e; } public static void printStackTrace() { printStackTrace(new Throwable()); } public static void printStackTrace(String msg) { printStackTrace(new Throwable(msg)); } public static void lockOrFail(Lock lock, long timeout) { try { ping(); if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) { String s = "Couldn't acquire lock after " + timeout + " ms."; if (lock instanceof ReentrantLock) { ReentrantLock l = (ReentrantLock) (lock); s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner"); } throw fail(s); } ping(); } catch (Exception __e) { throw rethrow(__e); } } public static ReentrantLock fairLock() { return new ReentrantLock(true); } public static Object[] expandParams(Class c, Object[] params) { if (l(params) == 1) params = new Object[] { singleFieldName(c), params[0] }; else warnIfOddCount(params); return params; } public static A findConceptWhere(Class c, Object... params) { return findConceptWhere(mainConcepts, c, params); } public static A findConceptWhere(Concepts concepts, Class c, Object... params) { 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; } public static Concept findConceptWhere(Concepts concepts, String c, Object... params) { for (Concept x : concepts.list(c)) if (checkConceptFields(x, params)) return x; return null; } public static A unlisted(Class c, Object... args) { concepts_unlisted.set(true); try { return nuObject(c, args); } finally { concepts_unlisted.set(null); } } public static int csetAll(Concept c, Object... values) { return cset(c, values); } public static ExpiringMap2 mechList_raw_cache = new ExpiringMap2(10000).setMap(ciMap()); public static Lock mechList_raw_lock = lock(); public static int mechList_raw_timeout = 60000; public static String mechList_raw(String name) { try { Lock __66 = mechList_raw_lock; lock(__66); try { if (empty(name)) return ""; String src = mechList_raw_cache.get(name); if (src != null) return src; AutoCloseable __67 = tempSetThreadLocal(loadPage_forcedTimeout_byThread, mechList_raw_timeout); try { src = mechList_raw_fresh(name); if (src != null) mechList_raw_cache.put(name, src); return src; } finally { _close(__67); } } finally { unlock(__66); } } catch (Exception __e) { throw rethrow(__e); } } public static VF2 mechList_raw_listener = new VF2() { public void get(String msg, Object arg) { try { if (eq(msg, "mechChange") && arg instanceof String) { mechList_raw_cache.remove((String) arg); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(msg, 'mechChange) && arg instanceof S) {\r\n //print(\"Got change noti..."; } }; public static void _onLoad_mechList_raw() { add(vm_busListeners_live(), mechList_raw_listener); } public static void cleanMeUp_mechList_raw() { remove(vm_busListeners_live(), mechList_raw_listener); } public static ThreadLocal mechList_clearCache_inFunction = new ThreadLocal(); public static void mechList_clearCache(String listName) { { AutoCloseable __88 = tempSetTL(mechList_clearCache_inFunction, true); try { print("Sending mech clear: " + listName); vmBus_send("mechList_clearCache", listName); } finally { _close(__88); } } mechList_clearCache_noSend(listName); } public static void mechList_clearCache_noSend(String listName) { for (String field : mcFields()) if (startsWithEndsWith(field, "mech", "_cache")) { Object o = getOptMC(field); if (o instanceof Map) removeFromMapCI_sync((Map) o, listName); } } public static String shortenSnippetID(String snippetID) { if (snippetID.startsWith("#")) snippetID = snippetID.substring(1); String httpBlaBla = "http://tinybrain.de/"; if (snippetID.startsWith(httpBlaBla)) snippetID = snippetID.substring(httpBlaBla.length()); return "" + parseLong(snippetID); } public static volatile boolean licensed_yes = true; public static boolean licensed() { if (!licensed_yes) return false; ping_okInCleanUp(); return true; } public static void licensed_off() { licensed_yes = false; } public static boolean hasBot(String searchPattern) { DialogIO io = findBot(searchPattern); if (io != null) { io.close(); return true; } else return false; } public static String fsI(String id) { return formatSnippetID(id); } public static String fsI(long id) { return formatSnippetID(id); } public static String dropAfterSpace(String s) { return s == null ? null : substring(s, 0, smartIndexOf(s, ' ')); } public static boolean isOK(String s) { s = trim(s); return swic(s, "ok ") || eqic(s, "ok") || matchStart("ok", s); } public static String sendOpt(String bot, String text, Object... args) { return sendToLocalBotOpt(bot, text, args); } public static boolean isMainProgram() { return creator() == null; } public static void cleanKill() { cleanKillVM(); } public static volatile PersistableThrowable _handleException_lastException; public static List _handleException_onException = synchroList(ll("printStackTrace2")); public static void _handleException(Throwable e) { _handleException_lastException = persistableThrowable(e); Throwable e2 = innerException(e); if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException) return; for (Object f : cloneList(_handleException_onException)) try { callF(f, e); } catch (Throwable e3) { printStackTrace2(e3); } } public static String _userHome; public static String userHome() { if (_userHome == null) { if (isAndroid()) _userHome = "/storage/sdcard0/"; else _userHome = System.getProperty("user.home"); } return _userHome; } public static File userHome(String path) { return new File(userDir(), path); } public static String dbBotName(String progIDWithCase) { return fsI_flex(progIDWithCase) + " Concepts"; } public static String actualUserHome_value; public static String actualUserHome() { if (actualUserHome_value == null) { if (isAndroid()) actualUserHome_value = "/storage/sdcard0/"; else actualUserHome_value = System.getProperty("user.home"); } return actualUserHome_value; } public static File actualUserHome(String sub) { return newFile(new File(actualUserHome()), sub); } public static String quote(Object o) { if (o == null) return "null"; return quote(str(o)); } public static String quote(String s) { if (s == null) return "null"; StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2)); quote_impl(s, out); return out.toString(); } public static void quote_impl(String s, StringBuilder out) { out.append('"'); int l = s.length(); for (int i = 0; i < l; i++) { char c = s.charAt(i); if (c == '\\' || c == '"') out.append('\\').append(c); else if (c == '\r') out.append("\\r"); else if (c == '\n') out.append("\\n"); else if (c == '\0') out.append("\\0"); else out.append(c); } out.append('"'); } public static A assertNotNull(A a) { assertTrue(a != null); return a; } public static A assertNotNull(String msg, A a) { assertTrue(msg, a != null); return a; } public static Android3 methodsBot2(String name, final Object receiver, final List exposedMethods) { return methodsBot2(name, receiver, exposedMethods, null); } public static Android3 methodsBot2(String name, final Object receiver, final List exposedMethods, final Lock lock) { Android3 android = new Android3(); android.greeting = name; android.console = false; android.responder = new Responder() { public String answer(String s, List history) { return exposeMethods2(receiver, s, exposedMethods, lock); } }; return makeBot(android); } public static List db_standardExposedMethods_list = ll("xlist", "xnew", "xset", "xdelete", "xget", "xclass", "xfullgrab", "xshutdown", "xchangeCount", "xcount"); public static List db_standardExposedMethods() { return db_standardExposedMethods_list; } public static A callCreator(String functionName, Object... args) { return (A) call(creator(), functionName, args); } public static int max(int a, int b) { return Math.max(a, b); } public static int max(int a, int b, int c) { return max(max(a, b), c); } public static long max(int a, long b) { return Math.max((long) a, b); } public static long max(long a, long b) { return Math.max(a, b); } public static double max(int a, double b) { return Math.max((double) a, b); } public static float max(float a, float b) { return Math.max(a, b); } public static double max(double a, double b) { return Math.max(a, b); } public static int max(Collection c) { int x = Integer.MIN_VALUE; for (int i : c) x = max(x, i); return x; } public static double max(double[] c) { if (c.length == 0) return Double.MIN_VALUE; double x = c[0]; for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]); return x; } public static float max(float[] c) { if (c.length == 0) return Float.MAX_VALUE; float x = c[0]; for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]); return x; } public static byte max(byte[] c) { byte x = -128; for (byte d : c) if (d > x) x = d; return x; } public static short max(short[] c) { short x = -0x8000; for (short d : c) if (d > x) x = d; return x; } public static int max(int[] c) { int x = Integer.MIN_VALUE; for (int d : c) if (d > x) x = d; return x; } public static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) { return a != null && a.regionMatches(true, offsetA, b, offsetB, len); } public static boolean isCISet(Collection l) { return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator(); } public static TreeSet caseInsensitiveSet() { return new TreeSet(caseInsensitiveComparator()); } public static TreeSet caseInsensitiveSet(Collection c) { return toCaseInsensitiveSet(c); } public static void addAll(Collection c, Iterable b) { if (c != null && b != null) for (A a : b) c.add(a); } public static boolean addAll(Collection c, Collection b) { return c != null && b != null && c.addAll(b); } public static boolean addAll(Collection c, B... b) { return c != null && c.addAll(Arrays.asList(b)); } public static List map(Iterable l, Object f) { return map(f, l); } public static List map(Object f, Iterable l) { List x = emptyList(l); if (l != null) for (Object o : l) x.add(callF(f, o)); return x; } public static List map(Iterable l, F1 f) { return map(f, l); } public static List map(F1 f, Iterable l) { List x = emptyList(l); if (l != null) for (Object o : l) x.add(callF(f, o)); return x; } public static List map(Object f, Object[] l) { return map(f, asList(l)); } public static List map(Object[] l, Object f) { return map(f, l); } public static List map(Object f, Map map) { return map(map, f); } public static List map(Map map, Object f) { List x = new ArrayList(); if (map != null) for (Object _e : map.entrySet()) { Map.Entry e = (Map.Entry) _e; x.add(callF(f, e.getKey(), e.getValue())); } return x; } public static String getString(Map map, Object key) { return map == null ? null : (String) map.get(key); } public static String getString(List l, int idx) { return (String) get(l, idx); } public static String getString(Object o, Object key) { if (o instanceof Map) return getString((Map) o, key); if (key instanceof String) return (String) getOpt(o, (String) key); throw fail("Not a string key: " + getClassName(key)); } public static Map safeUnstructMap(String s) { return safeUnstructureMap(s); } public static String loadTextFile(String fileName) { return loadTextFile(fileName, null); } public static String loadTextFile(File f, String defaultContents) { try { checkFileNotTooBigToRead(f); if (f == null || !f.exists()) return defaultContents; FileInputStream fileInputStream = new FileInputStream(f); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); return loadTextFile(inputStreamReader); } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFile(File fileName) { return loadTextFile(fileName, null); } public static String loadTextFile(String fileName, String defaultContents) { return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents); } public static 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); } public static List listFilesWithExtension(File dir, String ext) { return listFilesWithSuffix(dir, addPrefixOptIfNempty(".", ext)); } public static List listFilesWithExtension(String ext, File dir) { return listFilesWithExtension(dir, ext); } public static File remoteMechListMirrorsDir() { return javaxDataDir("Remote Mech Lists"); } public static boolean jsonDecode_useOrderedMaps = true; public static Object jsonDecode(final String text) { final List tok = jsonTok(text); if (l(tok) == 1) return null; class Y { public int i = 1; public Object parse() { String t = tok.get(i); if (t.startsWith("\"")) { String s = unquote(tok.get(i)); i += 2; return s; } if (t.equals("{")) return parseMap(); if (t.equals("[")) return this.parseList(); if (t.equals("null")) { i += 2; return null; } if (t.equals("false")) { i += 2; return false; } if (t.equals("true")) { i += 2; return true; } boolean minus = false; if (t.equals("-")) { minus = true; i += 2; t = get(tok, i); } if (isInteger(t)) { i += 2; if (eq(get(tok, i), ".")) { String x = t + "." + get(tok, i + 2); i += 4; double d = parseDouble(x); if (minus) d = -d; return d; } else { long l = parseLong(t); if (minus) l = -l; return l != (int) l ? new Long(l) : new Integer((int) l); } } throw new RuntimeException("Unknown token " + (i + 1) + ": " + t + ": " + text); } public Object parseList() { consume("["); List list = new ArrayList(); while (!tok.get(i).equals("]")) { list.add(parse()); if (tok.get(i).equals(",")) i += 2; } consume("]"); return list; } public Object parseMap() { consume("{"); Map map = jsonDecode_useOrderedMaps ? new LinkedHashMap() : new TreeMap(); while (!tok.get(i).equals("}")) { String key = unquote(tok.get(i)); i += 2; consume(":"); Object value = parse(); map.put(key, value); if (tok.get(i).equals(",")) i += 2; } consume("}"); return map; } public void consume(String s) { if (!tok.get(i).equals(s)) { String prevToken = i - 2 >= 0 ? tok.get(i - 2) : ""; String nextTokens = join(tok.subList(i, Math.min(i + 4, tok.size()))); throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")"); } i += 2; } } return new Y().parse(); } public static String postPageSilently(String url, Object... params) { return doPostSilently(litmap(params), url); } public static Object[] muricaCredentials() { String pass = muricaPassword(); return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0]; } public static List concatLists(Collection... lists) { List l = new ArrayList(); for (Collection list : lists) if (list != null) l.addAll(list); return l; } public static List concatLists(Collection> lists) { List l = new ArrayList(); for (Collection list : lists) if (list != null) l.addAll(list); return l; } public static File localMechListsDir() { return javaxDataDir("Mech Lists"); } public static Map syncMRUCache(int size) { return synchroMap(new MRUCache(size)); } public static List toLinesFullTrim(String s) { List l = new ArrayList(); for (String line : toLines(s)) if (nempty(line = trim(line))) l.add(line); return l; } public static List toLinesFullTrim(File f) { List l = new ArrayList(); for (String line : linesFromFile(f)) if (nempty(line = trim(line))) l.add(line); return l; } public static boolean mechList_goToCreator_dont; public static boolean mechList_goToCreator() { return eqOneOf(mechMode().readMode, null, "creator") && !mechList_goToCreator_dont && hasMethodNamed(creator(), "mechList_opt_raw"); } public static WeakReference creator_class; public static Object creator() { return creator_class == null ? null : creator_class.get(); } public static String mechList_opt_raw_fresh(String name) { Object readMode = mechMode().readMode; if (readMode instanceof File) { String md5Name = uniqueFileNameUsingMD5_80_v2(upper(name)); return loadTextFileFromZipFile((File) readMode, md5Name); } boolean useLocal = false, useRemote = true; if (eq(readMode, "mergeLocalAndRemote")) useLocal = true; else if (eq(readMode, "local")) { useLocal = true; useRemote = false; } String s = ""; if (useRemote) { if (eq(mechMode().readMode, "localCopies")) s = unnull(loadTextFile(remoteMechListMirrorFile(name))); else s = serverMechList_raw_fresh(name, true); } if (useLocal) s = appendNewLineIfNempty(s) + localMechList_opt_raw_fresh(name); return s; } public static Set _registerAutoCloseable_set = synchroHashSet(); public static void _registerAutoCloseable(AutoCloseable c) { addIfNotNull(_registerAutoCloseable_set, c); } public static void cleanMeUp__registerAutoCloseable() { closeAutoCloseables(getAndClearList(_registerAutoCloseable_set)); } public static AutoCloseable vmBus_onMessage(final String msg, final VF1 onMessage) { Map map = vm_busListenersByMessage_live(); synchronized (map) { Set listeners = map.get(msg); if (listeners == null) map.put(msg, listeners = syncIdentityHashSet()); return tempAdd(listeners, new VF2() { public void get(String _msg, Object arg) { try { callF(onMessage, arg); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, arg)"; } }); } } public static AutoCloseable vmBus_onMessage(String msg, final VF2 onMessage) { return vmBus_onMessage(msg, new VF1() { public void get(Object[] o) { try { callF(onMessage, first(o), second(o)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, first(o), second(o));"; } }); } public static AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) { return vmBus_onMessage(msg, runnableToVF1(onMessage)); } public static String programIDWithCase() { return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID(); } public static String getStackTrace(Throwable throwable) { lastException(throwable); return getStackTrace_noRecord(throwable); } public static String getStackTrace_noRecord(Throwable throwable) { StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); return hideCredentials(writer.toString()); } public static String getStackTrace() { return getStackTrace_noRecord(new Throwable()); } public static 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); } public static void warnIfOddCount(Object... list) { if (odd(l(list))) printStackTrace("Odd list size: " + list); } public static 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; } public static Object nuObject(String className, Object... args) { try { return nuObject(classForName(className), args); } catch (Exception __e) { throw rethrow(__e); } } public static A nuObject(Class c, Object... args) { try { if (args.length == 0) return nuObjectWithoutArguments(c); Constructor m = nuObject_findConstructor(c, args); m.setAccessible(true); return (A) m.newInstance(args); } catch (Exception __e) { throw rethrow(__e); } } public static Constructor nuObject_findConstructor(Class c, Object... args) { for (Constructor m : c.getDeclaredConstructors()) { if (!nuObject_checkArgs(m.getParameterTypes(), args, false)) continue; return m; } throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : "")); } public static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) { if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } public static Throwable printStackTrace2(Throwable e) { print(getStackTrace2(e)); return e; } public static void printStackTrace2() { printStackTrace2(new Throwable()); } public static void printStackTrace2(String msg) { printStackTrace2(new Throwable(msg)); } public static TreeMap ciMap() { return caseInsensitiveMap(); } public static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) { if (tl == null) return null; final A prev = setThreadLocal(tl, a); return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); } }; } public static String mechList_raw_fresh(String name) { return mechList_opt_raw_fresh(name); } public static 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); } } public static void add(BitSet bs, int i) { bs.set(i); } public static boolean add(Collection c, A a) { return c != null && c.add(a); } public static void add(Container c, Component x) { addToContainer(c, x); } public static Set vm_busListeners_live_cache; public static Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache; } public static Set vm_busListeners_live_load() { return vm_generalIdentityHashSet("busListeners"); } public static void remove(List l, int i) { if (l != null && i >= 0 && i < l(l)) l.remove(i); } public static void remove(Collection l, A a) { if (l != null) l.remove(a); } public static AutoCloseable tempSetTL(ThreadLocal tl, A a) { return tempSetThreadLocal(tl, a); } public static void vmBus_send(String msg, Object... args) { Object arg = empty(args) ? null : l(args) == 1 ? args[0] : args; pcallFAll(vm_busListeners_live(), msg, arg); pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg); } public static void vmBus_send(String msg) { vmBus_send(msg, (Object) null); } public static Set mcFields() { return staticFieldNames(mc()); } public static boolean startsWithEndsWith(String s, String prefix, String suffix) { return startsWith(s, prefix) && endsWith(s, suffix); } public static Object getOptMC(String field) { return getOpt(mc(), field); } public static void removeFromMapCI_sync(Map map, String key) { if (map == null) return; synchronized (getMutex(map)) { for (String k : cloneList(keys(map))) if (eqic(key, k)) map.remove(k); } } public static long parseLong(String s) { if (s == null) return 0; return Long.parseLong(dropSuffix("L", s)); } public static long parseLong(Object s) { return Long.parseLong((String) s); } public static Map findBot_cache = synchroHashMap(); public static int findBot_timeout = 5000; public static DialogIO findBot(String searchPattern) { String subBot = null; int i = searchPattern.indexOf('/'); if (i >= 0 && (isJavaIdentifier(searchPattern.substring(0, i)) || isInteger(searchPattern.substring(0, i)))) { subBot = searchPattern.substring(i + 1); searchPattern = searchPattern.substring(0, i); if (!isInteger(searchPattern)) searchPattern = "Multi-Port at " + searchPattern + "."; } if (isInteger(searchPattern)) return talkToSubBot(subBot, talkTo(parseInt(searchPattern))); if (eq(searchPattern, "remote")) return talkToSubBot(subBot, talkTo("second.tinybrain.de", 4999)); Integer port = findBot_cache.get(searchPattern); if (port != null) try { DialogIO io = talkTo("localhost", port); io.waitForLine(); String line = io.readLineNoBlock(); if (indexOfIgnoreCase(line, searchPattern) == 0) { call(io, "pushback", line); return talkToSubBot(subBot, io); } } catch (Exception e) { e.printStackTrace(); } List bots = quickBotScan(); for (ProgramScan.Program p : bots) { if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) { findBot_cache.put(searchPattern, p.port); return talkToSubBot(subBot, talkTo("localhost", p.port)); } } for (ProgramScan.Program p : bots) { String botName = firstPartOfHelloString(p.helloString); boolean isVM = startsWithIgnoreCase(p.helloString, "This is a JavaX VM."); boolean shouldRecurse = startsWithIgnoreCase(botName, "Multi-Port") || isVM; if (shouldRecurse) try { Map subBots = (Map) unstructure(sendToLocalBotQuietly(p.port, "list bots")); for (Number vport : subBots.keySet()) { String name = subBots.get(vport); if (startsWithIgnoreCase(name, searchPattern)) return talkToSubBot(vport.longValue(), talkTo("localhost", p.port)); } } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } return null; } public static 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); } public static int smartIndexOf(String s, int i, char c) { return smartIndexOf(s, c, i); } public static 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); } public static int smartIndexOf(String s, String sub) { return smartIndexOf(s, sub, 0); } public static int smartIndexOf(String s, char c) { return smartIndexOf(s, c, 0); } public static int smartIndexOf(List l, A sub) { return smartIndexOf(l, sub, 0); } public static int smartIndexOf(List l, int start, A sub) { return smartIndexOf(l, sub, start); } public static int smartIndexOf(List l, A sub, int start) { int i = indexOf(l, sub, start); return i < 0 ? l(l) : i; } public static String trim(String s) { return s == null ? null : s.trim(); } public static String trim(StringBuilder buf) { return buf.toString().trim(); } public static String trim(StringBuffer buf) { return buf.toString().trim(); } public static boolean eqic(String a, String b) { if ((a == null) != (b == null)) return false; if (a == null) return true; return a.equalsIgnoreCase(b); } public static boolean eqic(char a, char b) { if (a == b) return true; char u1 = Character.toUpperCase(a); char u2 = Character.toUpperCase(b); if (u1 == u2) return true; return Character.toLowerCase(u1) == Character.toLowerCase(u2); } public static boolean matchStart(String pat, String s) { return matchStart(pat, s, null); } public static boolean matchStart(String pat, String s, Matches matches) { if (s == null) return false; return matchStart(pat, parse3_cachedInput(s), matches); } public static boolean matchStart(String pat, List toks, Matches matches) { if (toks == null) return false; List tokpat = parse3_cachedPattern(pat); if (toks.size() < tokpat.size()) return false; String[] m = match2(tokpat, toks.subList(0, tokpat.size())); if (m == null) return false; if (matches != null) { matches.m = new String[m.length + 1]; arraycopy(m, matches.m); matches.m[m.length] = join(toks.subList(tokpat.size(), toks.size())); } return true; } public static String sendToLocalBotOpt(String bot, String text, Object... args) { if (bot == null) return null; text = format(text, args); DialogIO channel = findBot(bot); if (channel == null) { print(quote(bot) + " not found, skipping send: " + quote(text)); return null; } try { channel.readLine(); print(shorten(bot + "> " + text, 200)); channel.sendLine(text); String s = channel.readLine(); print(shorten(bot + "< " + s, 200)); return s; } catch (Throwable e) { e.printStackTrace(); return null; } finally { channel.close(); } } public static void cleanKillVM() { try { ping(); assertNotOnAWTThread(); cleanKillVM_noSleep(); Object o = new Object(); synchronized (o) { o.wait(); } } catch (Exception __e) { throw rethrow(__e); } } public static void cleanKillVM_noSleep() { call(getJavaX(), "cleanKill"); } public static List synchroList() { return Collections.synchronizedList(new ArrayList()); } public static List synchroList(List l) { return Collections.synchronizedList(l); } public static List ll(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } public static PersistableThrowable persistableThrowable(Throwable e) { return e == null ? null : new PersistableThrowable(e); } public static Throwable innerException(Throwable e) { return getInnerException(e); } public static ArrayList cloneList(Iterable l) { return l instanceof Collection ? cloneList((Collection) l) : asList(l); } public static ArrayList cloneList(Collection l) { if (l == null) return new ArrayList(); synchronized (collectionMutex(l)) { return new ArrayList(l); } } public static File userDir() { return new File(userHome()); } public static File userDir(String path) { return new File(userHome(), path); } public static String fsI_flex(String s) { return startsWithDigit(s) ? "#" + s : s; } public static File newFile(File base, String... names) { for (String name : names) base = new File(base, name); return base; } public static File newFile(String name) { return name == null ? null : new File(name); } public static boolean exposeMethods2_debug; public static String exposeMethods2(Object receiver, String s, List methodNames) { return exposeMethods2(receiver, s, methodNames, null); } public static String exposeMethods2(Object receiver, String s, List methodNames, Lock lock) { Matches m = new Matches(); if (exposeMethods2_debug) print("Received: " + s); if (match("call *", s, m)) { List l; if (isIdentifier(m.unq(0))) l = ll(m.unq(0)); else l = (List) unstructure(m.unq(0)); String method = getString(l, 0); if (!contains(methodNames, method)) throw fail("Method not allowed: " + method); if (lock != null) lock.lock(); try { if (exposeMethods2_debug) print("Calling: " + method); Object o = call(receiver, method, asObjectArray(subList(l, 1))); if (exposeMethods2_debug) print("Got: " + getClassName(o)); return ok2(structure(o)); } finally { if (lock != null) lock.unlock(); } } if (match("list methods", s)) return ok2(structure(methodNames)); return null; } public static int makeBot(String greeting) { return makeAndroid3(greeting).port; } public static Android3 makeBot(Android3 a) { makeAndroid3(a); return a; } public static Android3 makeBot(String greeting, Object responder) { Android3 a = new Android3(greeting); a.responder = makeResponder(responder); makeBot(a); return a; } public static Android3 makeBot() { return makeAndroid3(defaultBotName()); } public static Comparator caseInsensitiveComparator() { return betterCIComparator(); } public static String getClassName(Object o) { return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName(); } public static Map safeUnstructureMap(String s) { return (Map) safeUnstructure(s); } public static ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal(); public static void checkFileNotTooBigToRead(File f) { callF(checkFileNotTooBigToRead_tl.get(), f); } public static List listFilesWithSuffix(File dir, String suffix) { List l = new ArrayList(); for (File f : listFiles(dir)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix))) l.add(f); return l; } public static String addPrefixOptIfNempty(String prefix, String s) { return addPrefixIfNotEmpty2(prefix, s); } public static File javaxDataDir_dir; public static File javaxDataDir() { return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data"); } public static File javaxDataDir(String... subs) { return newFile(javaxDataDir(), subs); } public static List jsonTok(String s) { List tok = new ArrayList(); int l = l(s); int i = 0; while (i < l) { int j = i; char c; String cc; while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j + 2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); 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.isLetter(c)) do ++j; while (j < l && Character.isLetter(s.charAt(j))); else if (Character.isDigit(c)) do ++j; while (j < l && Character.isDigit(s.charAt(j))); else ++j; tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } public static 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; } public static 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 double parseDouble(String s) { return Double.parseDouble(s); } public static String join(String glue, Iterable strings) { if (strings == null) return ""; StringBuilder buf = new StringBuilder(); Iterator i = strings.iterator(); if (i.hasNext()) { buf.append(i.next()); while (i.hasNext()) buf.append(glue).append(i.next()); } return buf.toString(); } public static String join(String glue, String... strings) { return join(glue, Arrays.asList(strings)); } public static String join(Iterable strings) { return join("", strings); } public static String join(Iterable strings, String glue) { return join(glue, strings); } public static String join(String[] strings) { return join("", strings); } public static String join(String glue, Pair p) { return p == null ? "" : str(p.a) + glue + str(p.b); } public static String doPostSilently(Map urlParameters, String url) { return doPostSilently(makePostData(urlParameters), url); } public static String doPostSilently(String urlParameters, String url) { doPost_silently.set(true); return doPost(urlParameters, url); } public static HashMap litmap(Object... x) { HashMap map = new HashMap(); litmap_impl(map, x); return map; } public static void litmap_impl(Map map, Object... x) { for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null) map.put(x[i], x[i + 1]); } public static volatile boolean muricaPassword_pretendNotAuthed; public static String muricaPassword() { if (muricaPassword_pretendNotAuthed) return null; return trim(loadTextFile(muricaPasswordFile())); } public static Map synchroMap() { return synchroHashMap(); } public static Map synchroMap(Map map) { return Collections.synchronizedMap(map); } public static IterableIterator toLines(File f) { return linesFromFile(f); } public static 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; } public static int toLines_nextLineBreak(String s, int start) { for (int i = start; i < s.length(); i++) { char c = s.charAt(i); if (c == '\r' || c == '\n') return i; } return -1; } public static CloseableIterableIterator linesFromFile(File f) { try { if (!f.exists()) return emptyCloseableIterableIterator(); if (ewic(f.getName(), ".gz")) return linesFromReader(utf8bufferedReader(newGZIPInputStream(f))); return linesFromReader(utf8bufferedReader(f)); } catch (Exception __e) { throw rethrow(__e); } } public static boolean eqOneOf(Object o, Object... l) { for (Object x : l) if (eq(o, x)) return true; return false; } public static 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); } public static 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; } public static String uniqueFileNameUsingMD5_80_v2(String fullName) { return uniqueFileNameUsingMD5_80_v2(fullName, md5(fullName)); } public static String uniqueFileNameUsingMD5_80_v2(String fullName, String md5) { return takeFirst(80 - 33, fileNameEncode(fullName)) + " - " + md5; } public static String upper(String s) { return s == null ? null : s.toUpperCase(); } public static char upper(char c) { return Character.toUpperCase(c); } public static String loadTextFileFromZipFile(File inZip, String fileName) { try { if (!fileExists(inZip)) return null; try { ZipFile zip = new ZipFile(inZip); try { return loadTextFileFromZipFile(zip, fileName); } finally { _close(zip); } } catch (Throwable e) { throw fail(f2s(inZip), e); } } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFileFromZipFile(ZipFile zip, String fileName) { try { ZipEntry entry = zip.getEntry(fileName); if (entry == null) return null; InputStream fin = zip.getInputStream(entry); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copyStream(fin, baos); return fromUTF8(baos.toByteArray()); } finally { _close(fin); } } catch (Exception __e) { throw rethrow(__e); } } public static File remoteMechListMirrorFile(String listName) { return newFile(remoteMechListMirrorsDir(), uniqueFileNameUsingMD5_80_v2(upper(listName))); } public static boolean serverMechList_raw_fresh_verbose; public static String serverMechList_raw_fresh(String name) { return serverMechList_raw_fresh(name, false); } public static String serverMechList_raw_fresh(String name, boolean opt) { Lock __129 = downloadLock(); lock(__129); try { if (serverMechList_raw_fresh_verbose) print("serverMechList_raw_fresh " + name); String text = null; try { text = loadTextFile(remoteMechListMirrorFile(name)); } catch (Throwable __e) { _handleException(__e); } Object[] params = muricaCredentialsPlus("md5", md5OrNull(text), "l", l(text), "opt", opt ? 1 : 0, "withStatus", 1); String url = "http://butter.botcompany.de:8080/mech/raw/list-text/" + urlencode(name); String page = postPageSilently(url, params); Map map = jsonDecodeMap(page); boolean same = eq(map.get("Same"), true); boolean appended = eq(map.get("Appended"), true); if (serverMechList_raw_fresh_verbose) print("Mech list " + name + ": " + (appended ? "appended" : same ? "same" : "downloaded")); saveTextFile(remoteMechListMirrorMetaFile(name), struct(getMultipleKeys(map, "Name", "Status"))); if (same) return text; if (appended) text += (String) map.get("Text"); else text = (String) map.get("Text"); saveTextFile(remoteMechListMirrorFile(name), text); File nameFile = remoteMechListMirrorNameFile(name); if (!fileExists(nameFile)) { String actualName = or((String) map.get("Name"), name); saveTextFile(nameFile, actualName); } vmBus_send("remoteMechListMirrorChanged", name); return text; } finally { unlock(__129); } } public static String appendNewLineIfNempty(String s) { return empty(s) ? "" : s + "\n"; } public static String localMechList_opt_raw_fresh(String name) { return unnull(loadTextFile(localMechListFile(name))); } public static Set synchroHashSet() { return Collections.synchronizedSet(new HashSet()); } public static void addIfNotNull(Collection l, A a) { if (a != null && l != null) l.add(a); } public static void closeAutoCloseables(Collection l) { if (l != null) for (AutoCloseable c : l) { try { c.close(); } catch (Throwable __e) { _handleException(__e); } } } public static List getAndClearList(Collection l) { if (l == null) return emptyList(); synchronized (collectionMutex(l)) { List out = cloneList(l); l.clear(); return out; } } public static Map vm_busListenersByMessage_live_cache; public static Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache; } public static Map vm_busListenersByMessage_live_load() { return vm_generalHashMap("busListenersByMessage"); } public static Set syncIdentityHashSet() { return (Set) synchronizedSet(identityHashSet()); } public static AutoCloseable tempAdd(final Collection l, final 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); } }; } public static Object first(Object list) { return first((Iterable) list); } public static A first(List list) { return empty(list) ? null : list.get(0); } public static A first(A[] bla) { return bla == null || bla.length == 0 ? null : bla[0]; } public static A first(IterableIterator i) { return first((Iterator) i); } public static A first(Iterator i) { return i == null || !i.hasNext() ? null : i.next(); } public static A first(Iterable i) { if (i == null) return null; Iterator it = i.iterator(); return it.hasNext() ? it.next() : null; } public static Character first(String s) { return empty(s) ? null : s.charAt(0); } public static A first(Pair p) { return p == null ? null : p.a; } public static A second(List l) { return get(l, 1); } public static A second(A[] bla) { return bla == null || bla.length <= 1 ? null : bla[1]; } public static B second(Pair p) { return p == null ? null : p.b; } public static A third(List l) { return _get(l, 2); } public static A third(A[] bla) { return bla == null || bla.length <= 2 ? null : bla[2]; } public static VF1 runnableToVF1(final Runnable r) { return r == null ? null : new VF1() { public void get(A a) { try { r.run(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "r.run()"; } }; } public static volatile String caseID_caseID; public static String caseID() { return caseID_caseID; } public static void caseID(String id) { caseID_caseID = id; } public static String quoteUnlessIdentifierOrInteger(String s) { return quoteIfNotIdentifierOrInteger(s); } public static volatile PersistableThrowable lastException_lastException; public static PersistableThrowable lastException() { return lastException_lastException; } public static void lastException(Throwable e) { lastException_lastException = persistableThrowable(e); } public static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); } public static String hideCredentials(String url) { return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2="); } public static String hideCredentials(Object o) { return hideCredentials(str(o)); } public static Set listFields(Object c) { TreeSet fields = new TreeSet(); for (Field f : _getClass(c).getDeclaredFields()) fields.add(f.getName()); return fields; } public static String n(long l, String name) { return l + " " + trim(l == 1 ? singular(name) : getPlural(name)); } public static String n(Collection l, String name) { return n(l(l), name); } public static String n(Map m, String name) { return n(l(m), name); } public static String n(Object[] a, String name) { return n(l(a), name); } public static boolean odd(int i) { return (i & 1) != 0; } public static boolean odd(long i) { return (i & 1) != 0; } public static boolean odd(BigInteger i) { return odd(toInt(i)); } public static A cget(Object c, String field) { Object o = getOpt(c, field); if (o instanceof Concept.Ref) return (A) ((Concept.Ref) o).get(); return (A) o; } public static A cget(String field, Object c) { return cget(c, field); } public static Object deref(Object o) { if (o instanceof Derefable) o = ((Derefable) o).get(); return o; } public static Map classForName_cache = synchroHashMap(); public static Class classForName(String name) { try { Class c = classForName_cache.get(name); if (c == null) classForName_cache.put(name, c = Class.forName(name)); return c; } catch (Exception __e) { throw rethrow(__e); } } public static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap(); public static Object nuObjectWithoutArguments(String className) { try { return nuObjectWithoutArguments(classForName(className)); } catch (Exception __e) { throw rethrow(__e); } } public static 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); } } public static Constructor nuObjectWithoutArguments_findConstructor(Class c) { for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) { m.setAccessible(true); return m; } throw fail("No default constructor found in " + c.getName()); } public static List getClasses(Object[] array) { List l = new ArrayList(); for (Object o : array) l.add(_getClass(o)); return l; } public static boolean isInstanceX(Class type, Object arg) { if (type == boolean.class) return arg instanceof Boolean; if (type == int.class) return arg instanceof Integer; if (type == long.class) return arg instanceof Long; if (type == float.class) return arg instanceof Float; if (type == short.class) return arg instanceof Short; if (type == char.class) return arg instanceof Character; if (type == byte.class) return arg instanceof Byte; if (type == double.class) return arg instanceof Double; return type.isInstance(arg); } public static String getStackTrace2(Throwable e) { return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n"); } public static TreeMap caseInsensitiveMap() { return new TreeMap(caseInsensitiveComparator()); } public static A setThreadLocal(ThreadLocal tl, A value) { if (tl == null) return null; A old = tl.get(); tl.set(value); return old; } public static void addToContainer(final Container a, final Component b) { if (a != null && b != null) { swing(new Runnable() { public void run() { try { a.add(b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.add(b);"; } }); } } public static void pcallFAll(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) pcallF(f, args); } public static void pcallFAll(Iterator it, Object... args) { while (it.hasNext()) pcallF(it.next(), args); } public static Set staticFieldNames(Object o) { TreeSet fields = new TreeSet(); Class _c = _getClass(o); do { for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & Modifier.STATIC) != 0) fields.add(f.getName()); _c = _c.getSuperclass(); } while (_c != null); return fields; } public static boolean endsWith(String a, String b) { return a != null && a.endsWith(b); } public static boolean endsWith(String a, char c) { return nempty(a) && lastChar(a) == c; } public static boolean endsWith(String a, String b, Matches m) { if (!endsWith(a, b)) return false; m.m = new String[] { dropLast(l(b), a) }; return true; } public static Object getMutex(Object o) { return collectionMutex(o); } public static Set keys(Map map) { return map == null ? new HashSet() : map.keySet(); } public static Set keys(Object map) { return keys((Map) map); } public static Set keys(MultiMap mm) { return mm.keySet(); } public static String dropSuffix(String suffix, String s) { return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s; } public static Map synchroHashMap() { return Collections.synchronizedMap(new HashMap()); } public static 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; } public static DialogIO talkToSubBot(final long vport, final DialogIO io) { return talkToSubBot(String.valueOf(vport), io); } public static DialogIO talkToSubBot(final String subBot, final DialogIO io) { if (subBot == null) return io; return new talkToSubBot_IO(subBot, io); } public static class talkToSubBot_IO extends DialogIO { public String subBot; public DialogIO io; public talkToSubBot_IO(String subBot, DialogIO io) { this.io = io; this.subBot = subBot; } public boolean isStillConnected() { return io.isStillConnected(); } public String readLineImpl() { return io.readLineImpl(); } public boolean isLocalConnection() { return io.isLocalConnection(); } public Socket getSocket() { return io.getSocket(); } public void close() { io.close(); } public void sendLine(String line) { io.sendLine(format3("please forward to bot *: *", subBot, line)); } } public static DialogIO talkTo(int port) { return talkTo("localhost", port); } public static int talkTo_defaultTimeout = 10000; public static int talkTo_timeoutForReads = 0; public static ThreadLocal> talkTo_byThread = new ThreadLocal(); public static DialogIO talkTo(String ip, int port) { try { String full = ip + ":" + port; Map map = talkTo_byThread.get(); if (map != null && map.containsKey(full)) return map.get(full); if (isLocalhost(ip) && port == vmPort()) return talkToThisVM(); return new talkTo_IO(ip, port); } catch (Exception __e) { throw rethrow(__e); } } public static class talkTo_IO extends DialogIO { public String ip; public int port; public Socket s; public Writer w; public BufferedReader in; public talkTo_IO(String ip, int port) { this.port = port; this.ip = ip; try { s = new Socket(); try { if (talkTo_timeoutForReads != 0) s.setSoTimeout(talkTo_timeoutForReads); s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout); } catch (Throwable e) { throw fail("Tried talking to " + ip + ":" + port, e); } w = new OutputStreamWriter(s.getOutputStream(), "UTF-8"); in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8")); } catch (Exception __e) { throw rethrow(__e); } } public boolean isLocalConnection() { return s.getInetAddress().isLoopbackAddress(); } public boolean isStillConnected() { return !(eos || s.isClosed()); } public void sendLine(String line) { try { Lock __1396 = lock; lock(__1396); try { w.write(line + "\n"); w.flush(); } finally { unlock(__1396); } } catch (Exception __e) { throw rethrow(__e); } } public String readLineImpl() { try { return in.readLine(); } catch (Exception __e) { throw rethrow(__e); } } public void close() { try { if (!noClose) s.close(); } catch (IOException e) { } } public Socket getSocket() { return s; } } public static int parseInt(String s) { return empty(s) ? 0 : Integer.parseInt(s); } public static int parseInt(char c) { return Integer.parseInt(str(c)); } public static int indexOfIgnoreCase(List a, String b) { return indexOfIgnoreCase(a, b, 0); } public static int indexOfIgnoreCase(List a, String b, int i) { int n = l(a); for (; i < n; i++) if (eqic(a.get(i), b)) return i; return -1; } public static int indexOfIgnoreCase(String a, String b) { return indexOfIgnoreCase_manual(a, b); } public static List quickBotScan() { return ProgramScan.quickBotScan(); } public static List quickBotScan(int[] preferredPorts) { return ProgramScan.quickBotScan(preferredPorts); } public static List quickBotScan(String searchPattern) { List l = new ArrayList(); for (ProgramScan.Program p : ProgramScan.quickBotScan()) if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) l.add(p); return l; } public static String firstPartOfHelloString(String s) { int i = s.lastIndexOf('/'); return i < 0 ? s : rtrim(s.substring(0, i)); } public static Object unstructure(String text) { return unstructure(text, false); } public static Object unstructure(String text, final boolean allDynamic) { return unstructure(text, allDynamic, null); } public static int structure_internStringsLongerThan = 50; public static int unstructure_unquoteBufSize = 100; public static int unstructure_tokrefs; public abstract static class unstructure_Receiver { public abstract void set(Object o); } public static Object unstructure(String text, boolean allDynamic, Object classFinder) { if (text == null) return null; return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder); } public static Object unstructure_reader(BufferedReader reader) { return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null); } public static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object _classFinder) { final boolean debug = unstructure_debug; final class X { public int i = -1; public final Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder(); public HashMap refs = new HashMap(); public HashMap tokrefs = new HashMap(); public HashSet concepts = new HashSet(); public HashMap classesMap = new HashMap(); public List stack = new ArrayList(); public String curT; public char[] unquoteBuf = new char[unstructure_unquoteBufSize]; public String unquote(String s) { return unquoteUsingCharArray(s, unquoteBuf); } public String t() { return curT; } public String tpp() { String t = curT; consume(); return t; } public void parse(final unstructure_Receiver out) { String t = t(); int refID = 0; if (structure_isMarker(t, 0, l(t))) { refID = parseInt(t.substring(1)); consume(); } final int _refID = refID; final int tokIndex = i; parse_inner(refID, tokIndex, new unstructure_Receiver() { public void set(Object o) { if (_refID != 0) refs.put(_refID, o); if (o != null) tokrefs.put(tokIndex, o); out.set(o); } }); } public void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) { String t = t(); Class c = classesMap.get(t); if (c == null) { if (t.startsWith("\"")) { String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan); out.set(s); return; } if (t.startsWith("'")) { out.set(unquoteCharacter(tpp())); return; } if (t.equals("bigint")) { out.set(parseBigInt()); return; } if (t.equals("d")) { out.set(parseDouble()); return; } if (t.equals("fl")) { out.set(parseFloat()); return; } if (t.equals("sh")) { consume(); t = tpp(); if (t.equals("-")) { t = tpp(); out.set((short) (-parseInt(t))); return; } out.set((short) parseInt(t)); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; if (debug) print("l=" + l + ", isInt: " + isInt); out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("false") || t.equals("f")) { consume(); out.set(false); return; } if (t.equals("true") || t.equals("t")) { consume(); out.set(true); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; if (debug) print("l=" + l + ", isInt: " + isInt); out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("File")) { consume(); File f = new File(unquote(tpp())); out.set(f); return; } if (t.startsWith("r") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = refs.get(ref); if (o == null) print("Warning: unsatisfied back reference " + ref); out.set(o); return; } if (t.startsWith("t") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = tokrefs.get(ref); if (o == null) print("Warning: unsatisfied token reference " + ref); out.set(o); return; } if (t.equals("hashset")) { parseHashSet(out); return; } if (t.equals("lhs")) { parseLinkedHashSet(out); return; } if (t.equals("treeset")) { parseTreeSet(out); return; } if (eqOneOf(t, "hashmap", "hm")) { consume(); parseMap(new HashMap(), out); return; } if (t.equals("lhm")) { consume(); parseMap(new LinkedHashMap(), out); return; } if (t.equals("sync")) { consume(); if (t().equals("tm")) { consume(); { parseMap(synchronizedTreeMap(), out); return; } } if (t().equals("[")) { parseList(synchroList(), out); return; } { parseMap(synchronizedMap(), out); return; } } if (t.equals("{")) { parseMap(out); return; } if (t.equals("[")) { this.parseList(new ArrayList(), out); return; } if (t.equals("bitset")) { parseBitSet(out); return; } if (t.equals("array") || t.equals("intarray")) { parseArray(out); return; } if (t.equals("ba")) { consume(); String hex = unquote(tpp()); out.set(hexToBytes(hex)); return; } if (t.equals("boolarray")) { consume(); int n = parseInt(tpp()); String hex = unquote(tpp()); out.set(boolArrayFromBytes(hexToBytes(hex), n)); return; } if (t.equals("class")) { out.set(parseClass()); return; } if (t.equals("l")) { parseLisp(out); return; } if (t.equals("null")) { consume(); out.set(null); return; } if (eq(t, "c")) { consume("c"); t = t(); assertTrue(isJavaIdentifier(t)); concepts.add(t); } } if (eq(t, "j")) { consume("j"); out.set(parseJava()); return; } if (c == null && !isJavaIdentifier(t)) throw new RuntimeException("Unknown token " + (i + 1) + ": " + t); consume(); String className, fullClassName; if (eq(t(), ".")) { consume(); className = fullClassName = t + "." + assertIdentifier(tpp()); } else { className = t; fullClassName = "main$" + t; } if (c == null) { if (allDynamic) c = null; else c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName); if (c != null) classesMap.put(className, c); } boolean hasBracket = eq(t(), "("); if (hasBracket) consume(); boolean hasOuter = hasBracket && eq(t(), "this$1"); DynamicObject dO = null; Object o = null; final String thingName = t; if (c != null) { o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c); if (o instanceof DynamicObject) dO = (DynamicObject) o; } else { if (concepts.contains(t) && (c = findClass("Concept")) != null) o = dO = (DynamicObject) nuEmptyObject(c); else dO = new DynamicObject(); dO.className = className; if (debug) print("Made dynamic object " + t + " " + shortClassName(dO)); } if (refID != 0) refs.put(refID, o != null ? o : dO); tokrefs.put(tokIndex, o != null ? o : dO); final LinkedHashMap fields = new LinkedHashMap(); final Object _o = o; final DynamicObject _dO = dO; if (hasBracket) { stack.add(new Runnable() { public void run() { try { if (eq(t(), ")")) { consume(")"); objRead(_o, _dO, fields); out.set(_o != null ? _o : _dO); } else { final String key = unquote(tpp()); if (!eq(tpp(), "=")) throw fail("= expected, got " + t() + " after " + quote(key) + " in object " + thingName); stack.add(this); parse(new unstructure_Receiver() { public void set(Object value) { fields.put(key, value); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \")\")) {\r\n consume(\")\");\r\n objRead(_o, _dO, ..."; } }); } else { objRead(o, dO, fields); out.set(o != null ? o : dO); } } public void objRead(Object o, DynamicObject dO, Map fields) { if (o != null) if (dO != null) { if (debug) printStructure("setOptAllDyn", fields); setOptAllDyn(dO, fields); } else { setOptAll_pcall(o, fields); } else for (String field : keys(fields)) dO.fieldValues.put(intern(field), fields.get(field)); if (o != null) pcallOpt_noArgs(o, "_doneLoading"); } public void parseSet(final Set set, final unstructure_Receiver out) { this.parseList(new ArrayList(), new unstructure_Receiver() { public void set(Object o) { set.addAll((List) o); out.set(set); } }); } public void parseLisp(final unstructure_Receiver out) { throw fail("class Lisp not included"); } public void parseBitSet(final unstructure_Receiver out) { consume("bitset"); consume("{"); final BitSet bs = new BitSet(); stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); out.set(bs); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { bs.set((Integer) o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n ..."; } }); } public void parseList(final List list, final unstructure_Receiver out) { consume("["); stack.add(new Runnable() { public void run() { try { if (eq(t(), "]")) { consume("]"); out.set(list); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"]\")) {\r\n consume(\"]\");\r\n out.set(list);\r\n ..."; } }); } public void parseArray(final unstructure_Receiver out) { final String type = tpp(); consume("{"); final List list = new ArrayList(); stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); out.set(type.equals("intarray") ? toIntArray(list) : list.toArray()); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(type.equals(\"..."; } }); } public Object parseClass() { consume("class"); consume("("); String name = unquote(tpp()); consume(")"); Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass_fullName(name); if (c != null) return c; DynamicObject dO = new DynamicObject(); dO.className = "java.lang.Class"; name = dropPrefix("main$", name); dO.fieldValues.put("name", name); return dO; } public Object parseBigInt() { consume("bigint"); consume("("); String val = tpp(); if (eq(val, "-")) val = "-" + tpp(); consume(")"); return new BigInteger(val); } public Object parseDouble() { consume("d"); consume("("); String val = unquote(tpp()); consume(")"); return Double.parseDouble(val); } public Object parseFloat() { consume("fl"); String val; if (eq(t(), "(")) { consume("("); val = unquote(tpp()); consume(")"); } else { val = unquote(tpp()); } return Float.parseFloat(val); } public void parseHashSet(unstructure_Receiver out) { consume("hashset"); parseSet(new HashSet(), out); } public void parseLinkedHashSet(unstructure_Receiver out) { consume("lhs"); parseSet(new LinkedHashSet(), out); } public void parseTreeSet(unstructure_Receiver out) { consume("treeset"); parseSet(new TreeSet(), out); } public void parseMap(unstructure_Receiver out) { parseMap(new TreeMap(), out); } public Object parseJava() { String j = unquote(tpp()); Matches m = new Matches(); if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m)) return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2))); else { warn("Unknown Java object: " + j); return null; } } public void parseMap(final Map map, final unstructure_Receiver out) { consume("{"); stack.add(new Runnable() { public boolean v; public Object key; public void run() { if (v) { v = false; stack.add(this); if (!eq(tpp(), "=")) throw fail("= expected, got " + t() + " in map of size " + l(map)); parse(new unstructure_Receiver() { public void set(Object value) { map.put(key, value); if (debug) print("parseMap: Got value " + getClassName(value) + ", next token: " + quote(t())); if (eq(t(), ",")) consume(); } }); } else { if (eq(t(), "}")) { consume("}"); out.set(map); } else { v = true; stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { key = o; } }); } } } }); } public void consume() { curT = tok.next(); ++i; } public void consume(String s) { if (!eq(t(), s)) { throw fail(quote(s) + " expected, got " + quote(t())); } consume(); } public void parse_x(unstructure_Receiver out) { consume(); parse(out); while (nempty(stack)) popLast(stack).run(); } } Boolean b = DynamicObject_loading.get(); DynamicObject_loading.set(true); try { final Var v = new Var(); X x = new X(); x.parse_x(new unstructure_Receiver() { public void set(Object o) { v.set(o); } }); unstructure_tokrefs = x.tokrefs.size(); return v.get(); } finally { DynamicObject_loading.set(b); } } public static boolean unstructure_debug; public static String sendToLocalBotQuietly(String bot, String text, Object... args) { text = format3(text, args); DialogIO channel = newFindBot2(bot); if (channel == null) throw fail(quote(bot) + " not found"); try { channel.readLine(); channel.sendLine(text); String s = channel.readLine(); return s; } catch (Throwable e) { e.printStackTrace(); return null; } finally { channel.close(); } } public static String sendToLocalBotQuietly(int port, String text, Object... args) { text = format3(text, args); DialogIO channel = talkTo(port); try { channel.readLine(); channel.sendLine(text); String s = channel.readLine(); return s; } catch (Throwable e) { e.printStackTrace(); return null; } finally { if (channel != null) channel.close(); } } public static 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; } public static int min(int a, int b) { return Math.min(a, b); } public static long min(long a, long b) { return Math.min(a, b); } public static float min(float a, float b) { return Math.min(a, b); } public static float min(float a, float b, float c) { return min(min(a, b), c); } public static double min(double a, double b) { return Math.min(a, b); } public static double min(double[] c) { double x = Double.MAX_VALUE; for (double d : c) x = Math.min(x, d); return x; } public static float min(float[] c) { float x = Float.MAX_VALUE; for (float d : c) x = Math.min(x, d); return x; } public static byte min(byte[] c) { byte x = 127; for (byte d : c) if (d < x) x = d; return x; } public static short min(short[] c) { short x = 0x7FFF; for (short d : c) if (d < x) x = d; return x; } public static int min(int[] c) { int x = Integer.MAX_VALUE; for (int d : c) if (d < x) x = d; return x; } public static String asString(Object o) { return o == null ? null : o.toString(); } public static Map> parse3_cachedInput_cache = synchronizedMRUCache(100); public static synchronized List parse3_cachedInput(String s) { List tok = parse3_cachedInput_cache.get(s); if (tok == null) parse3_cachedInput_cache.put(s, tok = parse3(s)); return tok; } public static Map> parse3_cachedPattern_cache = synchronizedMRUCache(1000); public static synchronized List parse3_cachedPattern(String s) { List tok = parse3_cachedPattern_cache.get(s); if (tok == null) parse3_cachedPattern_cache.put(s, tok = parse3(s)); return tok; } public static String[] match2(List pat, List tok) { int i = pat.indexOf("..."); if (i < 0) return match2_match(pat, tok); pat = new ArrayList(pat); pat.set(i, "*"); while (pat.size() < tok.size()) { pat.add(i, "*"); pat.add(i + 1, ""); } return match2_match(pat, tok); } public static String[] match2_match(List pat, List tok) { List result = new ArrayList(); if (pat.size() != tok.size()) { return null; } for (int i = 1; i < pat.size(); i += 2) { String p = pat.get(i), t = tok.get(i); if (eq(p, "*")) result.add(t); else if (!equalsIgnoreCase(unquote(p), unquote(t))) return null; } return result.toArray(new String[result.size()]); } public static void arraycopy(Object[] a, Object[] b) { int n = min(a.length, b.length); for (int i = 0; i < n; i++) b[i] = a[i]; } public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) { System.arraycopy(src, srcPos, dest, destPos, n); } public static String format(String pat, Object... args) { return format3(pat, args); } public static int shorten_default = 100; public static String shorten(String s) { return shorten(s, shorten_default); } public static String shorten(String s, int max) { return shorten(s, max, "..."); } public static String shorten(String s, int max, String shortener) { if (s == null) return ""; if (max < 0) return s; return s.length() <= max ? s : substring(s, 0, min(s.length(), max - l(shortener))) + shortener; } public static String shorten(int max, String s) { return shorten(s, max); } public static void assertNotOnAWTThread() { assertFalse("Can't do this in AWT thread", isAWTThread()); } public static Throwable getInnerException(Throwable e) { if (e == null) return null; while (e.getCause() != null) e = e.getCause(); return e; } public static Throwable getInnerException(Runnable r) { return getInnerException(getException(r)); } public static Object collectionMutex(Object o) { String c = className(o); if (eq(c, "java.util.TreeMap$KeySet")) c = className(o = getOpt(o, "m")); else if (eq(c, "java.util.HashMap$KeySet")) c = className(o = get_raw(o, "this$0")); if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap")) c = className(o = get_raw(o, "m")); return o; } public static boolean startsWithDigit(String s) { return nempty(s) && isDigit(s.charAt(0)); } public static boolean isIdentifier(String s) { return isJavaIdentifier(s); } public static boolean contains(Collection c, Object o) { return c != null && c.contains(o); } public static boolean contains(Object[] x, Object o) { if (x != null) for (Object a : x) if (eq(a, o)) return true; return false; } public static boolean contains(String s, char c) { return s != null && s.indexOf(c) >= 0; } public static boolean contains(String s, String b) { return s != null && s.indexOf(b) >= 0; } public static boolean contains(BitSet bs, int i) { return bs != null && bs.get(i); } public static Object[] asObjectArray(List l) { return toObjectArray(l); } public static List subList(List l, int startIndex) { return subList(l, startIndex, l(l)); } public static List subList(List l, int startIndex, int endIndex) { if (l == null) return null; startIndex = Math.max(0, startIndex); endIndex = Math.min(l(l), endIndex); if (startIndex >= endIndex) return ll(); return l.subList(startIndex, endIndex); } public static String ok2(String s) { return "ok " + s; } public static boolean makeAndroid3_disable; public static class Android3 { public String greeting; public boolean publicOverride; public int startPort = 5000; public Responder responder; public boolean console = true; public boolean quiet; public boolean daemon = false; public boolean incomingSilent = false; public int incomingPrintLimit = 200; public boolean useMultiPort = true; public boolean recordHistory; public boolean verbose; public int answerPrintLimit = 500; public boolean newLineAboveAnswer, newLineBelowAnswer; public int port; public long vport; public DialogHandler handler; public ServerSocket server; public Android3(String greeting) { this.greeting = greeting; } public Android3() { } public synchronized void dispose() { if (server != null) { try { server.close(); } catch (IOException e) { print("[internal] " + e); } server = null; } if (vport != 0) { try { print("Disposing " + this); removeFromMultiPort(vport); vport = 0; } catch (Throwable __e) { _handleException(__e); } } } public String toString() { return "Bot: " + greeting + " [vport " + vport + "]"; } } public abstract static class Responder { public abstract String answer(String s, List history); } public static Android3 makeAndroid3(final String greeting) { return makeAndroid3(new Android3(greeting)); } public static Android3 makeAndroid3(final String greeting, Responder responder) { Android3 android = new Android3(greeting); android.responder = responder; return makeAndroid3(android); } public static Android3 makeAndroid3(final Android3 a) { if (makeAndroid3_disable) return a; if (a.responder == null) a.responder = new Responder() { public String answer(String s, List history) { return callStaticAnswerMethod(s, history); } }; if (!a.quiet) print("[bot] " + a.greeting); if (a.console && (readLine_noReadLine || makeAndroid3_consoleInUse())) a.console = false; record(a); if (a.useMultiPort) a.vport = addToMultiPort(a.greeting, makeAndroid3_verboseResponder(a)); if (a.console) makeAndroid3_handleConsole(a); if (a.useMultiPort) return a; a.handler = makeAndroid3_makeDialogHandler(a); if (a.quiet) startDialogServer_quiet.set(true); try { a.port = a.daemon ? startDialogServerOnPortAboveDaemon(a.startPort, a.handler) : startDialogServerOnPortAbove(a.startPort, a.handler); } finally { startDialogServer_quiet.set(null); } a.server = startDialogServer_serverSocket; return a; } public static void makeAndroid3_handleConsole(final Android3 a) { if (!a.quiet) print("You may also type on this console."); startThread(new Runnable() { public void run() { try { List history = new ArrayList(); while (licensed()) { String line; try { line = readLine(); } catch (Throwable e) { print(getInnerMessage(e)); break; } if (line == null) break; { history.add(line); history.add(makeAndroid3_getAnswer(line, history, a)); } } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "List history = new ArrayList();\r\n while (licensed()) {\r\n Stri..."; } }); } public static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) { return new DialogHandler() { public void run(final DialogIO io) { if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) { io.sendLine("Sorry, not allowed"); return; } String dialogID = randomID(8); io.sendLine(a.greeting + " / Your ID: " + dialogID); List history = new ArrayList(); while (io.isStillConnected()) { if (io.waitForLine()) { final String line = io.readLineNoBlock(); String s = dialogID + " at " + now() + ": " + quote(line); if (!a.incomingSilent) print(shorten(s, a.incomingPrintLimit)); if (eq(line, "bye")) { io.sendLine("bye stranger"); return; } Matches m = new Matches(); if (a.recordHistory) history.add(line); String answer; if (match3("this is a continuation of talk *", s, m) || match3("hello bot! this is a continuation of talk *", s, m)) { dialogID = unquote(m.m[0]); answer = "ok"; } else try { makeAndroid3_io.set(io); answer = makeAndroid3_getAnswer(line, history, a); } finally { makeAndroid3_io.set(null); } if (a.recordHistory) history.add(answer); io.sendLine(answer); } } } }; } public static String makeAndroid3_getAnswer(String line, List history, Android3 a) { String answer, originalAnswer; try { originalAnswer = a.responder.answer(line, history); answer = makeAndroid3_fallback(line, history, originalAnswer); } catch (Throwable e) { e = getInnerException(e); printStackTrace(e); originalAnswer = answer = e.toString(); } if (!a.incomingSilent) { if (originalAnswer == null) originalAnswer = "?"; if (a.newLineAboveAnswer) print(); print(">" + dropFirst(indentx(2, shorten(rtrim(originalAnswer), a.answerPrintLimit)))); if (a.newLineBelowAnswer) print(); } return answer; } public static String makeAndroid3_fallback(String s, List history, String answer) { if (answer == null && match3("what is your pid", s)) return getPID(); if (answer == null && match3("what is your program id", s)) return getProgramID(); if (match3("get injection id", s)) return getInjectionID(); if (answer == null) answer = "?"; if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0) answer = quote(answer); return answer; } public static boolean makeAndroid3_consoleInUse() { if (isTrue(vm_generalMap_get("consoleInUse"))) return true; for (Object o : record_list) if (o instanceof Android3 && ((Android3) o).console) return true; return false; } public static Responder makeAndroid3_verboseResponder(final Android3 a) { return new Responder() { public String answer(String s, List history) { if (a.verbose) print("> " + shorten(s, a.incomingPrintLimit)); String answer = a.responder.answer(s, history); if (a.verbose) print("< " + shorten(answer, a.incomingPrintLimit)); return answer; } }; } public static ThreadLocal makeAndroid3_io = new ThreadLocal(); public static Android3 makeAndroid3() { return makeAndroid3(getProgramTitle() + "."); } public static String makeResponder_callAnswerMethod(Object bot, String s, List history) { String answer = (String) callOpt(bot, "answer", s, history); if (answer == null) answer = (String) callOpt(bot, "answer", s); return answer; } public static Responder makeResponder(final Object bot) { if (bot instanceof Responder) return (Responder) bot; if (bot instanceof String) { String f = (String) (bot); return new Responder() { public String answer(String s, List history) { String answer = (String) callOptMC((String) bot, s, history); if (answer == null) answer = (String) callOptMC((String) bot, s); return answer; } }; } return new Responder() { public String answer(String s, List history) { return makeResponder_callAnswerMethod(bot, s, history); } }; } public static String defaultBotName() { return getProgramTitle() + "."; } public static betterCIComparator_C betterCIComparator_instance; public static betterCIComparator_C betterCIComparator() { if (betterCIComparator_instance == null) betterCIComparator_instance = new betterCIComparator_C(); return betterCIComparator_instance; } public static 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; } } public static Object safeUnstructure(String s) { return unstructure(s, true); } public static File[] listFiles(File dir) { File[] files = dir.listFiles(); return files == null ? new File[0] : files; } public static File[] listFiles(String dir) { return listFiles(new File(dir)); } public static boolean endsWithIgnoreCase(String a, String b) { int la = l(a), lb = l(b); return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb); } public static boolean endsWithIgnoreCase(String a, String b, Matches m) { if (!endsWithIgnoreCase(a, b)) return false; m.m = new String[] { substring(a, 0, l(a) - l(b)) }; return true; } public static String addPrefixIfNotEmpty2(String prefix, String s) { return empty(s) ? "" : addPrefix(prefix, s); } public static String makePostData(Map map) { List l = new ArrayList(); for (Map.Entry e : map.entrySet()) { String key = (String) (e.getKey()); Object val = e.getValue(); if (val != null) { String value = str(val); l.add(urlencode(key) + "=" + urlencode((value))); } } return join("&", l); } public static String makePostData(Object... params) { return makePostData(litorderedmap(params)); } public static ThreadLocal doPost_silently = new ThreadLocal(); public static ThreadLocal doPost_timeout = new ThreadLocal(); public static String doPost(Map urlParameters, String url) { return doPost(makePostData(urlParameters), url); } public static String doPost(String urlParameters, String url) { try { URL _url = new URL(url); ping(); return doPost(urlParameters, _url.openConnection(), _url); } catch (Exception __e) { throw rethrow(__e); } } public static String doPost(String urlParameters, URLConnection conn, URL url) { try { boolean silently = isTrue(optParam(doPost_silently)); Long timeout = optParam(doPost_timeout); setHeaders(conn); int l = lUtf8(urlParameters); if (!silently) print("Sending POST request: " + hideCredentials(url) + " (" + l + " bytes)"); if (timeout != null) setURLConnectionTimeouts(conn, timeout); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", str(l)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); writer.write(urlParameters); writer.flush(); loadPage_charset.set("UTF-8"); String contents = loadPage(conn, url, false); writer.close(); return contents; } catch (Exception __e) { throw rethrow(__e); } } public static File muricaPasswordFile() { return new File(javaxSecretDir(), "murica/muricaPasswordFile"); } public static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; public static CloseableIterableIterator emptyCloseableIterableIterator() { return emptyCloseableIterableIterator_instance; } public static boolean ewic(String a, String b) { return endsWithIgnoreCase(a, b); } public static boolean ewic(String a, String b, Matches m) { return endsWithIgnoreCase(a, b, m); } public static CloseableIterableIterator linesFromReader(Reader r) { final BufferedReader br = bufferedReader(r); return iteratorFromFunction_f0_autoCloseable(new F0() { public String get() { try { return readLineFromReaderWithClose(br); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret readLineFromReaderWithClose(br);"; } }, _wrapIOCloseable(r)); } public static BufferedReader utf8bufferedReader(InputStream in) { try { return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in)); } catch (Exception __e) { throw rethrow(__e); } } public static BufferedReader utf8bufferedReader(File f) { try { return utf8bufferedReader(newFileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } public static GZIPInputStream newGZIPInputStream(File f) { return gzInputStream(f); } public static GZIPInputStream newGZIPInputStream(InputStream in) { return gzInputStream(in); } public static String md5(String text) { try { if (text == null) return "-"; return bytesToHex(md5_impl(toUtf8(text))); } catch (Exception __e) { throw rethrow(__e); } } public static String md5(byte[] data) { if (data == null) return "-"; return bytesToHex(md5_impl(data)); } public static MessageDigest md5_md; public static byte[] md5_impl(byte[] data) { try { return MessageDigest.getInstance("MD5").digest(data); } catch (Exception __e) { throw rethrow(__e); } } public static String md5(File file) { return md5OfFile(file); } public static List takeFirst(List l, int n) { return l(l) <= n ? l : newSubListOrSame(l, 0, n); } public static List takeFirst(int n, List l) { return takeFirst(l, n); } public static String takeFirst(int n, String s) { return substring(s, 0, n); } public static String takeFirst(String s, int n) { return substring(s, 0, n); } public static List takeFirst(int n, Iterable i) { List l = new ArrayList(); Iterator it = i.iterator(); for (int _repeat_1579 = 0; _repeat_1579 < n; _repeat_1579++) { if (it.hasNext()) l.add(it.next()); else break; } return l; } public static String fileNameEncode_safeChars = " ()[]#,!"; public static String fileNameEncode(String s) { StringBuilder buf = new StringBuilder(); int n = l(s); for (int i = 0; i < n; i++) { char c = s.charAt(i); if (contains(fileNameEncode_safeChars, c)) buf.append(c); else buf.append(urlencode(str(c))); } return str(buf); } public static boolean fileExists(String path) { return path != null && new File(path).exists(); } public static boolean fileExists(File f) { return f != null && f.exists(); } public static String f2s(File f) { return f == null ? null : f.getAbsolutePath(); } public static String f2s(java.nio.file.Path p) { return p == null ? null : f2s(p.toFile()); } public static void copyStream(InputStream in, OutputStream out) { try { byte[] buf = new byte[65536]; while (true) { int n = in.read(buf); if (n <= 0) return; out.write(buf, 0, n); } } catch (Exception __e) { throw rethrow(__e); } } public static String fromUTF8(byte[] bytes) { return fromUtf8(bytes); } public static Lock downloadLock_lock = fairLock(); public static Lock downloadLock() { return downloadLock_lock; } public static Object[] muricaCredentialsPlus(Object... params) { return concatArrays(muricaCredentials(), params); } public static String md5OrNull(String s) { return s == null ? null : md5(s); } public static String urlencode(String x) { try { return URLEncoder.encode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static Map jsonDecodeMap(String s) { Object o = jsonDecode(s); if (o instanceof List && empty((List) o)) return new HashMap(); if (o instanceof Map) return (Map) o; else throw fail("Not a JSON map: " + s); } public static File saveTextFile(String fileName, String contents) throws IOException { CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)"); try { 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; } finally { action.done(); } } public static File saveTextFile(File fileName, String contents) { try { saveTextFile(fileName.getPath(), contents); return fileName; } catch (Exception __e) { throw rethrow(__e); } } public static File remoteMechListMirrorMetaFile(String listName) { return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".meta"); } public static Map getMultipleKeys(Map map, A... keys) { Map map2 = similarEmptyMap(map); if (map != null) for (A key : keys) map2.put(key, map.get(key)); return map2; } public static File remoteMechListMirrorNameFile(String listName) { return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".name"); } public static A or(A a, A b) { return a != null ? a : b; } public static File localMechListFile(String listName) { return newFile(localMechListsDir(), uniqueFileNameUsingMD5_80_v2(listName) + ".text"); } public static Set synchronizedSet() { return synchroHashSet(); } public static Set synchronizedSet(Set set) { return Collections.synchronizedSet(set); } public static Set identityHashSet() { return Collections.newSetFromMap(new IdentityHashMap()); } public static A _get(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } public static Object _get(Object o, String field) { return get(o, field); } public static A _get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } public static String quoteIfNotIdentifierOrInteger(String s) { if (s == null) return null; return isJavaIdentifier(s) || isInteger(s) ? s : quote(s); } public static Class _getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } public static Class _getClass(Object o) { return o == null ? null : o instanceof Class ? (Class) o : o.getClass(); } public static Class _getClass(Object realm, String name) { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } public static Map singular_specials = litmap("children", "child", "images", "image", "chess", "chess"); public static Set singular_specials2 = litset("time", "machine", "line"); public static String singular(String s) { if (s == null) return null; { String _a_194 = singular_specials.get(s); if (!empty(_a_194)) return _a_194; } 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; } public static List getPlural_specials = ll("sheep", "fish"); public static String getPlural(String s) { if (containsIgnoreCase(getPlural_specials, s)) return s; if (ewic(s, "y")) return dropSuffixIgnoreCase("y", s) + "ies"; if (ewic(s, "ss")) return s + "es"; if (ewic(s, "s")) return s; return s + "s"; } public static int toInt(Object o) { if (o == null) return 0; if (o instanceof Number) return ((Number) o).intValue(); if (o instanceof String) return parseInt((String) o); throw fail("woot not int: " + getClassName(o)); } public static int toInt(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } public static Throwable unwrapTrivialExceptionWraps(Throwable e) { if (e == null) return e; while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause(); return e; } public static String replacePrefix(String prefix, String replacement, String s) { if (!startsWith(s, prefix)) return s; return replacement + substring(s, l(prefix)); } public static Throwable innerException2(Throwable e) { if (e == null) return null; while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause(); return e; } public static Object swing(Object f) { return swingAndWait(f); } public static A swing(F0 f) { return (A) swingAndWait(f); } public static Object pcallF(Object f, Object... args) { return pcallFunction(f, args); } public static A pcallF(F0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { return null; } } public static B pcallF(F1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { return null; } } public static char lastChar(String s) { return empty(s) ? '\0' : s.charAt(l(s) - 1); } public static String[] dropLast(String[] a, int n) { n = Math.min(n, a.length); String[] b = new String[a.length - n]; System.arraycopy(a, 0, b, 0, b.length); return b; } public static List dropLast(List l) { return subList(l, 0, l(l) - 1); } public static List dropLast(int n, List l) { return subList(l, 0, l(l) - n); } public static List dropLast(Iterable l) { return dropLast(asList(l)); } public static String dropLast(String s) { return substring(s, 0, l(s) - 1); } public static String dropLast(String s, int n) { return substring(s, 0, l(s) - n); } public static String dropLast(int n, String s) { return dropLast(s, n); } public static boolean isLocalhost(String ip) { return isLoopbackIP(ip) || eqic(ip, "localhost"); } public static int vmPort() { return myVMPort(); } public static DialogIO talkToThisVM() { return new talkToThisVM_IO(); } public static class talkToThisVM_IO extends DialogIO { public List answers = ll(thisVMGreeting()); public boolean isLocalConnection() { return true; } public boolean isStillConnected() { return true; } public int getPort() { return vmPort(); } public void sendLine(String line) { answers.add(or2(sendToThisVM_newThread(line), "?")); } public String readLineImpl() { try { return popFirst(answers); } catch (Exception __e) { throw rethrow(__e); } } public void close() { } public Socket getSocket() { return null; } } public static int indexOfIgnoreCase_manual(String a, String b) { int la = l(a), lb = l(b); if (la < lb) return -1; int n = la - lb; loop: for (int i = 0; i <= n; i++) { for (int j = 0; j < lb; j++) { char c1 = a.charAt(i + j), c2 = b.charAt(j); if (!eqic(c1, c2)) continue loop; } return i; } return -1; } public static String rtrim(String s) { if (s == null) return null; int i = s.length(); while (i > 0 && " \t\r\n".indexOf(s.charAt(i - 1)) >= 0) --i; return i < s.length() ? s.substring(0, i) : s; } public static Producer javaTokC_noMLS_iterator(final String s) { return javaTokC_noMLS_iterator(s, 0); } public static Producer javaTokC_noMLS_iterator(final String s, final int startIndex) { return new Producer() { public final int l = s.length(); public int i = startIndex; public String next() { if (i >= l) return null; 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; } i = j; if (i >= l) return null; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { ++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 ++j; String t = quickSubstring(s, i, j); i = j; return t; } }; } public static Producer javaTokC_noMLS_onReader(final BufferedReader r) { final class X implements Producer { public StringBuilder buf = new StringBuilder(); public char c, d, e = 'x'; public X() { nc(); nc(); nc(); } public void nc() { try { c = d; d = e; if (e == '\0') return; int i = r.read(); e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i; } catch (Exception __e) { throw rethrow(__e); } } public void ncSave() { if (c != '\0') { buf.append(c); nc(); } } public String next() { while (c != '\0') { if (c == ' ' || c == '\t' || c == '\r' || c == '\n') nc(); else if (c == '/' && d == '*') { do nc(); while (c != '\0' && !(c == '*' && d == '/')); nc(); nc(); } else if (c == '/' && d == '/') { do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0); } else break; } if (c == '\0') return null; if (c == '\'' || c == '"') { char opener = c; ncSave(); while (c != '\0') { if (c == opener || c == '\n') { ncSave(); break; } else if (c == '\\') { ncSave(); ncSave(); } else ncSave(); } } else if (Character.isJavaIdentifierStart(c)) do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\''); else if (Character.isDigit(c)) { do ncSave(); while (Character.isDigit(c)); if (c == 'L') ncSave(); } else ncSave(); String t = buf.toString(); buf.setLength(0); return t; } } return new X(); } public static String unquoteUsingCharArray(String s, char[] buf) { 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(); if (l > buf.length) return unquote(s); int n = 0; 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++; } } buf[n++] = (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); char[] x = Character.toChars(code); int lx = x.length; for (int j = 0; j < lx; j++) buf[n++] = x[j]; i += 5; continue; default: ch = nextChar; } i++; } buf[n++] = ch; } return new String(buf, 0, n); } } return s; } public static boolean structure_isMarker(String s, int i, int j) { if (i >= j) return false; if (s.charAt(i) != 'm') return false; ++i; while (i < j) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } public static String internIfLongerThan(String s, int l) { return s == null ? null : l(s) >= l ? intern(s) : s; } public static char unquoteCharacter(String s) { assertTrue(s.startsWith("'") && s.length() > 1); return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length() - 1 : s.length()) + "\"").charAt(0); } public static float parseFloat(String s) { return Float.parseFloat(s); } public static boolean isLongConstant(String s) { if (!s.endsWith("L")) return false; s = s.substring(0, l(s) - 1); return isInteger(s); } public static SortedMap synchronizedTreeMap() { return synchroTreeMap(); } public static List parseList(String s) { return (List) safeUnstructure(s); } public static Map synchronizedMap() { return synchroMap(); } public static Map synchronizedMap(Map map) { return synchroMap(map); } public static 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; } public static boolean[] boolArrayFromBytes(byte[] a, int n) { boolean[] b = new boolean[n]; int m = min(n, l(a) * 8); for (int i = 0; i < m; i++) b[i] = (a[i / 8] & 1 << (i & 7)) != 0; return b; } public static String assertIdentifier(String s) { return assertIsIdentifier(s); } public static A nuStubInnerObject(Class c) { return nuStubInnerObject(c, null); } public static A nuStubInnerObject(Class c, Object classFinder) { try { Class outerType = getOuterClass(c, classFinder); Constructor m = c.getDeclaredConstructor(outerType); m.setAccessible(true); return (A) m.newInstance(new Object[] { null }); } catch (Exception __e) { throw rethrow(__e); } } public static Map nuEmptyObject_cache = newDangerousWeakHashMap(); public static A nuEmptyObject(Class c) { try { Constructor ctr; synchronized (nuEmptyObject_cache) { ctr = nuEmptyObject_cache.get(c); if (ctr == null) { nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c)); ctr.setAccessible(true); } } try { return (A) ctr.newInstance(); } catch (InstantiationException e) { if (empty(e.getMessage())) if ((c.getModifiers() & Modifier.ABSTRACT) != 0) throw fail("Can't instantiate abstract class " + className(c), e); else throw fail("Can't instantiate " + className(c), e); else throw rethrow(e); } } catch (Exception __e) { throw rethrow(__e); } } public static Constructor nuEmptyObject_findConstructor(Class c) { for (Constructor m : c.getDeclaredConstructors()) if (m.getParameterTypes().length == 0) return m; throw fail("No default constructor declared in " + c.getName()); } public static HashMap findClass_cache = new HashMap(); public static 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; } } public static String shortClassName(Object o) { if (o == null) return null; Class c = o instanceof Class ? (Class) o : o.getClass(); String name = c.getName(); return shortenClassName(name); } public static void printStructure(String prefix, Object o) { if (endsWithLetter(prefix)) prefix += ": "; print(prefix + structureForUser(o)); } public static void printStructure(Object o) { print(structureForUser(o)); } public static void setOptAllDyn(DynamicObject o, Map fields) { if (fields == null) return; HashMap fieldMap = instanceFieldsMap(o); for (Map.Entry e : fields.entrySet()) { String field = e.getKey(); Object val = e.getValue(); boolean has = fieldMap.containsKey(field); if (has) setOpt(o, field, val); else { o.fieldValues.put(intern(field), val); } } } public static void setOptAll_pcall(Object o, Map fields) { if (fields == null) return; for (String field : keys(fields)) try { setOpt(o, field, fields.get(field)); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } public static void setOptAll_pcall(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]; try { setOpt(o, field, value); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } } public static String intern(String s) { return fastIntern(s); } public static void pcallOpt_noArgs(Object o, String method) { try { callOpt_noArgs(o, method); } catch (Throwable __e) { _handleException(__e); } } public static int[] toIntArray(List l) { int[] a = new int[l(l)]; for (int i = 0; i < a.length; i++) a[i] = l.get(i); return a; } public static String dropPrefix(String prefix, String s) { return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s; } public static boolean jmatch(String pat, String s) { return jmatch(pat, s, null); } public static boolean jmatch(String pat, String s, Matches matches) { if (s == null) return false; return jmatch(pat, javaTok(s), matches); } public static boolean jmatch(String pat, List toks) { return jmatch(pat, toks, null); } public static boolean jmatch(String pat, List toks, Matches matches) { List tokpat = javaTok(pat); String[] m = match2(tokpat, toks); if (m == null) return false; else { if (matches != null) matches.m = m; return true; } } public static boolean warn_on = true; public static void warn(String s) { if (warn_on) print("Warning: " + s); } public static void warn(String s, List warnings) { warn(s); if (warnings != null) warnings.add(s); } public static A popLast(List l) { return liftLast(l); } public static Map newFindBot2_cache = synchroHashMap(); public static boolean newFindBot2_verbose; public static DialogIO newFindBot2(String name) { Integer port = newFindBot2_cache.get(name); if (port != null) { if (newFindBot2_verbose) print("newFindBot2: testing " + name + " => " + port); DialogIO io = talkTo(port); String q = format("has bot *", name); String s = io.ask(q); if (match("yes", s)) { io = talkToSubBot(name, io); call(io, "pushback", "?"); return io; } newFindBot2_cache.remove(name); if (newFindBot2_verbose) print("newFindBot2: dropping " + name + " => " + port); } DialogIO io = findBot(name); if (io != null) { newFindBot2_cache.put(name, io.getPort()); if (newFindBot2_verbose) print("newFindBot2: remembering " + name + " => " + port); } return io; } public static String baseClassName(String className) { return substring(className, className.lastIndexOf('.') + 1); } public static String baseClassName(Object o) { return baseClassName(getClassName(o)); } public static String prependIfNempty(String prefix, String s) { return empty(s) ? s : prefix + s; } public static Map synchronizedMRUCache(int maxSize) { return synchroMap(new MRUCache(maxSize)); } public static List parse3(String s) { return dropPunctuation(javaTokPlusPeriod(s)); } public static boolean equalsIgnoreCase(String a, String b) { return eqic(a, b); } public static boolean equalsIgnoreCase(char a, char b) { return eqic(a, b); } public static void assertFalse(Object o) { if (!(eq(o, false))) throw fail(str(o)); } public static boolean assertFalse(boolean b) { if (b) throw fail("oops"); return b; } public static boolean assertFalse(String msg, boolean b) { if (b) throw fail(msg); return b; } public static Throwable getException(Runnable r) { try { callF(r); return null; } catch (Throwable e) { return e; } } public static String className(Object o) { return getClassName(o); } public static boolean isDigit(char c) { return Character.isDigit(c); } public static Object[] toObjectArray(Collection c) { List l = asList(c); return l.toArray(new Object[l.size()]); } public static void removeFromMultiPort(long vport) { if (vport == 0) return; for (Object port : getMultiPorts()) call(port, "removePort", vport); } public static String callStaticAnswerMethod(List bots, String s) { for (Object c : bots) try { String answer = callStaticAnswerMethod(c, s); if (!empty(answer)) return answer; } catch (Throwable e) { print("Error calling " + getProgramID(c)); e.printStackTrace(); } return null; } public static String callStaticAnswerMethod(Object c, String s) { String answer = (String) callOpt(c, "answer", s, litlist(s)); if (answer == null) answer = (String) callOpt(c, "answer", s); return emptyToNull(answer); } public static String callStaticAnswerMethod(String s) { return callStaticAnswerMethod(mc(), s); } public static String callStaticAnswerMethod(String s, List history) { return callStaticAnswerMethod(mc(), s, history); } public static String callStaticAnswerMethod(Object c, String s, List history) { String answer = (String) callOpt(c, "answer", s, history); if (answer == null) answer = (String) callOpt(c, "answer", s); return emptyToNull(answer); } public static List record_list = synchroList(); public static void record(Object o) { record_list.add(o); } public static Object addToMultiPort_responder; public static long addToMultiPort(final String botName) { return addToMultiPort(botName, new Object() { public String answer(String s, List history) { String answer = (String) (callOpt(getMainClass(), "answer", s, history)); if (answer != null) return answer; answer = (String) callOpt(getMainClass(), "answer", s); if (answer != null) return answer; if (match3("get injection id", s)) return getInjectionID(); return null; } }); } public static long addToMultiPort(final String botName, final Object responder) { addToMultiPort_responder = responder; startMultiPort(); List ports = getMultiPorts(); if (ports == null) return 0; if (ports.isEmpty()) throw fail("No multiports!"); if (ports.size() > 1) print("Multiple multi-ports. Using last one."); Object port = last(ports); Object responder2 = new Object() { public String answer(String s, List history) { if (match3("get injection id", s)) return getInjectionID(); if (match3("your name", s)) return botName; return (String) call(responder, "answer", s, history); } }; record(responder2); return (Long) call(port, "addResponder", botName, responder2); } public static AtomicInteger dialogServer_clients = new AtomicInteger(); public static boolean dialogServer_printConnects; public static ThreadLocal startDialogServer_quiet = new ThreadLocal(); public static Set dialogServer_knownClients = synchroTreeSet(); public static int startDialogServerOnPortAbove(int port, DialogHandler handler) { while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler)) ++port; return port; } public static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) { while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler, true)) ++port; return port; } public static void startDialogServer(int port, DialogHandler handler) { if (!startDialogServerIfPortAvailable(port, handler)) throw fail("Can't start dialog server on port " + port); } public static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) { return startDialogServerIfPortAvailable(port, handler, false); } public static ServerSocket startDialogServer_serverSocket; public static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); } catch (IOException e) { return false; } final ServerSocket _serverSocket = serverSocket; startDialogServer_serverSocket = serverSocket; Thread thread = new Thread("Socket accept port " + port) { public void run() { try { while (true) { try { final Socket s = _serverSocket.accept(); String client = s.getInetAddress().toString(); if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) { print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet()); dialogServer_knownClients.add(client); } String threadName = "Handling client " + s.getInetAddress(); Thread t2 = new Thread(threadName) { public void run() { try { final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8"); final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8")); DialogIO io = new DialogIO() { public boolean isLocalConnection() { return s.getInetAddress().isLoopbackAddress(); } public boolean isStillConnected() { return !(eos || s.isClosed()); } public void sendLine(String line) { try { w.write(line + "\n"); w.flush(); } catch (Exception __e) { throw rethrow(__e); } } public String readLineImpl() { try { return in.readLine(); } catch (Exception __e) { throw rethrow(__e); } } public void close() { try { s.close(); } catch (IOException e) { } } public Socket getSocket() { return s; } }; try { handler.run(io); } finally { if (!io.noClose) s.close(); } } catch (IOException e) { print("[internal] " + e); } finally { } } }; t2.setDaemon(true); t2.start(); } catch (SocketTimeoutException e) { } } } catch (IOException e) { print("[internal] " + e); } } }; if (daemon) thread.setDaemon(true); thread.start(); if (!isTrue(getAndClearThreadLocal(startDialogServer_quiet))) print("Dialog server on port " + port + " started."); return true; } public static Thread startThread(Object runnable) { return startThread(defaultThreadName(), runnable); } public static Thread startThread(String name, Object runnable) { runnable = wrapAsActivity(runnable); return startThread(newThread(toRunnable(runnable), name)); } public static Thread startThread(Thread t) { _registerThread(t); t.start(); return t; } public static volatile boolean readLine_noReadLine; public static String readLine_lastInput; public static String readLine_prefix = "[] "; public static String readLine() { if (readLine_noReadLine) return null; String s = readLineHidden(); if (s != null) { readLine_lastInput = s; print(readLine_prefix + s); } return s; } public static String getInnerMessage(Throwable e) { if (e == null) return null; return getInnerException(e).getMessage(); } public static boolean publicCommOn() { return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication"))); } public static int randomID_defaultLength = 12; public static String randomID(int length) { return makeRandomID(length); } public static String randomID() { return randomID(randomID_defaultLength); } public static long now_virtualTime; public static long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } public static boolean match3(String pat, String s) { return match3(pat, s, null); } public static boolean match3(String pat, String s, Matches matches) { if (pat == null || s == null) return false; return match3(pat, parse3_cachedInput(s), matches); } public static boolean match3(String pat, List toks, Matches matches) { List tokpat = parse3_cachedPattern(pat); return match3(tokpat, toks, matches); } public static boolean match3(List tokpat, List toks, Matches matches) { String[] m = match2(tokpat, toks); if (m == null) return false; if (matches != null) matches.m = m; return true; } public static String[] dropFirst(int n, String[] a) { return drop(n, a); } public static String[] dropFirst(String[] a) { return drop(1, a); } public static Object[] dropFirst(Object[] a) { return drop(1, a); } public static List dropFirst(List l) { return dropFirst(1, l); } public static List dropFirst(int n, Iterable i) { return dropFirst(n, toList(i)); } public static List dropFirst(Iterable i) { return dropFirst(toList(i)); } public static List dropFirst(int n, List l) { return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size())); } public static List dropFirst(List l, int n) { return dropFirst(n, l); } public static String dropFirst(int n, String s) { return substring(s, n); } public static String dropFirst(String s) { return substring(s, 1); } public static String indentx(String s) { return indentx(indent_default, s); } public static String indentx(int n, String s) { return dropSuffix(repeat(' ', n), indent(n, s)); } public static String indentx(String indent, String s) { return dropSuffix(indent, indent(indent, s)); } public static String processID_cached; public static String getPID() { if (processID_cached == null) { String name = ManagementFactory.getRuntimeMXBean().getName(); processID_cached = name.replaceAll("@.*", ""); } return processID_cached; } public static String getInjectionID() { return (String) call(getJavaX(), "getInjectionID", getMainClass()); } public static A vm_generalMap_get(Object key) { return (A) vm_generalMap().get(key); } public static String getProgramTitle() { return getProgramName(); } public static Object callOptMC(String method, Object... args) { return callOpt(mc(), method, args); } public static String addPrefix(String prefix, String s) { return s.startsWith(prefix) ? s : prefix + s; } public static LinkedHashMap litorderedmap(Object... x) { LinkedHashMap map = new LinkedHashMap(); litmap_impl(map, x); return map; } public static A optParam(ThreadLocal tl, A defaultValue) { return optPar(tl, defaultValue); } public static A optParam(ThreadLocal tl) { return optPar(tl); } public static A optParam(Object[] opt, String name, A defaultValue) { if (!even(l(opt))) throw fail("Odd parameter length"); for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name)) return (A) opt[i + 1]; return defaultValue; } public static A optParam(Object[] opt, String name) { return optParam(opt, name, null); } public static 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) { } } public static int lUtf8(String s) { return l(utf8(s)); } public static 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; } public static File javaxSecretDir_dir; public static File javaxSecretDir() { return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret"); } public static File javaxSecretDir(String sub) { return newFile(javaxSecretDir(), sub); } public static BufferedReader bufferedReader(Reader r) { return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r); } public static CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) { class IFF2 extends CloseableIterableIterator { public A a; public boolean done; 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(); } public static String readLineFromReaderWithClose(BufferedReader r) { try { String s = r.readLine(); if (s == null) r.close(); return s; } catch (Exception __e) { throw rethrow(__e); } } public static AutoCloseable _wrapIOCloseable(final AutoCloseable c) { return c == null ? null : new AutoCloseable() { public String toString() { return "c.close();\r\n _registerIO(c, null, false);"; } public void close() throws Exception { c.close(); _registerIO(c, null, false); } }; } public static A _registerIOWrap(A wrapper, Object wrapped) { return wrapper; } public static FileInputStream newFileInputStream(File path) throws IOException { return newFileInputStream(path.getPath()); } public static FileInputStream newFileInputStream(String path) throws IOException { FileInputStream f = new FileInputStream(path); _registerIO(f, path, true); return f; } public static int gzInputStream_defaultBufferSize = 65536; public static GZIPInputStream gzInputStream(File f) { try { return gzInputStream(new FileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } public static GZIPInputStream gzInputStream(File f, int bufferSize) { try { return gzInputStream(new FileInputStream(f), bufferSize); } catch (Exception __e) { throw rethrow(__e); } } public static GZIPInputStream gzInputStream(InputStream in) { return gzInputStream(in, gzInputStream_defaultBufferSize); } public static GZIPInputStream gzInputStream(InputStream in, int bufferSize) { try { return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in); } catch (Exception __e) { throw rethrow(__e); } } 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(); } public static byte[] toUtf8(String s) { try { return s.getBytes("UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } public static boolean md5OfFile_verbose; public static String md5OfFile(String path) { return md5OfFile(newFile(path)); } public static String md5OfFile(File f) { try { if (!f.exists()) return "-"; if (md5OfFile_verbose) print("Getting MD5 of " + f); MessageDigest md5 = MessageDigest.getInstance("MD5"); FileInputStream in = new FileInputStream(f); try { byte[] buf = new byte[65536]; int l; while (true) { l = in.read(buf); if (l <= 0) break; md5.update(buf, 0, l); } return bytesToHex(md5.digest()); } finally { _close(in); } } catch (Exception __e) { throw rethrow(__e); } } public static List newSubListOrSame(List l, int startIndex) { return newSubListOrSame(l, startIndex, l(l)); } public static List newSubListOrSame(List l, int startIndex, int endIndex) { if (l == null) return null; startIndex = max(0, startIndex); endIndex = min(l(l), endIndex); if (startIndex >= endIndex) return ll(); if (startIndex == 0 && endIndex == l(l)) return l; return cloneList(l.subList(startIndex, endIndex)); } public static String fromUtf8(byte[] bytes) { try { return new String(bytes, "UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } public static Object[] concatArrays(Object[]... arrays) { int l = 0; for (Object[] a : arrays) l += l(a); Object[] x = new Object[l]; int i = 0; for (Object[] a : arrays) if (a != null) { System.arraycopy(a, 0, x, i, l(a)); i += l(a); } return x; } public static List beginCriticalAction_inFlight = synchroList(); public static class CriticalAction { public String description; public CriticalAction() { } public CriticalAction(String description) { this.description = description; } public void done() { beginCriticalAction_inFlight.remove(this); } } public static CriticalAction beginCriticalAction(String description) { ping(); CriticalAction c = new CriticalAction(description); beginCriticalAction_inFlight.add(c); return c; } public static void cleanMeUp_beginCriticalAction() { int n = 0; while (nempty(beginCriticalAction_inFlight)) { int m = l(beginCriticalAction_inFlight); if (m != n) { n = m; try { print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description"))); } catch (Throwable __e) { _handleException(__e); } } sleepInCleanUp(10); } } 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; } public static void 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(); } } catch (Exception __e) { throw rethrow(__e); } } public static FileOutputStream newFileOutputStream(File path) throws IOException { return newFileOutputStream(path.getPath()); } public static FileOutputStream newFileOutputStream(String path) throws IOException { return newFileOutputStream(path, false); } public static FileOutputStream newFileOutputStream(File path, boolean append) throws IOException { return newFileOutputStream(path.getPath(), append); } public static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException { mkdirsForFile(path); FileOutputStream f = new FileOutputStream(path, append); _registerIO(f, path, true); return f; } public static Map similarEmptyMap(Map m) { if (m instanceof TreeMap) return new TreeMap(((TreeMap) m).comparator()); if (m instanceof LinkedHashMap) return new LinkedHashMap(); return new HashMap(); } public static Class getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } public static Class getClass(Object o) { return o instanceof Class ? (Class) o : o.getClass(); } public static Class getClass(Object realm, String name) { try { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } catch (Exception __e) { throw rethrow(__e); } } public static String classNameToVM(String name) { return name.replace(".", "$"); } public static HashSet litset(A... items) { return lithashset(items); } public static String afterLastSpace(String s) { return s == null ? null : substring(s, s.lastIndexOf(' ') + 1); } public static boolean containsIgnoreCase(Collection l, String s) { if (l != null) for (String x : l) if (eqic(x, s)) return true; return false; } public static boolean containsIgnoreCase(String[] l, String s) { if (l != null) for (String x : l) if (eqic(x, s)) return true; return false; } public static boolean containsIgnoreCase(String s, char c) { return indexOfIgnoreCase(s, String.valueOf(c)) >= 0; } public static boolean containsIgnoreCase(String a, String b) { return indexOfIgnoreCase(a, b) >= 0; } public static String dropSuffixIgnoreCase(String suffix, String s) { return ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } public static void swingAndWait(Runnable r) { try { if (isAWTThread()) r.run(); else EventQueue.invokeAndWait(addThreadInfoToRunnable(r)); } catch (Exception __e) { throw rethrow(__e); } } public static Object swingAndWait(final Object f) { if (isAWTThread()) return callF(f); else { final Var result = new Var(); swingAndWait(new Runnable() { public void run() { try { result.set(callF(f)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; } }); return result.get(); } } public static Object pcallFunction(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); } return null; } public static boolean isLoopbackIP(String ip) { return eq(ip, "127.0.0.1"); } public static int myVMPort() { List records = (List) (get(getJavaX(), "record_list")); Object android = records.get(records.size() - 1); return (Integer) get(android, "port"); } public static String thisVMGreeting() { List record_list = (List) (get(getJavaX(), "record_list")); Object android = first(record_list); return getString(android, "greeting"); } public static String or2(String a, String b) { return nempty(a) ? a : b; } public static String or2(String a, String b, String c) { return or2(or2(a, b), c); } public static String sendToThisVM_newThread(String s, Object... args) { final String _s = format(s, args); try { return (String) evalInNewThread(new F0() { public Object get() { try { return callStaticAnswerMethod(getJavaX(), _s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret callStaticAnswerMethod(getJavaX(), _s);"; } }); } catch (Throwable e) { e = getInnerException(e); printStackTrace(e); return str(e); } } public static A popFirst(List l) { if (empty(l)) return null; A a = first(l); l.remove(0); return a; } public static A popFirst(Collection l) { if (empty(l)) return null; A a = first(l); l.remove(a); return a; } public static String quickSubstring(String s, int i, int j) { if (i == j) return ""; return s.substring(i, j); } public static NavigableMap synchroTreeMap() { return Collections.synchronizedNavigableMap(new TreeMap()); } public static 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; } public static String assertIsIdentifier(String s) { if (!isIdentifier(s)) throw fail("Not an identifier: " + quote(s)); return s; } public static Class getOuterClass(Class c) { return getOuterClass(c, null); } public static Class getOuterClass(Class c, Object classFinder) { try { String s = c.getName(); int i = s.lastIndexOf('$'); String name = substring(s, 0, i); if (classFinder != null) return (Class) callF(classFinder, name); return Class.forName(name); } catch (Exception __e) { throw rethrow(__e); } } public static String shortenClassName(String name) { if (name == null) return null; int i = lastIndexOf(name, "$"); if (i < 0) i = lastIndexOf(name, "."); return i < 0 ? name : substring(name, i + 1); } public static boolean endsWithLetter(String s) { return nempty(s) && isLetter(last(s)); } public static String structureForUser(Object o) { return beautifyStructure(struct_noStringSharing(o)); } public static HashMap instanceFieldsMap(Object o) { Class c = o.getClass(); HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } return map; } public static Method fastIntern_method; public static String fastIntern(String s) { try { if (s == null) return null; if (fastIntern_method == null) { fastIntern_method = findMethodNamed(javax(), "internPerProgram"); if (fastIntern_method == null) upgradeJavaXAndRestart(); } return (String) fastIntern_method.invoke(null, s); } catch (Exception __e) { throw rethrow(__e); } } public static Map> callOpt_noArgs_cache = newDangerousWeakHashMap(); public static Object callOpt_noArgs(Object o, String method) { try { if (o == null) return null; if (o instanceof Class) return callOpt(o, method); Class c = o.getClass(); HashMap map; synchronized (callOpt_noArgs_cache) { map = callOpt_noArgs_cache.get(c); if (map == null) map = callOpt_noArgs_makeCache(c); } Method m = map.get(method); return m != null ? m.invoke(o) : null; } catch (Exception __e) { throw rethrow(__e); } } public static HashMap callOpt_noArgs_makeCache(Class c) { HashMap map = new HashMap(); Class _c = c; do { for (Method m : c.getDeclaredMethods()) if (m.getParameterTypes().length == 0) { m.setAccessible(true); String name = m.getName(); if (!map.containsKey(name)) map.put(name, m); } _c = _c.getSuperclass(); } while (_c != null); callOpt_noArgs_cache.put(c, map); return map; } public static int javaTok_n, javaTok_elements; public static boolean javaTok_opt; public static List javaTok(String s) { ++javaTok_n; ArrayList tok = new ArrayList(); int l = s == null ? 0 : 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; } 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) { 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)) || "'".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; tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } public static List javaTok(List tok) { return javaTokWithExisting(join(tok), tok); } public static A liftLast(List l) { if (l.isEmpty()) return null; int i = l(l) - 1; A a = l.get(i); l.remove(i); return a; } public static List dropPunctuation_keep = litlist("*", "<", ">"); public static List dropPunctuation(List tok) { tok = new ArrayList(tok); for (int i = 1; i < tok.size(); i += 2) { String t = tok.get(i); if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) { tok.set(i - 1, tok.get(i - 1) + tok.get(i + 1)); tok.remove(i); tok.remove(i); i -= 2; } } return tok; } public static String dropPunctuation(String s) { return join(dropPunctuation(nlTok(s))); } public static List javaTokPlusPeriod(String s) { List tok = new ArrayList(); int l = s.length(); int i = 0; while (i < l) { int j = i; char c; String cc; while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j + 2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); cc = s.substring(i, Math.min(i + 2, l)); if (c == (char) 0x201C || c == (char) 0x201D) c = '"'; if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { char _c = s.charAt(j); if (_c == (char) 0x201C || _c == (char) 0x201D) _c = '"'; if (_c == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } if (j - 1 >= i + 1) { tok.add(opener + s.substring(i + 1, j - 1) + opener); i = j; continue; } } 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))); else if (cc.equals("[[")) { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (cc.equals("[=") && 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 if (s.substring(j, Math.min(j + 3, l)).equals("...")) j += 3; else if (c == '$' || c == '#') do ++j; while (j < l && Character.isDigit(s.charAt(j))); else ++j; tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } public static List getMultiPorts() { return (List) callOpt(getJavaX(), "getMultiPorts"); } public static ArrayList litlist(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } public static String emptyToNull(String s) { return eq(s, "") ? null : s; } public static Map emptyToNull(Map map) { return empty(map) ? null : map; } public static void startMultiPort() { List mp = getMultiPorts(); if (mp != null && mp.isEmpty()) { nohupJavax("#1001639"); throw fail("Upgrading JavaX, please restart this program afterwards."); } } public static A last(List l) { return empty(l) ? null : l.get(l.size() - 1); } public static char last(String s) { return empty(s) ? '#' : s.charAt(l(s) - 1); } public static int last(int[] a) { return l(a) != 0 ? a[l(a) - 1] : 0; } public static A last(A[] a) { return l(a) != 0 ? a[l(a) - 1] : null; } public static A last(Iterator it) { A a = null; while (it.hasNext()) { ping(); a = it.next(); } return a; } public static Set synchroTreeSet() { return Collections.synchronizedSet(new TreeSet()); } public static boolean forbiddenPort(int port) { return port == 5037; } public static A getAndClearThreadLocal(ThreadLocal tl) { A a = tl.get(); tl.set(null); return a; } public static String defaultThreadName_name; public static String defaultThreadName() { if (defaultThreadName_name == null) defaultThreadName_name = "A thread by " + programID(); return defaultThreadName_name; } public static Runnable wrapAsActivity(Object r) { return toRunnable(r); } public static Thread newThread(Object runnable) { return new Thread(_topLevelErrorHandling(toRunnable(runnable))); } public static Thread newThread(Object runnable, String name) { if (name == null) name = defaultThreadName(); return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name); } public static Thread newThread(String name, Object runnable) { return newThread(runnable, name); } public static Runnable toRunnable(final Object o) { if (o instanceof Runnable) return (Runnable) o; return new Runnable() { public void run() { try { callF(o); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; } }; } public static Map _registerThread_threads; public static Object _onRegisterThread; public static Thread _registerThread(Thread t) { if (_registerThread_threads == null) _registerThread_threads = newWeakHashMap(); _registerThread_threads.put(t, true); vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc())); callF(_onRegisterThread, t); return t; } public static void _registerThread() { _registerThread(Thread.currentThread()); } public static String readLineHidden() { try { if (get(javax(), "readLine_reader") == null) set(javax(), "readLine_reader", new BufferedReader(new InputStreamReader(System.in, "UTF-8"))); try { return ((BufferedReader) get(javax(), "readLine_reader")).readLine(); } finally { consoleClearInput(); } } catch (Exception __e) { throw rethrow(__e); } } public static String makeRandomID(int length) { return makeRandomID(length, defaultRandomGenerator()); } public static 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); } public static 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; } public static 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; } public static ArrayList toList(A[] a) { return asList(a); } public static ArrayList toList(int[] a) { return asList(a); } public static ArrayList toList(Set s) { return asList(s); } public static ArrayList toList(Iterable s) { return asList(s); } public static String repeat(char c, int n) { n = Math.max(n, 0); char[] chars = new char[n]; for (int i = 0; i < n; i++) chars[i] = c; return new String(chars); } public static List repeat(A a, int n) { n = Math.max(n, 0); List l = new ArrayList(n); for (int i = 0; i < n; i++) l.add(a); return l; } public static List repeat(int n, A a) { return repeat(a, n); } public static int indent_default = 2; public static String indent(int indent) { return repeat(' ', indent); } public static String indent(int indent, String s) { return indent(repeat(' ', indent), s); } public static String indent(String indent, String s) { return indent + s.replace("\n", "\n" + indent); } public static String indent(String s) { return indent(indent_default, s); } public static List indent(String indent, List lines) { List l = new ArrayList(); for (String s : lines) l.add(indent + s); return l; } public static Map vm_generalMap_map; public static Map vm_generalMap() { if (vm_generalMap_map == null) vm_generalMap_map = (Map) get(javax(), "generalMap"); return vm_generalMap_map; } public static String getProgramName_cache; public static String getProgramName() { Lock __808 = downloadLock(); lock(__808); try { if (getProgramName_cache == null) getProgramName_cache = getSnippetTitleOpt(programID()); return getProgramName_cache; } finally { unlock(__808); } } public static void _onLoad_getProgramName() { startThread(new Runnable() { public void run() { try { getProgramName(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getProgramName();"; } }); } public static A optPar(ThreadLocal tl, A defaultValue) { A a = tl.get(); if (a != null) { tl.set(null); return a; } return defaultValue; } public static A optPar(ThreadLocal tl) { return optPar(tl, null); } public static A optPar(Object[] params, String name) { return optParam(params, name); } public static A optPar(Object[] params, String name, A defaultValue) { return optParam(params, name, defaultValue); } public static boolean even(int i) { return (i & 1) == 0; } public static boolean even(long i) { return (i & 1) == 0; } public static String getComputerID_quick() { return computerID(); } public static byte[] utf8(String s) { return toUtf8(s); } public static void _registerIO(Object object, String path, boolean opened) { } public static String n2(long l) { return formatWithThousands(l); } public static String n2(Collection l) { return n2(l(l)); } public static String n2(double l, String singular) { return n2(l, singular, singular + "s"); } public static String n2(double l, String singular, String plural) { if (fraction(l) == 0) return n2((long) l, singular, plural); else return l + " " + plural; } public static String n2(long l, String singular, String plural) { return n_fancy2(l, singular, plural); } public static String n2(long l, String singular) { return n_fancy2(l, singular, singular + "s"); } public static String n2(Collection l, String singular) { return n2(l(l), singular); } public static String n2(Collection l, String singular, String plural) { return n_fancy2(l, singular, plural); } public static String n2(Map m, String singular, String plural) { return n_fancy2(m, singular, plural); } public static String n2(Map m, String singular) { return n2(l(m), singular); } public static String n2(Object[] a, String singular) { return n2(l(a), singular); } public static String n2(Object[] a, String singular, String plural) { return n_fancy2(a, singular, plural); } public static List collect(Collection c, String field) { return collectField(c, field); } public static List collect(String field, Collection c) { return collectField(c, field); } public static void sleepInCleanUp(long ms) { try { if (ms < 0) return; Thread.sleep(ms); } catch (Exception __e) { throw rethrow(__e); } } public static HashSet lithashset(A... items) { HashSet set = new HashSet(); for (A a : items) set.add(a); return set; } public static 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); } } public static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map())); public static HashMap getOpt_special; public static Object getOpt_cached(Object o, String field) { try { if (o == null) return null; Class c = o.getClass(); HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } if (map == getOpt_special) { if (o instanceof Class) return getOpt((Class) o, field); if (o instanceof Map) return ((Map) o).get(field); } Field f = map.get(field); if (f != null) return f.get(o); if (o instanceof DynamicObject) return ((DynamicObject) o).fieldValues.get(field); return null; } catch (Exception __e) { throw rethrow(__e); } } public static HashMap getOpt_makeCache(Class c) { HashMap map; if (isSubtypeOf(c, Map.class)) map = getOpt_special; else { map = new HashMap(); Class _c = c; do { for (Field f : _c.getDeclaredFields()) { f.setAccessible(true); String name = f.getName(); if (!map.containsKey(name)) map.put(name, f); } _c = _c.getSuperclass(); } while (_c != null); } if (getOpt_cache != null) getOpt_cache.put(c, map); return map; } public static Runnable addThreadInfoToRunnable(final Object r) { final Object info = _threadInfo(); return info == null ? asRunnable(r) : new Runnable() { public void run() { try { _inheritThreadInfo(info); callF(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_inheritThreadInfo(info); callF(r);"; } }; } public static Object callFunction(Object f, Object... args) { return callF(f, args); } public static Object evalInNewThread(final Object f) { final Flag flag = new Flag(); final Var var = new Var(); final Var exception = new Var(); startThread(new Runnable() { public void run() { try { try { var.set(callF(f)); } catch (Throwable e) { exception.set(e); } flag.raise(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n var.set(callF(f));\r\n } catch (Throwable e) {\r\n exception..."; } }); flag.waitUntilUp(); if (exception.has()) throw rethrow(exception.get()); return var.get(); } public static int charDiff(char a, char b) { return (int) a - (int) b; } public static int charDiff(String a, char b) { return charDiff(stringToChar(a), b); } public static int lastIndexOf(String a, String b) { return a == null || b == null ? -1 : a.lastIndexOf(b); } public static int lastIndexOf(String a, char b) { return a == null ? -1 : a.lastIndexOf(b); } public static boolean isLetter(char c) { return Character.isLetter(c); } public static String beautifyStructure(String s) { List tok = javaTok(s); structure_addTokenMarkers(tok); jreplace(tok, "lhm", ""); return join(tok); } public static String struct_noStringSharing(Object o) { structure_Data d = new structure_Data(); d.noStringSharing = true; return structure(o, d); } public static 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); } public static Method findMethodNamed(Class c, String method) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) { m.setAccessible(true); return m; } c = c.getSuperclass(); } return null; } public static void upgradeJavaXAndRestart() { run("#1001639"); restart(); sleep(); } public static String javaTok_substringN(String s, int i, int j) { if (i == j) return ""; if (j == i + 1 && s.charAt(i) == ' ') return " "; return s.substring(i, j); } public static String javaTok_substringC(String s, int i, int j) { return s.substring(i, j); } public static List javaTokWithExisting(String s, List existing) { ++javaTok_n; int nExisting = javaTok_opt && existing != null ? existing.size() : 0; ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList(); int l = s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; 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; } public static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) { return t.length() == j - i && s.regionMatches(i, t, 0, j - i); } public static List nlTok(String s) { return javaTokPlusPeriod(s); } public static 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);"; } }); } public static 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);"; } }); } public static Runnable _topLevelErrorHandling(final Runnable runnable) { final Object info = _threadInfo(); return new Runnable() { public void run() { try { try { _threadInheritInfo(info); runnable.run(); } catch (Throwable __e) { _handleException(__e); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }"; } }; } public static WeakReference weakRef(A a) { return newWeakReference(a); } public static void set(Object o, String field, Object value) { if (o instanceof Class) set((Class) o, field, value); else try { Field f = set_findField(o.getClass(), field); f.setAccessible(true); smartSet(f, o, value); } catch (Exception e) { throw new RuntimeException(e); } } public static void set(Class c, String field, Object value) { try { Field f = set_findStaticField(c, field); f.setAccessible(true); smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } public static Field set_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } public static Field set_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } public static void consoleClearInput() { consoleSetInput(""); } public static Random defaultRandomGenerator() { return ThreadLocalRandom.current(); } public static String getSnippetTitleOpt(String s) { return isSnippetID(s) ? getSnippetTitle(s) : s; } public static String _computerID; public static Lock computerID_lock = lock(); public static String computerID() { if (_computerID == null) { Lock __1201 = computerID_lock; lock(__1201); 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(__1201); } } return _computerID; } public static String formatWithThousands(long l) { return formatWithThousandsSeparator(l); } public static double fraction(double d) { return d % 1; } public static String n_fancy2(long l, String singular, String plural) { return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural); } public static String n_fancy2(Collection l, String singular, String plural) { return n_fancy2(l(l), singular, plural); } public static String n_fancy2(Map m, String singular, String plural) { return n_fancy2(l(m), singular, plural); } public static String n_fancy2(Object[] a, String singular, String plural) { return n_fancy2(l(a), singular, plural); } public static List collectField(Collection c, String field) { List l = new ArrayList(); if (c != null) for (Object a : c) l.add(getOpt(a, field)); return l; } public static List collectField(String field, Collection c) { return collectField(c, field); } public static void clear(Collection c) { if (c != null) c.clear(); } public static void put(Map map, A a, B b) { if (map != null) map.put(a, b); } public static List _registerDangerousWeakMap_preList; public static A _registerDangerousWeakMap(A map) { return _registerDangerousWeakMap(map, null); } public static A _registerDangerousWeakMap(A map, Object init) { callF(init, map); if (init instanceof String) { final String f = (String) (init); init = new VF1() { public void get(Map map) { try { callMC(f, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callMC(f, map)"; } }; } if (javax() == null) { if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList(); _registerDangerousWeakMap_preList.add(pair(map, init)); return map; } call(javax(), "_registerDangerousWeakMap", map, init); return map; } public static void _onLoad_registerDangerousWeakMap() { assertNotNull(javax()); if (_registerDangerousWeakMap_preList == null) return; for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b); _registerDangerousWeakMap_preList = null; } public static boolean isSubtypeOf(Class a, Class b) { return b.isAssignableFrom(a); } public static Runnable asRunnable(Object o) { return toRunnable(o); } public static void _inheritThreadInfo(Object info) { _threadInheritInfo(info); } public static char stringToChar(String s) { if (l(s) != 1) throw fail("bad stringToChar: " + s); return firstChar(s); } public static String structure_addTokenMarkers(String s) { return join(structure_addTokenMarkers(javaTok(s))); } public static List structure_addTokenMarkers(List tok) { TreeSet refs = new TreeSet(); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (t.startsWith("t") && isInteger(t.substring(1))) refs.add(parseInt(t.substring(1))); } if (empty(refs)) return tok; for (int i : refs) { int idx = i * 2 + 1; String t = ""; if (endsWithLetterOrDigit(tok.get(idx - 1))) t = " "; tok.set(idx, t + "m" + i + " " + tok.get(idx)); } return tok; } public static String jreplace(String s, String in, String out) { return jreplace(s, in, out, null); } public static String jreplace(String s, String in, String out, Object condition) { List tok = javaTok(s); return jreplace(tok, in, out, condition) ? join(tok) : s; } public static boolean jreplace(List tok, String in, String out) { return jreplace(tok, in, out, false, true, null); } public static boolean jreplace(List tok, String in, String out, Object condition) { return jreplace(tok, in, out, false, true, condition); } public static boolean jreplace(List tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) { List tokin = javaTok(in); jfind_preprocess(tokin); String[] toks = toStringArray(codeTokensOnly(tokin)); boolean anyChange = false; for (int n = 0; n < 10000; n++) { int i = findCodeTokens(tok, 1, ignoreCase, toks, condition); if (i < 0) return anyChange; List subList = tok.subList(i - 1, i + l(tokin) - 1); String expansion = jreplaceExpandRefs(out, subList); int end = i + l(tokin) - 2; clearAllTokens(tok, i, end); tok.set(i, expansion); if (reTok) reTok(tok, i, end); anyChange = true; } throw fail("woot? 10000! " + quote(in) + " => " + quote(out)); } public static boolean jreplace_debug; public static Class run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } public static void restart() { Object j = getJavaX(); call(j, "cleanRestart", get(j, "fullArgs")); } public static volatile boolean sleep_noSleep; public static 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); } } public static void sleep() { try { if (sleep_noSleep) throw fail("nosleep"); print("Sleeping."); sleepQuietly(); } catch (Exception __e) { throw rethrow(__e); } } public static Class hotwireOnce(String programID) { return hotwireCached(programID, false); } public static WeakReference newWeakReference(A a) { return a == null ? null : new WeakReference(a); } public static 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) value = ((Long) value).intValue(); if (type == LinkedHashMap.class && value instanceof Map) { f.set(o, asLinkedHashMap((Map) value)); return; } try { if (f.getType() == Concept.Ref.class) { f.set(o, ((Concept) o).new Ref((Concept) value)); return; } if (o instanceof Concept.Ref) { f.set(o, ((Concept.Ref) o).get()); return; } } catch (Throwable _e) { } throw e; } } public static void consoleSetInput(final String text) { if (headless()) return; setTextAndSelectAll(consoleInputField(), text); focusConsole(); } public static String getSnippetTitle(String id) { try { if (id == null) return null; if (!isSnippetID(id)) return "?"; 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); } } public static String getSnippetTitle(long id) { return getSnippetTitle(fsI(id)); } public static File computerIDFile() { return javaxDataDir("Basic Info/computer-id.txt"); } public static String formatWithThousandsSeparator(long l) { return NumberFormat.getInstance(new Locale("en_US")).format(l); } public static Pair pair(A a, B b) { return new Pair(a, b); } public static Pair pair(A a) { return new Pair(a, a); } public static char firstChar(String s) { return s.charAt(0); } public static int jfind(String s, String in) { return jfind(javaTok(s), in); } public static int jfind(List tok, String in) { return jfind(tok, 1, in); } public static int jfind(List tok, int startIdx, String in) { return jfind(tok, startIdx, in, null); } public static int jfind(List tok, String in, Object condition) { return jfind(tok, 1, in, condition); } public static int jfind(List tok, int startIdx, String in, Object condition) { List tokin = javaTok(in); jfind_preprocess(tokin); return jfind(tok, startIdx, tokin, condition); } public static int jfind(List tok, List tokin) { return jfind(tok, 1, tokin); } public static int jfind(List tok, int startIdx, List tokin) { return jfind(tok, startIdx, tokin, null); } public static int jfind(List tok, int startIdx, List tokin, Object condition) { return findCodeTokens(tok, startIdx, false, toStringArray(codeTokensOnly(tokin)), condition); } public static List jfind_preprocess(List tok) { for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">")); replaceSublist(tok, ll("\\", "", "*"), ll("\\*")); return tok; } public static String[] toStringArray(Collection c) { String[] a = new String[l(c)]; Iterator it = c.iterator(); for (int i = 0; i < l(a); i++) a[i] = it.next(); return a; } public static String[] toStringArray(Object o) { if (o instanceof String[]) return (String[]) o; else if (o instanceof Collection) return toStringArray((Collection) o); else throw fail("Not a collection or array: " + getClassName(o)); } public static List codeTokensOnly(List tok) { List l = new ArrayList(); for (int i = 1; i < tok.size(); i += 2) l.add(tok.get(i)); return l; } public static int findCodeTokens(List tok, String... tokens) { return findCodeTokens(tok, 1, false, tokens); } public static int findCodeTokens(List tok, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, 1, ignoreCase, tokens); } public static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, startIdx, ignoreCase, tokens, null); } public static List findCodeTokens_specials = litlist("*", "", "", "", "\\*"); public static boolean findCodeTokens_debug; public static int findCodeTokens_indexed, findCodeTokens_unindexed; public static int findCodeTokens_bails, findCodeTokens_nonbails; public static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) { if (findCodeTokens_debug) { if (eq(getClassName(tok), "main$IndexedList2")) findCodeTokens_indexed++; else findCodeTokens_unindexed++; } if (!findCodeTokens_specials.contains(tokens[0]) && !tok.contains(tokens[0])) { ++findCodeTokens_bails; return -1; } ++findCodeTokens_nonbails; outer: for (int i = startIdx | 1; i + tokens.length * 2 - 2 < tok.size(); i += 2) { for (int j = 0; j < tokens.length; j++) { String p = tokens[j], t = tok.get(i + j * 2); boolean match; if (eq(p, "*")) match = true; else if (eq(p, "")) match = isQuoted(t); else if (eq(p, "")) match = isIdentifier(t); else if (eq(p, "")) match = isInteger(t); else if (eq(p, "\\*")) match = eq("*", t); else match = ignoreCase ? eqic(p, t) : eq(p, t); if (!match) continue outer; } if (condition == null || checkTokCondition(condition, tok, i - 1)) return i; } return -1; } public static String jreplaceExpandRefs(String s, List tokref) { List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { if (tok.get(i).startsWith("$") && isInteger(tok.get(i).substring(1))) { String x = tokref.get(-1 + parseInt(tok.get(i).substring(1)) * 2); tok.set(i, x); } } return join(tok); } public static void clearAllTokens(List tok) { for (int i = 0; i < tok.size(); i++) tok.set(i, ""); } public static void clearAllTokens(List tok, int i, int j) { for (; i < j; i++) tok.set(i, ""); } public static List reTok(List tok) { replaceCollection(tok, javaTok(tok)); return tok; } public static List reTok(List tok, int i) { return reTok(tok, i, i + 1); } public static List reTok(List tok, int i, int j) { i = i & ~1; j = j | 1; List t = javaTok(join(subList(tok, i, j))); replaceListPart(tok, i, j, t); return tok; } public static Class hotwire(String src) { 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; } } public static A callMain(A c, String... args) { callOpt(c, "main", new Object[] { args }); return c; } public static void callMain() { callMain(mc()); } public static Object sleepQuietly_monitor = new Object(); public static void sleepQuietly() { try { assertFalse(isAWTThread()); synchronized (sleepQuietly_monitor) { sleepQuietly_monitor.wait(); } } catch (Exception __e) { throw rethrow(__e); } } public static TreeMap hotwireCached_cache = new TreeMap(); public static Lock hotwireCached_lock = lock(); public static Class hotwireCached(String programID) { return hotwireCached(programID, true); } public static Class hotwireCached(String programID, boolean runMain) { return hotwireCached(programID, runMain, false); } public static Class hotwireCached(String programID, boolean runMain, boolean dependent) { Lock __1425 = hotwireCached_lock; lock(__1425); 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(__1425); } } public static LinkedHashMap asLinkedHashMap(Map map) { if (map instanceof LinkedHashMap) return (LinkedHashMap) map; LinkedHashMap m = new LinkedHashMap(); if (map != null) synchronized (collectionMutex(map)) { m.putAll(map); } return m; } public static boolean headless() { return isHeadless(); } public static JTextField setTextAndSelectAll(final JTextField tf, final String text) { { swing(new Runnable() { public void run() { try { tf.setText(text); tf.selectAll(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tf.setText(text);\r\n tf.selectAll();"; } }); } return tf; } public static JTextField consoleInputField() { Object console = get(getJavaX(), "console"); return (JTextField) getOpt(console, "tfInput"); } public static void focusConsole(String s) { setConsoleInput(s); focusConsole(); } public static void focusConsole() { JComponent tf = consoleInputFieldOrComboBox(); if (tf != null) { tf.requestFocus(); } } public static boolean isLocalSnippetID(String snippetID) { return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID)); } public static boolean isLocalSnippetID(long snippetID) { return snippetID >= 1000 && snippetID <= 9999; } public static 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"); } public static boolean isImageServerSnippet(long id) { return id >= 1100000 && id < 1200000; } public static String imageServerURL() { return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/"); } public static String muricaCredentialsQuery() { return htmlQuery(muricaCredentials()); } public static boolean isGeneralFileServerSnippet(long id) { return id >= 1400000 && id < 1500000; } public static String tb_mainServer_default = "http://tinybrain.de:8080"; public static Object tb_mainServer_override; public static String tb_mainServer() { if (tb_mainServer_override != null) return (String) callF(tb_mainServer_override); return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default)); } public static File tb_mainServer_file() { return getProgramFile("#1001638", "mainserver.txt"); } public static boolean tb_mainServer_isDefault() { return eq(tb_mainServer(), tb_mainServer_default); } public static String standardCredentials_noCookies() { return standardCredentials() + "&noCookies=1"; } public static boolean saveTextFileIfChanged(File f, String contents) { return saveTextFileIfDifferent(f, contents); } public static File snippetTitle_cacheFile(String snippetID) { return javaxCachesDir("Snippet Titles/" + psI(snippetID)); } public static List replaceSublist(List l, List x, List y) { if (x == null) return l; int i = 0; while (true) { i = indexOfSubList(l, x, i); if (i < 0) break; removeSubList(l, i, i + l(x)); l.addAll(i, y); i += l(y); } return l; } public static List replaceSublist(List l, int fromIndex, int toIndex, List y) { removeSubList(l, fromIndex, toIndex); l.addAll(fromIndex, y); return l; } public static boolean isQuoted(String s) { if (isNormalQuoted(s)) return true; return isMultilineQuoted(s); } public static boolean checkTokCondition(Object condition, List tok, int i) { if (condition instanceof TokCondition) return ((TokCondition) condition).get(tok, i); return checkCondition(condition, tok, i); } public static void replaceCollection(Collection dest, Collection src) { dest.clear(); dest.addAll(src); } public static void replaceListPart(List l, int i, int j, List l2) { int j2 = i + l(l2); if (j2 == j) { copyListPart(l2, 0, l, i, l(l2)); return; } l.subList(i, j).clear(); l.addAll(i, l2); } public static boolean _inCore() { return false; } public static List hotwire_copyOver_after = synchroList(); public static 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); } public static Object makeDependent_postProcess; public static 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); } public static void setConsoleInput(String text) { consoleSetInput(text); } public static JComponent consoleInputFieldOrComboBox() { Object console = get(getJavaX(), "console"); JComboBox cb = (JComboBox) (getOpt(console, "cbInput")); if (cb != null) return cb; return (JTextField) getOpt(console, "tfInput"); } public static long psI(String snippetID) { return parseSnippetID(snippetID); } public static File localSnippetFile(long snippetID) { return localSnippetsDir(snippetID + ".text"); } public static File localSnippetFile(String snippetID) { return localSnippetFile(parseSnippetID(snippetID)); } public static String getFileInfoField(File f, String field) { return getOneLineFileInfoField(f, field); } public static File dropExtension(File f) { return f == null ? null : fileInSameDir(f, dropExtension(f.getName())); } public static String dropExtension(String s) { return takeFirst(s, smartLastIndexOf(s, '.')); } public static String htmlQuery(Map params) { return params.isEmpty() ? "" : "?" + makePostData(params); } public static String htmlQuery(Object... data) { return htmlQuery(litmap(data)); } public static File getProgramFile(String progID, String fileName) { if (new File(fileName).isAbsolute()) return new File(fileName); return new File(getProgramDir(progID), fileName); } public static File getProgramFile(String fileName) { return getProgramFile(getProgramID(), fileName); } public static String standardCredentials() { String user = standardCredentialsUser(); String pass = standardCredentialsPass(); if (nempty(user) && nempty(pass)) return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass); return ""; } public static boolean saveTextFileIfDifferent(File f, String contents) { if (eq(loadTextFile(f), contents)) return false; { saveTextFile(f, contents); return true; } } public static File javaxCachesDir_dir; public static File javaxCachesDir() { return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches"); } public static File javaxCachesDir(String sub) { return newFile(javaxCachesDir(), sub); } public static int indexOfSubList(List x, List y) { return indexOfSubList(x, y, 0); } public static int indexOfSubList(List x, List y, int i) { outer: for (; i + l(y) <= l(x); i++) { for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y.get(j))) continue outer; return i; } return -1; } public static int indexOfSubList(List x, A[] y, int i) { outer: for (; i + l(y) <= l(x); i++) { for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y[j])) continue outer; return i; } return -1; } public static void removeSubList(List l, int from, int to) { if (l != null) subList(l, from, to).clear(); } public static void removeSubList(List l, int from) { if (l != null) subList(l, from).clear(); } public static 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; } public static 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) == '['; } public static boolean checkCondition(Object condition, Object... args) { return isTrue(callF(condition, args)); } public static void copyListPart(List a, int i1, List b, int i2, int n) { if (a == null || b == null) return; for (int i = 0; i < n; i++) b.set(i2 + i, a.get(i1 + i)); } public static void setOptIfNotNull(Object o, String field, Object value) { if (value != null) setOpt(o, field, value); } public static Object mainBot; public static Object getMainBot() { return mainBot; } public static List dependentClasses() { return cleanUpAndGetWeakReferencesList(hotwire_classes); } public static File localSnippetsDir() { return javaxDataDir("Personal Programs"); } public static File localSnippetsDir(String sub) { return newFile(localSnippetsDir(), sub); } public static String getOneLineFileInfoField(File f, String field) { File infoFile = associatedInfosFile(f); List lines = lines(loadTextFile(infoFile)); return firstStartingWithIC_drop(lines, field + ": "); } public static File fileInSameDir(File f, String newName) { return newFile(parentFile(f), newName); } public static int smartLastIndexOf(String s, char c) { if (s == null) return 0; int i = s.lastIndexOf(c); return i >= 0 ? i : l(s); } public static File getProgramDir() { return programDir(); } public static File getProgramDir(String snippetID) { return programDir(snippetID); } public static String standardCredentialsUser() { return trim(loadTextFile(new File(userHome(), ".tinybrain/username"))); } public static String standardCredentialsPass() { return trim(loadTextFile(new File(userHome(), ".tinybrain/userpass"))); } public static List> hotwire_classes = synchroList(); public static Class hotwireDependent(String src) { Class c = hotwire(src); makeDependent(c); return c; } public static 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; } } public static File associatedInfosFile(File f) { return replaceExtension(f, ".infos"); } public static String lines(Collection lines) { return fromLines(lines); } public static List lines(String s) { return toLines(s); } public static String firstStartingWithIC_drop(Collection l, final String prefix) { for (String s : unnull(l)) if (swic(s, prefix)) return substring(s, l(prefix)); return null; } public static String firstStartingWithIC_drop(String prefix, Collection l) { return firstStartingWithIC_drop(l, prefix); } public static File parentFile(File f) { return dirOfFile(f); } public static File programDir_mine; public static File programDir() { return programDir(getProgramID()); } public static File programDir(String snippetID) { boolean me = sameSnippetID(snippetID, programID()); if (programDir_mine != null && me) return programDir_mine; File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID)); if (me) { String c = caseID(); if (nempty(c)) dir = newFile(dir, c); } return dir; } public static File programDir(String snippetID, String subPath) { return new File(programDir(snippetID), subPath); } public static File replaceExtension(File f, String extOld, String extNew) { return newFile(replaceExtension(f2s(f), extOld, extNew)); } public static File replaceExtension(File f, String extNew) { return replaceExtension(f, fileExtension(f), extNew); } public static String replaceExtension(String s, String extOld, String extNew) { s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s); return s + addPrefixOptIfNempty(".", extNew); } public static String replaceExtension(String name, String extNew) { return replaceExtension(name, fileExtension(name), extNew); } public static String fromLines(Collection lines) { StringBuilder buf = new StringBuilder(); if (lines != null) for (Object line : lines) buf.append(str(line)).append('\n'); return buf.toString(); } public static String fromLines(String... lines) { return fromLines(asList(lines)); } public static File dirOfFile(File f) { return f == null ? null : f.getParentFile(); } public static boolean sameSnippetID(String a, String b) { if (!isSnippetID(a) || !isSnippetID(b)) return false; return parseSnippetID(a) == parseSnippetID(b); } public static String fileExtension(File f) { if (f == null) return null; return fileExtension(f.getName()); } public static String fileExtension(String s) { return substring(s, smartLastIndexOf(s, '.')); } public static String dropSuffixIC(String suffix, String s) { return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } public abstract static class VF2 { public abstract void get(A a, B b); } public static class ProgramScan { public static int threads = isWindows() ? 500 : 10; public static int timeout = 5000; public static String ip = "127.0.0.1"; public static int quickScanFrom = 10000, quickScanTo = 10999; public static int maxNumberOfVMs_android = 4; public static int maxNumberOfVMs_nonAndroid = 50; public static int maxNumberOfVMs; public static boolean verbose; public static class Program { public int port; public String helloString; public Program(int port, String helloString) { this.helloString = helloString; this.port = port; } } public static List scan() { try { return scan(1, 65535); } catch (Exception __e) { throw rethrow(__e); } } public static List scan(int fromPort, int toPort) { return scan(fromPort, toPort, new int[0]); } public static List scan(int fromPort, int toPort, int[] preferredPorts) { try { Set preferredPortsSet = new HashSet(asList(preferredPorts)); int scanSize = toPort - fromPort + 1; String name = toPort < 10000 ? "bot" : "program"; int threads = isWindows() ? min(500, scanSize) : min(scanSize, 10); final ExecutorService es = Executors.newFixedThreadPool(threads); if (verbose) print(firstToUpper(name) + "-scanning " + ip + " with timeout " + timeout + " ms in " + threads + " threads."); startTiming(); List> futures = new ArrayList(); List ports = new ArrayList(); for (int port : preferredPorts) { futures.add(checkPort(es, ip, port, timeout)); ports.add(port); } for (int port = fromPort; port <= toPort; port++) if (!preferredPortsSet.contains(port) && !forbiddenPort(port)) { futures.add(checkPort(es, ip, port, timeout)); ports.add(port); } es.shutdown(); List programs = new ArrayList(); long time = now(); int i = 0; for (final Future f : futures) { if (verbose) print("Waiting for port " + get(ports, i++) + " at time " + (now() - time)); Program p = f.get(); if (p != null) programs.add(p); } if (verbose) print("Found " + programs.size() + " " + name + "(s) on " + ip); return programs; } catch (Exception __e) { throw rethrow(__e); } } public static Future checkPort(final ExecutorService es, final String ip, final int port, final int timeout) { return es.submit(new Callable() { @Override public Program call() { try { Socket socket = new Socket(); try { socket.setSoTimeout(timeout); socket.connect(new InetSocketAddress(ip, port), timeout); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); String hello = or(in.readLine(), "?"); return new Program(port, hello); } finally { socket.close(); } } catch (Exception ex) { return null; } } }); } public static List quickScan() { return scan(quickScanFrom, quickScanTo); } public static List quickBotScan() { return quickBotScan(new int[0]); } public static List quickBotScan(int[] preferredPorts) { if (maxNumberOfVMs == 0) maxNumberOfVMs = isAndroid() ? maxNumberOfVMs_android : maxNumberOfVMs_nonAndroid; return scan(4999, 5000 + maxNumberOfVMs - 1, preferredPorts); } } public abstract static class DialogIO { public String line; public boolean eos, loud, noClose; public Lock lock = lock(); public abstract String readLineImpl(); public abstract boolean isStillConnected(); public abstract void sendLine(String line); public abstract boolean isLocalConnection(); public abstract Socket getSocket(); public abstract void close(); public int getPort() { Socket s = getSocket(); return s == null ? 0 : s.getPort(); } public boolean helloRead; public int shortenOutputTo = 500; public String readLineNoBlock() { String l = line; line = null; return l; } public boolean waitForLine() { try { ping(); if (line != null) return true; line = readLineImpl(); if (line == null) eos = true; return line != null; } catch (Exception __e) { throw rethrow(__e); } } public String readLine() { waitForLine(); helloRead = true; return readLineNoBlock(); } public String ask(String s, Object... args) { if (loud) return askLoudly(s, args); if (!helloRead) readLine(); if (args.length != 0) s = format3(s, args); sendLine(s); return readLine(); } public String askLoudly(String s, Object... args) { if (!helloRead) readLine(); if (args.length != 0) s = format3(s, args); print("> " + shorten(s, shortenOutputTo)); sendLine(s); String answer = readLine(); print("< " + shorten(answer, shortenOutputTo)); return answer; } public void pushback(String l) { if (line != null) throw fail(); line = l; helloRead = false; } } public abstract static class DialogHandler { public abstract void run(DialogIO io); } public static class ConceptFieldIndex implements IConceptIndex, IFieldIndex { public Class cc; public String field; public HashMap objectToValue = new HashMap(); public MultiMap valueToObject = new MultiMap(); public ConceptFieldIndex() { } public ConceptFieldIndex(Class cc, String field) { this(mainConcepts, cc, field); } public ConceptFieldIndex(Concepts concepts, Class cc, String field) { this.field = field; this.cc = cc; concepts.addConceptIndex(this); for (A c : list(concepts, cc)) updateImpl(c); concepts.addFieldIndex(cc, field, this); } public void update(Concept c) { if (!isInstance(cc, c)) return; updateImpl(c); } public synchronized void updateImpl(Concept c) { Val newValue = (Val) (cget(c, field)); Val oldValue = objectToValue.get(c); if (newValue == null || newValue != oldValue) { valueToObject.remove(oldValue, (A) c); valueToObject.put(newValue, (A) c); objectToValue.put((A) c, newValue); } } public synchronized void remove(Concept c) { if (!isInstance(cc, c)) return; Val value = (Val) (cget(c, field)); objectToValue.remove(c); valueToObject.remove(value, (A) c); } public synchronized A get(Val value) { return valueToObject.getFirst(value); } public synchronized List getAll(Val value) { return valueToObject.get(value); } } public static class Var implements IVar { public A v; public Var() { } public Var(A v) { this.v = v; } public synchronized void set(A a) { if (v != a) { v = a; notifyAll(); } } public synchronized A get() { return v; } public synchronized boolean has() { return v != null; } public synchronized void clear() { v = null; } public String toString() { return str(get()); } } public static class TimedCache { public long timeout; public A value; public Object function; public long set; public Lock lock = lock(); public int stores, fails, hits; public TimedCache(double timeoutSeconds, Object function) { this(function, timeoutSeconds); } public TimedCache(Object function, double timeoutSeconds) { this(timeoutSeconds); this.function = function; } public TimedCache(double timeoutSeconds) { timeout = toMS(timeoutSeconds); } public A set(A a) { Lock __175 = lock; lock(__175); try { ++stores; value = a; set = now(); return a; } finally { unlock(__175); } } public boolean has() { Lock __176 = lock; lock(__176); try { clean(); if (set != 0) { ++hits; return true; } ++fails; return false; } finally { unlock(__176); } } public A get() { Lock __177 = lock; lock(__177); try { if (function != null) return get(function); clean(); if (set != 0) ++hits; else ++fails; return value; } finally { unlock(__177); } } public A get(Object makerFunction) { Lock __178 = lock; lock(__178); try { if (this.has()) return getNoClean(); A a = (A) (callF(makerFunction)); return set(a); } finally { unlock(__178); } } public A getNoClean() { Lock __179 = lock; lock(__179); try { return value; } finally { unlock(__179); } } public void clean() { Lock __180 = lock; lock(__180); try { if (timeout > 0 && now() > set + timeout) clear(); } finally { unlock(__180); } } public void clear() { Lock __181 = lock; lock(__181); try { set = 0; value = null; } finally { unlock(__181); } } public String stats() { return "Stores: " + stores + ", hits: " + hits + ", fails: " + fails; } } public abstract static class TokCondition { public abstract boolean get(List tok, int i); } public abstract static class IterableIterator implements Iterator, Iterable { public Iterator iterator() { return this; } public void remove() { unsupportedOperation(); } } public static class Flag { public boolean up; 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 synchronized void waitUntilUp(long timeout) { if (!up) { try { wait(timeout); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized boolean isUp() { return up; } 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 static 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 abstract static class CloseableIterableIterator extends IterableIterator implements AutoCloseable { public void close() throws Exception { } } public static class ExpiringMap2 extends AbstractMap { public Map> byKey = new HashMap(); public PriorityBlockingQueue> queue = new PriorityBlockingQueue(); public long standardExpiryTime; public boolean renewOnOverwrite = true, renewOnGet; public Object onChange; public ExpiringMap2() { } public ExpiringMap2(long standardExpiryTime) { this.standardExpiryTime = standardExpiryTime; } public ExpiringMap2(long standardExpiryTime, Object onChange) { this.onChange = onChange; this.standardExpiryTime = standardExpiryTime; } public synchronized boolean clean() { boolean changes = false; Pair p; while ((p = queue.peek()) != null && sysTime() >= p.a) { p = queue.poll(); Pair v = byKey.get(p.b); if (v != null) { byKey.remove(p.b); changes = true; change(); } } return changes; } public void change() { callF(onChange); } public synchronized B put(A a, B b) { clean(); long timeout = sysTime() + standardExpiryTime; Pair p = byKey.get(a); if (p != null && renewOnOverwrite) queue.remove(new Pair(p.a, a)); byKey.put(a, pair(timeout, b)); change(); if (p == null || renewOnOverwrite) queue.add(new Pair(timeout, a)); return pairB(p); } public synchronized B remove(Object a) { clean(); Pair p = byKey.get(a); if (p == null) return null; queue.remove(new Pair(p.a, a)); byKey.remove(a); change(); return p.b; } public synchronized B get(Object a) { clean(); Pair p = byKey.get(a); if (renewOnGet && p != null) { queue.remove(new Pair(p.a, a)); long timeout = sysTime() + standardExpiryTime; byKey.put((A) a, pair(timeout, p.b)); queue.add(new Pair(timeout, a)); } return pairB(p); } public synchronized Set> entrySet() { clean(); return synchronizedSet(mapValues("pairB", byKey).entrySet()); } public synchronized Set keySet() { clean(); return synchronizedSet(byKey.keySet()); } public synchronized int size() { clean(); return byKey.size(); } public void setStandardExpiryTime(long ms) { standardExpiryTime = ms; } public synchronized ExpiringMap2 setMap(Map innerMap) { byKey = innerMap; return this; } } public static interface Producer { public A next(); } public abstract static class DynCRUD extends DynModule { public transient Class conceptClass; public transient SimpleCRUD crud; public String caseID; public DynCRUD() { } public DynCRUD(Class conceptClass) { this.conceptClass = conceptClass; } public void start() { super.start(); dbWithCase(caseID); crud = makeCRUD(); } public JComponent visualize() { makeConceptsTable_idWidth = 0; showConceptsTable_afterUpdate.set(new VF1() { public void get(JTable t) { try { int n = tableColumnCount(t); for (int i = 0; i < n; i++) setColumnName(t, i, i == 0 ? "" : humanizeFormLabel(getColumnName(t, i))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "int n = tableColumnCount(t);\r\n for i to n:\r\n setColumnName(t, i, ..."; } }); return withMargin(crud.make()); } public SimpleCRUD makeCRUD() { return new SimpleCRUD(db_mainConcepts(), conceptClass); } public JTable table() { return crud == null ? null : crud.table; } public A selected() { return crud == null ? null : crud.selectedConcept(); } public void addButton(JComponent button) { if (crud != null) addComponent(crud.buttons, button); } public void addButton(String name, Object action) { addButton(jbutton(name, action)); } public void makeSortable() { addRowSorter(table()); rowSorter_setComparatorForAllColumns(table(), alphaNumComparator()); } public String searchTerm() { return crud == null || crud.tableSearcher == null ? null : gtt(crud.tableSearcher.tfInput); } public void addCountToName() { onConceptChangeAndNow(new Runnable() { public void run() { try { setModuleName(programTitle() + " (" + conceptCount() + ")"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setModuleName(programTitle() + \" (\" + conceptCount() + \")\")"; } }); } public Concepts conceptsObject() { return crud.concepts; } public List list(Class c) { return conceptsObject().list(c); } public List concepts() { AutoCloseable __186 = enter(); try { return list(conceptClass); } finally { _close(__186); } } public List data() { return concepts(); } public int conceptCount() { AutoCloseable __187 = enter(); try { return countConcepts(conceptClass); } finally { _close(__187); } } public void deleteAll() { AutoCloseable __188 = enter(); try { deleteConcepts(conceptClass); } finally { _close(__188); } } public void addDialog() { AutoCloseable __189 = enter(); try { crud.newConcept(); } finally { _close(__189); } } } public static class PersistableThrowable { public String className; public String msg; public String stacktrace; public PersistableThrowable() { } public PersistableThrowable(Throwable e) { if (e == null) className = "Crazy Null Error"; else { className = getClassName(e).replace('/', '.'); msg = e.getMessage(); stacktrace = getStackTrace_noRecord(e); } } public String toString() { return nempty(msg) ? className + ": " + msg : className; } } public static class MechMode { public Object readMode; public Object writeMode; public MechMode() { } public MechMode(Object readMode, Object writeMode) { this.writeMode = writeMode; this.readMode = readMode; } public String toString() { return "MechMode(" + readMode + ", " + writeMode + ")"; } public boolean equals(Object o) { if (!(o instanceof MechMode)) return false; MechMode x = (MechMode) (o); return eq(readMode, x.readMode) && eq(writeMode, x.writeMode); } public int hashCode() { int h = -866263200; h = h * 2 + _hashCode(readMode); h = h * 2 + _hashCode(writeMode); return h; } } public static 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); } } public static class MultiMap { public Map> data = new HashMap>(); 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); } } public void addAll(A key, Collection values) { synchronized (data) { 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(A key, Collection values) { synchronized (data) { for (B value : values) put(key, value); } } 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 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()) 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) { data.remove(key); } } public void remove(A key, B value) { synchronized (data) { List list = data.get(key); if (list != null) { list.remove(value); 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 putAll(MultiMap map) { synchronized (data) { for (A key : map.keySet()) putAll(key, map.get(key)); } } public int keysSize() { synchronized (data) { return l(data); } } public int size() { synchronized (data) { int n = 0; for (List l : data.values()) n += l(l); return n; } } 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 List allValues() { return concatLists(values(data)); } public Object mutex() { return data; } } public static boolean SimpleCRUD_searcher = true; public static class SimpleCRUD { public Class cc; public JTable table; public JPanel buttons, panel; public Object renderer; public String hID = "ID"; public Set excludeFieldsFromEditing; public String modifiedField; public TableSearcher tableSearcher; public Set multiLineFields; public Concepts concepts; public SimpleCRUD(Class cc) { this(db_mainConcepts(), cc); } public SimpleCRUD(Concepts concepts, Class cc) { this.cc = cc; this.concepts = concepts; } public SimpleCRUD show(String frameTitle) { make(); showFrame(frameTitle, panel); return this; } public SimpleCRUD show() { return show(plural(shortClassName(cc))); } public SimpleCRUD showMaximized() { show(); maximizeFrame(panel); return this; } public JPanel makePanel() { return make(); } public JPanel make() { db(); framesBot(); table = makeConceptsTable(cc, wrapRenderer(renderer)); { swing(new Runnable() { public void run() { try { buttons = jRightAlignedLine(jbutton("Add...", new Runnable() { public void run() { try { newConcept(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "newConcept()"; } }), tableDependButton(table, jbutton("Edit", new Runnable() { public void run() { try { editConcept(selectedConcept()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "editConcept(selectedConcept())"; } })), tableDependButton(table, jbutton("Delete", new Runnable() { public void run() { try { final List l = selectedConcepts(); withDBLock(new Runnable() { public void run() { try { for (A c : l) c.delete(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "for (A c : l) c.delete()"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final List l = selectedConcepts();\r\n withDBLock(r { for (A c : l)..."; } }))); if (SimpleCRUD_searcher) { tableSearcher = tableWithSearcher2(table, "withMargin", true); panel = centerAndSouthWithMargin(tableSearcher.panel, buttons); } else panel = centerAndSouthWithMargin(table, buttons); Object fEdit = new VF1() { public void get(Integer row) { try { editConcept((A) getConcept(toLong(getTableCell(table, row, 0)))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "editConcept((A) getConcept(toLong(getTableCell(table, row, 0))))"; } }; tablePopupMenuItem(table, "Edit...", fEdit); onDoubleClick(table, fEdit); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "buttons = jRightAlignedLine(\r\n jbutton(\"Add...\", r { newConcept() }),\r..."; } }); } return panel; } public Object wrapRenderer(final Object renderer) { return renderer == null ? null : new F1() { public Object get(A a) { try { return putAll(litorderedmap(hID, str(a.id)), (Map) callF(renderer, a)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "putAll(litorderedmap(hID, str(a.id)), (Map) callF(renderer, a))"; } }; } public void newConcept() { final A c = unlisted(cc); final Map map = makeComponents(c); Runnable r = new Runnable() { public void run() { try { register(c); saveData(c, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "register(c);\r\n saveData(c, map);"; } }; AutoCloseable __196 = tempSetMCOpt("formLayouter1_fixer2", 12); try { showFormTitled2("New " + shortClassName(cc), arrayPlus(mapToObjectArray(map), r)); } finally { _close(__196); } } public void editConcept(final A c) { if (c == null) return; final Map map = makeComponents(c); Runnable r = new Runnable() { public void run() { try { saveData(c, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "saveData(c, map)"; } }; AutoCloseable __197 = tempSetMCOpt("formLayouter1_fixer2", 12); try { showFormTitled2("Edit " + shortClassName(cc) + " #" + c.id, arrayPlus(mapToObjectArray(map), r)); } finally { _close(__197); } } public A selectedConcept() { return (A) getConcept(toLong(selectedTableCell(table, 0))); } public List selectedConcepts() { int[] rows = table.getSelectedRows(); List l = new ArrayList(); for (int row : rows) l.add((A) getConcept(toLong(getTableCell(table, row, 0)))); return l; } public Map makeComponents(A c) { Map map = litorderedmap(); makeComponents(c, map); return map; } public JComponent fieldComponent(A c, String field) { Class type = getFieldType(cc, field); Object value = getOpt(c, field); if (type == boolean.class) return jCenteredCheckBox(isTrue(value)); else if (contains(multiLineFields, field)) return typeWriterTextArea((String) value); else try { return autoComboBox(structureOrText_crud(value), new TreeSet(map("structureOrText_crud", collect(list(cc), field)))); } catch (Throwable e) { printException(e); return jTextField(structureOrText_crud(value)); } } public void saveComponent(A c, String field, JComponent comp) { comp = unwrap(comp); if (comp instanceof JTextComponent) cset(c, field, convertToField(trimIf(!(comp instanceof JTextArea), getText((JTextComponent) comp)), cc, field)); else if (comp instanceof JComboBox) cset(c, field, convertToField(getTextTrim((JComboBox) comp), cc, field)); else if (comp instanceof JCheckBox) cset(c, field, isChecked((JCheckBox) comp)); } public List fields() { if (excludeFieldsFromEditing != null && modifiedField != null) excludeFieldsFromEditing.add(modifiedField); return listWithoutSet(filter(conceptFieldsInOrder(cc), new F1() { public Boolean get(String field) { try { return fieldType(cc, field) != Concept.Ref.class; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "fieldType(cc, field) != Concept.Ref.class"; } }), excludeFieldsFromEditing); } public void excludeFieldsFromEditing(String... fields) { excludeFieldsFromEditing = setPlus(excludeFieldsFromEditing, fields); } public void makeComponents(A c, Map map) { for (String field : fields()) map.put(field, fieldComponent(c, field)); } public void saveData(A c, Map components) { for (String field : keys(components)) saveComponent(c, field, components.get(field)); if (modifiedField != null) cset(c, modifiedField, now()); } } public static interface IVar { public void set(A a); public A get(); public boolean has(); public void clear(); } public static B pairB(Pair p) { return p == null ? null : p.b; } public static String structureOrText_crud(Object o) { if (o == null) return ""; if (o instanceof Long) return str(o); if (o instanceof File) return ((File) o).getAbsolutePath(); return structureOrText(o); } public static boolean isWindows() { return System.getProperty("os.name").contains("Windows"); } public static String firstToUpper(String s) { if (empty(s)) return s; return Character.toUpperCase(s.charAt(0)) + s.substring(1); } public static long stopTiming_defaultMin = 10; public static long startTiming_startTime; public static void startTiming() { startTiming_startTime = now(); } public static void stopTiming() { stopTiming(null); } public static void stopTiming(String text) { stopTiming(text, stopTiming_defaultMin); } public static void stopTiming(String text, long minToPrint) { long time = now() - startTiming_startTime; if (time >= minToPrint) { text = or2(text, "Time: "); print(text + time + " ms"); } } public static List list(Class type) { return db_mainConcepts().list(type); } public static List list(Concepts concepts, Class type) { return concepts.list(type); } public static List list(String type) { return db_mainConcepts().list(type); } public static List list(Concepts concepts, String type) { return concepts.list(type); } public static boolean isInstance(Class type, Object arg) { return type.isInstance(arg); } public static List getAll(Map map, Collection l) { return lookupAllOpt(map, l); } public static List getAll(Collection l, Map map) { return lookupAllOpt(map, l); } public static long toMS(double seconds) { return (long) (seconds * 1000); } public static Iterator iterator(Iterable c) { return c == null ? emptyIterator() : c.iterator(); } public static UnsupportedOperationException unsupportedOperation() { throw new UnsupportedOperationException(); } public static long sysTime() { return sysNow(); } public static void change() { callOpt(getOptMC("mainConcepts"), "allChanged"); } public static Map mapValues(Object func, Map map) { Map m = similarEmptyMap(map); for (Object key : keys(map)) m.put(key, callF(func, map.get(key))); return m; } public static Map mapValues(Map map, Object func) { return mapValues(func, map); } public static Set keySet(Map map) { return map == null ? new HashSet() : map.keySet(); } public static Set keySet(Object map) { return keys((Map) map); } public static Set keySet(MultiMap mm) { return mm.keySet(); } public static void dbWithCase(String caseID) { caseID(caseID); db(); } public static int tableColumnCount(JTable table) { return tableNumColumns(table); } public static void setColumnName(final JTable table, final int idx, final String name) { if (table != null) { swing(new Runnable() { public void run() { try { if (table.getColumnCount() > idx) table.getColumnModel().getColumn(idx).setHeaderValue(name); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (table.getColumnCount() > idx)\r\n table.getColumnModel().getColumn(idx..."; } }); } } public static Map humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5"); public static String humanizeFormLabel(String s) { if (containsSpace(s)) return s; return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID")); } public static String getColumnName(final JTable table, final int idx) { return table == null ? null : swing(new F0() { public String get() { try { return table.getColumnCount() <= idx ? null : str(table.getColumnModel().getColumn(idx).getHeaderValue()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret table.getColumnCount() <= idx ? null\r\n : str(table.getColumnModel()...."; } }); } public static int withMargin_defaultWidth = 6; public static JPanel withMargin(Component c) { return withMargin(withMargin_defaultWidth, c); } public static JPanel withMargin(int w, Component c) { return withMargin(w, w, c); } public static JPanel withMargin(int w, int h, Component c) { return withMargin(w, h, w, h, c); } public static 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 = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right)); p.add(c); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat..."; } }); } public static A addComponent(final A c, final Component component) { if (component != null) { swing(new Runnable() { public void run() { try { c.add(component); revalidate(c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.add(component);\r\n revalidate(c);"; } }); } return c; } public static JButton jbutton(String text, Object action) { return newButton(text, action); } public static JButton jbutton(String text) { return newButton(text, null); } public static JButton jbutton(Action action) { return swingNu(JButton.class, action); } public static JTable addRowSorter(final JTable table) { if (table != null) { swing(new Runnable() { public void run() { try { table.setRowSorter(new TableRowSorter(table.getModel())); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "table.setRowSorter(new TableRowSorter(table.getModel()));"; } }); } return table; } public static void rowSorter_setComparatorForAllColumns(JTable table, final Comparator comparator) { if (table == null) return; setTableModel_fixSorter.put(table, new VF2() { public void get(JTable table, RowSorter sorter) { try { if (sorter instanceof TableRowSorter) { int n = tableColumnCount(table); for (int i = 0; i < n; i++) ((TableRowSorter) sorter).setComparator(i, comparator); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (sorter cast TableRowSorter) {\r\n int n = tableColumnCount(table);\r\n ..."; } }); } public static AlphanumComparator alphaNumComparator_instance; public static Comparator alphaNumComparator() { if (alphaNumComparator_instance == null) alphaNumComparator_instance = new AlphanumComparator(); return alphaNumComparator_instance; } public static String gtt(JTextComponent c) { return getTextTrim(c); } public static String gtt(JComboBox cb) { return getTextTrim(cb); } public static void onConceptChangeAndNow(Runnable r) { onConceptsChangeAndNow(r); } public static String programTitle() { return getProgramName(); } public static void concepts() { conceptsAndBot(); } public static void concepts(int autoSaveInterval) { conceptsAndBot(autoSaveInterval); } public static int countConcepts(Class c, Object... params) { return db_mainConcepts().countConcepts(c, params); } public static int countConcepts() { return db_mainConcepts().countConcepts(); } public static int countConcepts(String className) { return db_mainConcepts().countConcepts(className); } public static int countConcepts(Concepts concepts, String className) { return concepts.countConcepts(className); } public static void deleteConcepts(List conceptsOrIDs) { db_mainConcepts().deleteConcepts(conceptsOrIDs); } public static List deleteConcepts(Class c, Object... params) { List l = findConceptsWhere(c, params); deleteConcepts(l); return l; } public static int _hashCode(Object a) { return a == null ? 0 : a.hashCode(); } public static int hashCodeFor(Object a) { return a == null ? 0 : a.hashCode(); } public static Map putAll(Map a, Map b) { if (a != null) a.putAll(b); return a; } public static 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; } public static 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); } } public static Collection values(Map map) { return map == null ? emptyList() : map.values(); } public static Collection values(MultiMap mm) { return mm == null ? emptyList() : concatLists(values(mm.data)); } public static JFrame showFrame() { return makeFrame(); } public static JFrame showFrame(Object content) { return makeFrame(content); } public static JFrame showFrame(String title) { return makeFrame(title); } public static JFrame showFrame(String title, Object content) { return makeFrame(title, content); } public static JFrame showFrame(final JFrame f) { if (f != null) { swing(new Runnable() { public void run() { try { if (frameTooSmall(f)) frameStandardSize(f); if (!f.isVisible()) f.setVisible(true); if (f.getState() == Frame.ICONIFIED) f.setState(Frame.NORMAL); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (frameTooSmall(f)) frameStandardSize(f);\r\n if (!f.isVisible()) f.setVis..."; } }); } return f; } public static JFrame showFrame(String title, Object content, JFrame frame) { if (frame == null) return showFrame(title, content); else { frame.setTitle(title); setFrameContents(frame, content); return frame; } } public static String plural(String s) { return getPlural(s); } public static JFrame maximizeFrame(final Component c) { JFrame f = swing(new F0() { public JFrame get() { try { JFrame f = getFrame(c); if (f != null) f.setExtendedState(JFrame.MAXIMIZED_BOTH); return f; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFrame f = getFrame(c);\r\n if (f != null)\r\n f.setExtendedState(JFrame...."; } }); if (!isAWTThread()) { Dimension d = maximumWindowBounds().getSize(); long start = sysNow(); while (licensed()) { try { if (f.getWidth() >= d.getWidth() - 100 && f.getHeight() >= d.getHeight() - 100) break; if (sysNow() >= start + 100) { warn("maximizeFrame timeout"); break; } } catch (Throwable __e) { _handleException(__e); } sleep(1); } } return f; } public static volatile boolean framesBot_has; public static Android3 framesBot() { if (framesBot_has) return null; framesBot_has = true; Android3 android = new Android3(); android.greeting = programIDPlusHome() + " Frames."; android.console = false; android.responder = new Responder() { public String answer(String s, List history) { if (match("activate frames", s)) { swingLater(new Runnable() { public void run() { try { activateMyFrames(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// prevent blocking when called from same program's AWT thread\r\n act..."; } }); return "OK, activating " + programName(); } return null; } }; return makeBot(android); } public static ThreadLocal> showConceptsTable_dropFields = new ThreadLocal(); public static ThreadLocal showConceptsTable_postProcess = new ThreadLocal(); public static ThreadLocal showConceptsTable_afterUpdate = new ThreadLocal(); public static ThreadLocal showConceptsTable_concepts = new ThreadLocal(); public static int makeConceptsTable_idWidth = 50; public static JTable showConceptsTable(Class c) { JTable table = makeConceptsTable(c); showFrame(plural(shortClassName(c)), table); return table; } public static JTable makeConceptsTable(final Class c) { List dropFields = getAndClearThreadLocal(showConceptsTable_dropFields); final Object pp = getAndClearThreadLocal(showConceptsTable_postProcess); final Object afterUpdate = optParam(showConceptsTable_afterUpdate); final Concepts concepts = optParam(showConceptsTable_concepts, db_mainConcepts()); final List fields = listMinusList(concatLists(ll("id"), conceptFieldsInOrder(c)), dropFields); final JTable table = sexyTable(); tablePopupMenu(table, new VF2() { public void get(JPopupMenu menu, final Integer row) { try { addMenuItem(menu, "Delete", new Runnable() { public void run() { try { final long id = toLong(getTableCell(table, row, 0)); withDBLock(new Runnable() { public void run() { try { deleteConcept(id); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "deleteConcept(id)"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final long id = toLong(getTableCell(table, row, 0));\r\n withDBLock(r { de..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, \"Delete\", r {\r\n final long id = toLong(getTableCell(ta..."; } }); awtOnConceptChanges(table, new Runnable() { public void run() { try { List data = new ArrayList(); for (final Concept cc : list(concepts, c)) data.add(map(new F1() { public Object get(String field) { try { return renderForTable(cget(cc, field)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "renderForTable(cget(cc, field))"; } }, fields)); data = (List) postProcess(pp, data); fillTableWithData(table, data, map("humanizeFormLabel", fields)); if (table.getColumnCount() > 0) table.getColumnModel().getColumn(0).setMaxWidth(makeConceptsTable_idWidth); pcallF(afterUpdate, table); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "//print(\"Updating concept table\");\r\n new List data;\r\n for (final ..."; } }, true); return table; } public static JTable makeConceptsTable(final Class cClass, final Object renderer) { if (renderer == null) return makeConceptsTable(cClass); final Object pp = optParam(showConceptsTable_postProcess); final Object afterUpdate = optParam(showConceptsTable_afterUpdate); final Concepts concepts = optParam(showConceptsTable_concepts); final JTable table = sexyTable(); awtOnConceptChanges(table, 1000, new Runnable() { public void run() { try { List data = new ArrayList(); for (A c : list(concepts, cClass)) addIfNotNull(data, (Map) pcallF(renderer, c)); data = (List) postProcess(pp, data); dataToTable_uneditable(data, table); pcallF(afterUpdate, table); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new List data;\r\n for (A c : list(concepts, cClass))\r\n addIfNotNu..."; } }); return table; } public static JTable showConceptsTable(final Class c, final Object f) { JTable table = makeConceptsTable(c, f); showFrame(plural(shortClassName(c)), table); return table; } public static JTable showConceptsTable(String title, Class cClass, Object f) { return setFrameTitle(title, showConceptsTable(cClass, f)); } public static JPanel jRightAlignedLine(Component... components) { return jrightAlignedLine(components); } public static JPanel jRightAlignedLine(List components) { return jrightAlignedLine(components); } public static JButton tableDependButton(JTable tbl, JButton b) { tableDependButtons(tbl, ll(b)); return b; } public static JButton tableDependButton(JTable tbl, String text, Object action) { return tableDependButton(tbl, jbutton(text, action)); } public static A selectedConcept(JTable table, Class cc) { return (A) getConcept(toLong(selectedTableCell(table, 0))); } public static class TableSearcher { public JTable table; public JTextField tfInput; public JComponent searchPanel, panel; public F2 rowTester; public List rowIndices; public String input() { return gtt(tfInput); } } public static TableSearcher tableWithSearcher2(final JTable t, Object... __) { final TableSearcher s = new TableSearcher(); s.table = t; s.tfInput = jtextfield(); s.rowTester = new F2() { public Boolean get(String pat, Map row) { try { return anyValueContainsIgnoreCase(row, pat); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "anyValueContainsIgnoreCase(row, pat)"; } }; onUpdate(s.tfInput, new Runnable() { public List lastFiltered, lastOriginal; public void run() { String pat = s.input(); List> data = rawTableData(t); if (eq(lastFiltered, data)) data = lastOriginal; List data2 = new ArrayList(); List rowIndices = new ArrayList(); for (int i = 0; i < l(data); i++) { Map map = data.get(i); if (isTrue(callF(s.rowTester, pat, map))) { data2.add(map); rowIndices.add(i); } } lastFiltered = data2; lastOriginal = data; dataToTable(t, data2); s.rowIndices = rowIndices; } }); s.searchPanel = withLabel("Search:", s.tfInput); JComponent top = s.searchPanel; s.panel = boolOptPar(__, "withMargin") ? northAndCenterWithMargin(top, t) : northAndCenter(top, t); return s; } public static JPanel centerAndSouthWithMargin(Component c, Component s) { return centerAndSouth(c, withTopMargin(s)); } public static Concept getConcept(long id) { return db_mainConcepts().getConcept(id); } public static A getConcept(Class cc, long id) { return getConcept(db_mainConcepts(), cc, id); } public static A getConcept(Concepts concepts, Class cc, long id) { Concept c = concepts.getConcept(id); if (c == null) return null; if (!isInstance(cc, c)) throw fail("Can't convert concept: " + getClassName(c) + " -> " + getClassName(cc) + " (" + id + ")"); return (A) c; } public static long toLong(Object o) { if (o instanceof Number) return ((Number) o).longValue(); if (o instanceof String) return parseLong((String) o); return 0; } public static Object getTableCell(JTable tbl, int row, int col) { if (row >= 0 && row < tbl.getModel().getRowCount()) return tbl.getModel().getValueAt(row, col); return null; } public static void tablePopupMenuItem(final JTable table, final String name, final Object action) { tablePopupMenu(table, new VF2() { public void get(JPopupMenu menu, final Integer row) { try { addMenuItem(menu, name, new Runnable() { public void run() { try { pcallF(action, row); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, row)"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, name, r { pcallF(action, row) });"; } }); } public static JList onDoubleClick(final JList list, final Object runnable) { { swing(new Runnable() { public void run() { try { list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { int idx = list.locationToIndex(evt.getPoint()); Object item = list.getModel().getElementAt(idx); list.setSelectedIndex(idx); callF(runnable, item); } } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "list.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(Mous..."; } }); } return list; } public static JTable onDoubleClick(final JTable table, final Object runnable) { { swing(new Runnable() { public void run() { try { table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { int idx = table.rowAtPoint(evt.getPoint()); table.setRowSelectionInterval(idx, idx); callF(runnable, idx); } } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "table.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(Mou..."; } }); } return table; } public static void onDoubleClick(final JComponent c, final Object runnable) { { swing(new Runnable() { public void run() { try { c.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getButton() == 1 && evt.getClickCount() == 2) callF(runnable, evt.getPoint()); } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(MouseEv..."; } }); } } public static void register(Concept c) { db_mainConcepts().register(c); } public static AutoCloseable tempSetMCOpt(final String field, Object value) { final Object oldValue = getMCOpt(field); setMCOpt(field, value); return new AutoCloseable() { public String toString() { return "setMCOpt(field, oldValue);"; } public void close() throws Exception { setMCOpt(field, oldValue); } }; } public static JPanel showFormTitled2(String title, Object... parts) { return showFormTitled_customLayout(formLayouter1(), title, parts); } public static Object[] arrayPlus(Object[] a1, Object... a2) { return concatArrays(a1, a2); } public static Object[] mapToObjectArray(Map map) { List l = new ArrayList(); for (Object o : keys(map)) { l.add(o); l.add(map.get(o)); } return toObjectArray(l); } public static Object selectedTableCell(JTable t, int col) { return getTableCell(t, selectedTableRow(t), col); } public static Object selectedTableCell(final JTable t) { return swing(new F0() { public Object get() { try { return selectedTableCell(t, t.getSelectedColumn()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret selectedTableCell(t, t.getSelectedColumn());"; } }); } public static Object selectedTableCell(final JTable t, final String colName) { return swing(new F0() { public Object get() { try { return selectedTableCell(t, tableColumnViewIndex(t, colName)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret selectedTableCell(t, tableColumnViewIndex(t, colName));"; } }); } public static Class getFieldType(Object o, String field) { return fieldType(o, field); } public static JCheckBox jCenteredCheckBox() { return centerCheckBox(new JCheckBox()); } public static JCheckBox jCenteredCheckBox(boolean checked) { return centerCheckBox(new JCheckBox("", checked)); } public static JCheckBox jCenteredCheckBox(String text, boolean checked) { return centerCheckBox(new JCheckBox(text, checked)); } public static JCheckBox jCenteredCheckBox(String text) { return centerCheckBox(new JCheckBox(text)); } public static JCheckBox jCenteredCheckBox(String text, boolean checked, final Object onChange) { return centerCheckBox(jCheckBox(text, checked, onChange)); } public static JCheckBox jCenteredCheckBox(boolean checked, final Object onChange) { return centerCheckBox(jCheckBox(checked, onChange)); } public static JTextArea typeWriterTextArea() { return newTypeWriterTextArea(); } public static JTextArea typeWriterTextArea(String text) { return newTypeWriterTextArea(text); } public static AutoComboBox autoComboBox() { return autoComboBox(new ArrayList()); } public static AutoComboBox autoComboBox(final Collection items) { return swing(new F0() { public AutoComboBox get() { try { AutoComboBox cb = new AutoComboBox(); cb.setKeyWord(items); return cb; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new AutoComboBox cb;\r\n cb.setKeyWord(items);\r\n ret cb;"; } }); } public static AutoComboBox autoComboBox(String value, Collection items) { return setText(autoComboBox(items), value); } public static void printException(Throwable e) { printStackTrace(e); } public static JTextField jTextField() { return jTextField(""); } public static JTextField jTextField(final String text) { return swing(new F0() { public JTextField get() { try { JTextField tf = new JTextField(unnull(text)); standardTextFieldPopupMenu(tf); jenableUndoRedo(tf); tf.selectAll(); return tf; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JTextField tf = new JTextField(unnull(text));\r\n standardTextFieldPopupMenu..."; } }); } public static JTextField jTextField(Object o) { return jTextField(strOrEmpty(o)); } public static JComponent unwrap(JComponent c) { return c instanceof JScrollPane ? unwrapScrollPane((JScrollPane) c) : c; } public static Object convertToField(Object o, Class c, String field) { Field f = setOpt_findField(c, field); if (f == null) return o; Class t = f.getType(); if (t == Long.class || t == long.class) return toLong(o); else if (t == Integer.class || t == int.class) return toInt(o); else if (t == String.class) return o instanceof String ? (String) o : str(o); else if (t == File.class) if (o instanceof String) return new File((String) o).getAbsoluteFile(); return o; } public static String trimIf(boolean b, String s) { return b ? trim(s) : s; } public static String getText(final AbstractButton c) { return c == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getText();"; } }); } public static String getText(final JTextComponent c) { return c == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getText();"; } }); } public static String getText(final JLabel l) { return l == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return l.getText(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret l.getText();"; } }); } public static String getText(final JComboBox cb) { if (cb == null) return null; if (isEditableComboBox(cb)) return unnull((String) cb.getEditor().getItem()); else return str(cb.getSelectedItem()); } public static String getTextTrim(JTextComponent c) { return trim(getText(c)); } public static String getTextTrim(JComboBox cb) { return trim(getText(cb)); } public static String getTextTrim(JComponent c) { if (c instanceof JLabel) return trim(((JLabel) c).getText()); if (c instanceof JComboBox) return getTextTrim((JComboBox) c); return getTextTrim((JTextComponent) c); } public static boolean isChecked(final 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 "ret checkBox.isSelected();"; } }); } public static boolean isChecked(final 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 "ret mi.isSelected();"; } }); } public static void cUpdatePNGFile(Concept c, String field, BufferedImage image, boolean deleteOldFile) { PNGFile png = (PNGFile) (cget(c, field)); if (image == null && png != null) cset(c, field, null); else if (image != null && (png == null || !imagesIdentical(png.getImage(), image))) { if (png != null && deleteOldFile) png.delete(); cset(c, field, new PNGFile(image)); } } public static Set fields(Object c) { return listFields(c); } public static List listWithoutSet(Collection l, Collection stuff) { return listMinusSet(l, stuff); } public static List conceptFieldsInOrder(Concept c) { return conceptFieldsInOrder(c.getClass()); } public static List conceptFieldsInOrder(Class c) { String order = toStringOpt(getOpt(c, "_fieldOrder")); Set set = asTreeSet(conceptFields(c)); if (order == null) return asList(set); List fields = splitAtSpace(order); setAddAll(fields, set); return fields; } public static Set setPlus(Collection l, A... more) { Set set = similarEmptySet(l); addAll(set, l); for (A a : more) set.add(a); return set; } public static Map> setTableModel_after = weakHashMap(); public static Map> setTableModel_fixSorter = weakHashMap(); public static void setTableModel(final JTable table, final TableModel model) { { swing(new Runnable() { public void run() { try { Map widths = tableColumnWidthsByName(table); int[] i = table.getSelectedRows(); TableRowSorter sorter = model.getColumnCount() == tableColumnCount(table) ? (TableRowSorter) table.getRowSorter() : null; List sortKeys = sorter == null ? null : sorter.getSortKeys(); table.setModel(model); int n = model.getRowCount(); ListSelectionModel sel = table.getSelectionModel(); for (int j = 0; j < i.length; j++) if (i[j] < n) sel.addSelectionInterval(i[j], i[j]); tableSetColumnPreferredWidths(table, widths); if (sorter != null) { sorter.setModel(model); callF(setTableModel_fixSorter.get(table), table, sorter); if (sortKeys != null) sorter.setSortKeys(sortKeys); } table.setRowSorter(sorter); callF(setTableModel_after.get(table), table); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Map widths = tableColumnWidthsByName(table);\r\n int[] i = ..."; } }); } } public static String structureOrText(Object o) { return o instanceof String ? (String) o : structure(o); } public static List lookupAllOpt(Map map, Collection l) { List out = new ArrayList(); if (l != null) for (A a : l) addIfNotNull(out, map.get(a)); return out; } public static List lookupAllOpt(Collection l, Map map) { return lookupAllOpt(map, l); } public static Iterator emptyIterator() { return Collections.emptyIterator(); } public static long sysNow() { ping(); return System.nanoTime() / 1000000; } public static int tableNumColumns(final JTable table) { return swing(new F0() { public Integer get() { try { return table.getColumnCount(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret table.getColumnCount();"; } }); } public static boolean containsSpace(String s) { return containsSpaces(s); } public static String joinWithSpace(Collection c) { return join(" ", c); } public static String joinWithSpace(String... c) { return join(" ", c); } public static List replaceElementsUsingMap(Iterable l, final Map map) { return map(l, new F1() { public A get(A a) { try { return getOrKeep(map, a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getOrKeep(map, a)"; } }); } public static List splitCamelCase(String s) { return ai_splitCamelCase(s); } public static A revalidate(final A c) { if (c == null || !c.isShowing()) return c; { swing(new Runnable() { public void run() { try { c.revalidate(); c.repaint(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// magic combo to actually relayout and repaint\r\n c.revalidate();\r\n c.r..."; } }); } return c; } public static void revalidate(RootPaneContainer c) { revalidate((Component) c); } public static void revalidate(JFrame f) { revalidate((Component) f); } public static void revalidate(JInternalFrame f) { revalidate((Component) f); } public static boolean newButton_autoToolTip = true; public static JButton newButton(final String text, final Object action) { return swing(new F0() { public JButton get() { try { String text2 = dropPrefix("[disabled] ", text); final JButton btn = new JButton(text2); if (l(text2) < l(text)) btn.setEnabled(false); if (newButton_autoToolTip) { btn.setToolTipText(btn.getText()); } if (action != null) btn.addActionListener(actionListener(action, btn)); return btn; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "S text2 = dropPrefix(\"[disabled] \", text);\r\n final JButton btn = new JButt..."; } }); } public static A swingNu(final Class c, final Object... args) { return swingConstruct(c, args); } public static void onConceptsChangeAndNow(Runnable r) { onConceptsChange(r); callF(r); } public static List findConceptsWhere(Class c, Object... params) { return findConceptsWhere(db_mainConcepts(), c, params); } public static List findConceptsWhere(String c, Object... params) { return findConceptsWhere(db_mainConcepts(), c, params); } public static List findConceptsWhere(Concepts concepts, Class c, Object... params) { 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) { List 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); } public static List findConceptsWhere(Concepts concepts, String c, Object... params) { return filterConcepts(concepts.list(c), params); } public static String makeFrame_defaultIcon; public static boolean makeFrame_hideConsole; public static ThreadLocal> makeFrame_post = new ThreadLocal(); public static JFrame makeFrame() { return makeFrame((Component) null); } public static JFrame makeFrame(Object content) { return makeFrame(programTitle(), content); } public static JFrame makeFrame(String title) { return makeFrame(title, null); } public static JFrame makeFrame(String title, Object content) { return makeFrame(title, content, true); } public static 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) ..."; } }); } public static boolean frameTooSmall(JFrame frame) { return frame.getWidth() < 100 || frame.getHeight() < 50; } public static void frameStandardSize(JFrame frame) { frame.setBounds(300, 100, 500, 400); } public static void setFrameContents(final Component c, final Object contents) { { swing(new Runnable() { public void run() { try { JFrame frame = getFrame(c); frame.getContentPane().removeAll(); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(wrap(contents)); revalidate(frame); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFrame frame = getFrame(c);\r\n frame.getContentPane().removeAll();\r\n fra..."; } }); } } public static JFrame getFrame(final Object _o) { return swing(new F0() { public JFrame get() { try { Object o = _o; if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof JFrame) return (JFrame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; } }); } public static Rectangle maximumWindowBounds() { return maxWindowBounds(); } public static String programIDPlusHome() { String s = fsI(programID()); String home = userHomeIfNotActual(); if (home != null) s += " " + quote(home); return s; } public static void swingLater(long delay, final Object r) { javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r))); timer.setRepeats(false); timer.start(); } public static void swingLater(Object r) { SwingUtilities.invokeLater(toRunnable(r)); } public static List activateMyFrames() { final List l = myFrames(); { swing(new Runnable() { public void run() { try { for (JFrame f : l) activateFrame(f); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "for (JFrame f : l)\r\n activateFrame(f);"; } }); } return l; } public static String programName() { return getProgramName(); } public static List listMinusList(Collection l, Collection stuff) { if (empty(stuff) && l instanceof List) return (List) l; List l2 = cloneList(l); for (Object o : stuff) l2.remove(o); return l2; } public static boolean sexyTable_drag = false; public static JTable sexyTable() { final JTable table = sexyTableWithoutDrag(); if (sexyTable_drag) tableEnableTextDrag(table); return table; } public static void addMenuItem(JPopupMenu menu, String text, Object action) { menu.add(jmenuItem(text, action)); } public static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) { menu.add(menuItem); } public static void addMenuItem(JMenu menu, String text, Object action) { menu.add(jmenuItem(text, action)); } public static void addMenuItem(Menu menu, String text, Object action) { menu.add(menuItem(text, action)); } public static void addMenuItem(JMenu menu, JMenuItem menuItem) { menu.add(menuItem); } public static void deleteConcept(long id) { db_mainConcepts().deleteConcept(id); } public static void deleteConcept(Concept c) { if (c != null) c.delete(); } public static void deleteConcept(Concept.Ref ref) { if (ref != null) deleteConcept(ref.get()); } public static int awtOnConceptChanges_defaultDelay = 1000; public static void awtOnConceptChanges(Component component, Object runnable) { awtOnConceptChanges(componentToJComponent(component), runnable, true); } public static void awtOnConceptChanges(JComponent component, final Object runnable, boolean runOnFirstTime) { awtOnConceptChanges(component, awtOnConceptChanges_defaultDelay, 0, runnable, runOnFirstTime); } public static void awtOnConceptChanges(JComponent component, int delay, final Object runnable) { awtOnConceptChanges(component, delay, delay, runnable); } public static void awtOnConceptChanges(JComponent component, int delay, int firstDelay, Object runnable) { awtOnConceptChanges(component, delay, firstDelay, runnable, true); } public static boolean awtOnConceptChanges_debug; public static void awtOnConceptChanges(JComponent component, int delay, int firstDelay, final Object runnable, final boolean runOnFirstTime) { installTimer(component, delay, firstDelay, new Runnable() { public long c = runOnFirstTime ? -1 : changeCount(); public void run() { long _c = changeCount(); if (awtOnConceptChanges_debug) print("awtOnConceptChanges: " + _c + " / " + c); if (_c != c) { c = _c; call(runnable); } } }); } public static Object renderForTable(Object o) { return or(toBufferedImageOpt(o), o); } public static A postProcess(Object f, A a) { return callPostProcessor(f, a); } public static void fillTableWithData(final JTable table, List rows, List colNames) { fillTableWithData(table, rows, toStringArray(colNames)); } public static void fillTableWithData(final JTable table, List rows, String... colNames) { final DefaultTableModel model = fillTableWithData_makeModel(rows, colNames); setTableModel(table, model); } public static DefaultTableModel fillTableWithData_makeModel(List rows, String... colNames) { Pair p = fillTableWithData_makeData(rows, colNames); return new DefaultTableModel(p.a, p.b) { public Class getColumnClass(int column) { return or(_getClass(getValueAt(0, column)), String.class); } public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } }; } public static JTable dataToTable_uneditable(Object data, final JTable table) { return dataToTable_uneditable(table, data); } public static JTable dataToTable_uneditable(final JTable table, final Object data) { { swing(new Runnable() { public void run() { try { dataToTable(table, data, true); makeTableUneditable(table); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "dataToTable(table, data, true);\r\n makeTableUneditable(table);"; } }); } return table; } public static JTable dataToTable_uneditable(final Object data) { return dataToTable_uneditable(showTable(), data); } public static JTable dataToTable_uneditable(Object data, String title) { return dataToTable_uneditable(showTable(title), data); } public static A setFrameTitle(A c, final String title) { final Frame f = getAWTFrame(c); if (f != null) { swing(new Runnable() { public void run() { try { f.setTitle(title); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.setTitle(title);"; } }); } return c; } public static A setFrameTitle(String title, A c) { return setFrameTitle(c, title); } public static JFrame setFrameTitle(String title) { Object f = getOpt(mc(), "frame"); if (f instanceof JFrame) return setFrameTitle((JFrame) f, title); return null; } public static JPanel jrightAlignedLine(final Component... components) { return swing(new F0() { public RightAlignedLine get() { try { return new RightAlignedLine(components); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret RightAlignedLine(components);"; } }); } public static JPanel jrightAlignedLine(List components) { return jrightAlignedLine(asArray(Component.class, components)); } public static void tableDependButtons(final JTable table, List buttons) { for (Component c : buttons) if (c instanceof JButton) { final JButton b = (JButton) (c); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { b.setEnabled(table.getSelectedRow() >= 0); } }); b.setEnabled(table.getSelectedRow() >= 0); } } public static JTextField jtextfield() { return jTextField(); } public static JTextField jtextfield(String text) { return jTextField(text); } public static JTextField jtextfield(Object o) { return jTextField(o); } public static boolean anyValueContainsIgnoreCase(Map map, String pat) { for (Object val : values(map)) if (val instanceof String && containsIgnoreCase((String) val, pat)) return true; return false; } public static void onUpdate(JComponent c, final Object r) { if (c instanceof JTextComponent) ((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { call(r); } public void removeUpdate(DocumentEvent e) { call(r); } public void changedUpdate(DocumentEvent e) { call(r); } }); else if (c instanceof ItemSelectable) ((ItemSelectable) c).addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { call(r); } }); else print("Warning: onUpdate doesn't know " + getClassName(c)); } public static void onUpdate(List l, Object r) { for (JComponent c : l) onUpdate(c, r); } public static List> rawTableData(JTable t) { int n = tableRows(t); List l = new ArrayList(); for (int i = 0; i < n; i++) l.add(rawTableLineAsMap(t, i)); return l; } public static JTable dataToTable(Object data) { return dataToTable(showTable(), data); } public static JTable dataToTable(Object data, String title) { return dataToTable(showTable(title), data); } public static JTable dataToTable(JTable table, Object data) { return dataToTable(table, data, false); } public static JTable dataToTable(JTable table, Object data, boolean now) { List rows = new ArrayList(); List cols = new ArrayList(); if (data instanceof List) { for (Object x : (List) data) { try { rows.add(dataToTable_makeRow(x, cols)); } catch (Throwable __e) { _handleException(__e); } } } else if (data instanceof Map) { Map map = (Map) (data); for (Object key : map.keySet()) { Object value = map.get(key); rows.add(litlist(structureOrTextForUser(key), structureOrTextForUser(value))); } } else if (data != null) print("Unknown data type: " + data); fillTableWithData(table, rows, cols); return table; } public static JComponent withLabel(String label, JComponent component) { return westAndCenter(jlabel(label + " "), component); } public static boolean boolOptPar(ThreadLocal tl) { return boolOptParam(tl); } public static boolean boolOptPar(Object[] __, String name) { return boolOptParam(__, name); } public static boolean boolOptPar(String name, Object[] __) { return boolOptParam(__, name); } public static JPanel northAndCenterWithMargin(Component n, Component c) { return northAndCenter(withBottomMargin(n), c); } public static JPanel northAndCenter(Component n, Component c) { return centerAndNorth(c, n); } public static JPanel centerAndSouth(final Component c, final Component s) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.CENTER, wrap(c)); if (s != null) panel.add(BorderLayout.SOUTH, wrap(s)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT..."; } }); } public static int withTopMargin_defaultWidth = 6; public static JPanel withTopMargin(Component c) { return withTopMargin(withTopMargin_defaultWidth, c); } public static JPanel withTopMargin(final int w, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createEmptyBorder(w, 0, 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..."; } }); } public static Object getMCOpt(String field) { return getOptMC(field); } public static void setMCOpt(String field, Object value) { setOptMC(field, value); } public static JPanel showFormTitled_customLayout(final F1 layouter, final String title, final Object... parts) { return showFormTitled_customArrangement(false, new F1, JPanel>() { public JPanel get(List components) { try { return customLayoutPanel(layouter, components); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "customLayoutPanel(layouter, components)"; } }, title, parts); } public static int formLayouter1_yPlus = 5; public static int formLayouter1_fixer2 = 0; public static F1 formLayouter1() { final int yplus = formLayouter1_yPlus, fixer2 = formLayouter1_fixer2; return new F1() { public Dimension get(Container parent) { try { List l = getComponents(parent); BitSet bigOnes = new BitSet(); for (int i = 0; i < l(l); i++) if (containsATextArea(l.get(i))) add(bigOnes, i); int nBigOnes = bigOnes.cardinality(); int mandatoryHeight = totalPreferredHeight(listWithoutIndicesInBitSet(l, bigOnes)); int gap = 4, outerSpacing = 5; Dimension size = parent.getSize(); int gapsAndMargins = outerSpacing * 2 - (l(l) - 1) * gap; int totalSpace = size.height - gapsAndMargins - fixer2; int liberalSpace = totalSpace - mandatoryHeight; double perBigOne = doubleRatio(liberalSpace, nBigOnes); double y = outerSpacing; for (int i = 0; i < l(l); i++) { Component c = l.get(i); boolean big = contains(bigOnes, i); double h = big ? perBigOne : c.getPreferredSize().height; int actualY = iround(y); c.setBounds(10, actualY, size.width - outerSpacing * 2, iround(y + h) - actualY); y += h + gap; } Dimension pref = componentsBoundingSize(parent, outerSpacing); if (parent.getHeight() == 0) pref.height = totalPreferredHeight(l) + gapsAndMargins + yplus; return pref; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "L l = getComponents(parent);\r\n new BitSet bigOnes;\r\n for i o..."; } }; } public static int selectedTableRow(final JTable t) { return t == null ? -1 : swing(new F0() { public Integer get() { try { return t.getSelectedRow(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret t.getSelectedRow();"; } }); } public static int tableColumnViewIndex(final JTable t, final String colName) { return swing(new F0() { public Integer get() { try { return t.convertColumnIndexToView(t.getColumn(colName).getModelIndex()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret t.convertColumnIndexToView(t.getColumn(colName).getModelIndex());"; } }); } public static JCheckBox centerCheckBox(JCheckBox cb) { return setHorizontalAlignment(SwingConstants.CENTER, cb); } public static JCheckBox jCheckBox() { return swingNu(JCheckBox.class); } public static JCheckBox jCheckBox(boolean checked) { return swingNu(JCheckBox.class, "", checked); } public static JCheckBox jCheckBox(String text, boolean checked) { return swingNu(JCheckBox.class, text, checked); } public static JCheckBox jCheckBox(String text) { return swingNu(JCheckBox.class, text); } public static JCheckBox jCheckBox(String text, boolean checked, final Object onChange) { JCheckBox cb = jCheckBox(checked, onChange); cb.setText(text); return cb; } public static JCheckBox jCheckBox(boolean checked, final Object onChange) { final JCheckBox cb = jCheckBox(checked); cb.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { pcallF(onChange, cb.isSelected()); } }); return cb; } public static JTextArea newTypeWriterTextArea() { return newTypeWriterTextArea(""); } public static JTextArea newTypeWriterTextArea(String text) { return setFont(jTextArea(text), typeWriterFont()); } public static boolean setText_opt = true; public static A setText(A c, Object text) { setText((Object) c, text); return c; } public static A setText(final A c, Object text) { final String s = strUnnull(text); { swing(new Runnable() { public void run() { try { c.getEditor().setItem(s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.getEditor().setItem(s);"; } }); } return c; } public static void setText(JLabel c, Object text) { setText((Object) c, text); } public static JButton setText(JButton c, Object text) { setText((Object) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text))); return c; } public static A setText(final A c, Object text) { if (c == null) return null; final String s = strUnnull(text); { swing(new Runnable() { public void run() { try { if (!setText_opt || neq(callOpt(c, "getText"), s)) call(c, "setText", s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n call(c, \"setText\", s);"; } }); } return c; } public static JTextField standardTextFieldPopupMenu(final JTextField tf) { final WeakReference ref = weakRef(tf); componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() { public void run() { try { copyTextToClipboard(ref.get().getText()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(ref.get().getText())"; } }); componentPopupMenuItem(tf, "Paste", new Runnable() { public void run() { try { ref.get().paste(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ref.get().paste()"; } }); return tf; } public static A jenableUndoRedo(final A textcomp) { { swing(new Runnable() { public void run() { try { final UndoManager undo = new UndoManager(); vm_generalWeakSet("Undo Managers").add(undo); textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent evt) { undo.addEdit(evt.getEdit()); } }); textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() { public void run() { try { if (undo.canUndo()) undo.undo(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canUndo()) undo.undo()"; } })); textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() { public void run() { try { if (undo.canRedo()) undo.redo(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canRedo()) undo.redo()"; } })); textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo"); textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new UndoManager undo;\r\n vm_generalWeakSet(\"Undo Managers\").add(undo)..."; } }); } return textcomp; } public static String strOrEmpty(Object o) { return o == null ? "" : str(o); } public static JComponent unwrapScrollPane(JScrollPane sp) { return sp == null ? null : (JComponent) sp.getViewport().getView(); } public static Field setOpt_findField(Class c, String field) { HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } return map.get(field); } public static void setOpt(Object o, String field, Object value) { try { if (o == null) return; Class c = o.getClass(); HashMap map; if (getOpt_cache == null) map = getOpt_makeCache(c); else synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } if (map == getOpt_special) { if (o instanceof Class) { setOpt((Class) o, field, value); return; } setOpt_raw(o, field, value); return; } Field f = map.get(field); if (f != null) smartSet(f, o, value); } catch (Exception __e) { throw rethrow(__e); } } public static void setOpt(Class c, String field, Object value) { if (c == null) return; try { Field f = setOpt_findStaticField(c, field); if (f != null) smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } public static Field setOpt_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) { f.setAccessible(true); return f; } _c = _c.getSuperclass(); } while (_c != null); return null; } public static 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 "ret cb.isEditable();"; } }); } public static boolean imagesIdentical(BufferedImage img1, BufferedImage img2) { if (img1 == null) return img2 == null; if (img2 == null) return false; int w = img1.getWidth(), h = img1.getHeight(); if (w != img2.getWidth() || h != img2.getHeight()) return false; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) if (img1.getRGB(x, y) != img2.getRGB(x, y)) return false; return true; } public static List listMinusSet(Iterable l, Collection stuff) { if (empty(stuff)) return asList(l); Set set = asSet(stuff); List l2 = new ArrayList(); for (A a : l) if (!set.contains(a)) l2.add(a); return l2; } public static String toStringOpt(Object o) { return o instanceof String ? ((String) o) : null; } public static TreeSet asTreeSet(List l) { TreeSet set = new TreeSet(); for (Object o : l) if (o != null) set.add(o); return set; } public static TreeSet asTreeSet(Set set) { return set instanceof TreeSet ? (TreeSet) set : new TreeSet(set); } public static String[] conceptFields_drop = { "className", "fieldValues", "id", "created", "refs", "backRefs", "_concepts" }; public static Set conceptFields(Concept c) { return setMinus(mergeSets(allNonStaticNonTransientFields(c), keys(c.fieldValues)), conceptFields_drop); } public static Set conceptFields(Class c) { return setMinus(allNonStaticNonTransientFields(c), conceptFields_drop); } public static List splitAtSpace(String s) { return empty(s) ? emptyList() : asList(s.split("\\s+")); } public static void setAddAll(List a, Collection b) { for (A x : b) setAdd(a, x); } public static Set similarEmptySet(Collection m) { if (m instanceof TreeSet) return new TreeSet(((TreeSet) m).comparator()); if (m instanceof LinkedHashSet) return new LinkedHashSet(); return new HashSet(); } public static Map weakHashMap() { return newWeakHashMap(); } public static Map tableColumnWidthsByName(JTable table) { TableColumnModel tcm = table.getColumnModel(); if (tcm == null) return null; int n = tcm.getColumnCount(); TreeMap map = new TreeMap(); for (int i = 0; i < n; i++) { TableColumn tc = tcm.getColumn(i); map.put(str(tc.getHeaderValue()), tc.getWidth()); } return map; } public static boolean tableSetColumnPreferredWidths_debug; public static void tableSetColumnPreferredWidths(final JTable table, final Map widths) { if (table == null || widths == null) return; { swing(new Runnable() { public void run() { try { try { TableColumnModel tcm = table.getColumnModel(); int n = tcm.getColumnCount(); for (int i = 0; i < n; i++) { TableColumn tc = tcm.getColumn(i); Integer w = widths.get(str(tc.getHeaderValue())); if (w != null) { tc.setPreferredWidth(w); if (tableSetColumnPreferredWidths_debug) print("Setting preferred width of column " + i + " to " + w); } } } catch (Throwable __e) { _handleException(__e); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall {\r\n TableColumnModel tcm = table.getColumnModel();\r\n int n = tcm...."; } }); } } public static void tableSetColumnPreferredWidths(JTable table, Object... widths) { tableSetColumnPreferredWidths(table, litorderedmap(widths)); } public static boolean containsSpaces(String s) { return indexOf(s, ' ') >= 0; } public static A getOrKeep(Map map, A a) { A v = map.get(a); return v != null ? v : a; } public static List ai_splitCamelCase(String s) { int j = 0; List l = new ArrayList(); for (int i = 0; i < l(s); i++) if (isUpperCaseLetter(s.charAt(i)) && i > j) { l.add(substring(s, j, i)); j = i; } if (j < l(s)) l.add(substring(s, j)); return l; } public static ActionListener actionListener(final Object runnable) { return actionListener(runnable, null); } public static ActionListener actionListener(final Object runnable, final Object instanceToHold) { if (runnable instanceof ActionListener) return (ActionListener) runnable; final Object info = _threadInfo(); return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { _threadInheritInfo(info); AutoCloseable __1052 = holdInstance(instanceToHold); try { callF(runnable); } finally { _close(__1052); } } catch (Throwable __e) { messageBox(__e); } } }; } public static A swingConstruct(final Class c, final Object... args) { return swing(new F0() { public A get() { try { return nuObject(c, args); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret nuObject(c, args);"; } }); } public static void onConceptsChange(Runnable r) { addConceptIndex(simpleConceptIndex(r)); } public static 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; } public static List filterConcepts(List list, Object... params) { List l = new ArrayList(); for (A x : list) if (checkConceptFields(x, params)) l.add(x); return l; } public static 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; } public static void _initFrame(JFrame f) { myFrames_list.put(f, Boolean.TRUE); standardTitlePopupMenu(f); } public static Component wrap(Object swingable) { return _recordNewSwingComponent(wrap_2(swingable)); } public static Component wrap_2(Object swingable) { if (swingable == null) return null; Component c; if (swingable instanceof Component) c = (Component) swingable; else c = (Component) callOpt(swingable, "swing"); if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree) return jscroll(c); return c == null ? jlabel(str(swingable)) : c; } public static Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400); public static Rectangle defaultNewFrameBounds() { return swing(new F0() { public Rectangle get() { try { defaultNewFrameBounds_r.translate(60, 20); if (!screenRectangle().contains(defaultNewFrameBounds_r)) defaultNewFrameBounds_r.setLocation(30 + random(30), 20 + random(20)); return new Rectangle(defaultNewFrameBounds_r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "defaultNewFrameBounds_r.translate(60, 20);\r\n if (!screenRectangle().contai..."; } }); } public static 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);"; } }); } } public static List buttonsInGroup(ButtonGroup g) { if (g == null) return ll(); return asList(g.getElements()); } public static Rectangle maxWindowBounds() { return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); } public static String userHomeIfNotActual() { String home = userHome(); return eq(home, actualUserHome()) ? null : home; } public static Map myFrames_list = weakHashMap(); public static List myFrames() { return swing(new F0>() { public List get() { try { return keysList(myFrames_list); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret keysList(myFrames_list);"; } }); } public static boolean activateFrame(final Component c) { return swing(new F0() { public Boolean get() { try { Frame f = getAWTFrame(c); if (f == null) return false; if (!f.isVisible()) f.setVisible(true); if (f.getState() == Frame.ICONIFIED) f.setState(Frame.NORMAL); if (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())..."; } }); } public static void tableEnableTextDrag(final JTable table) { TransferHandler th = new TransferHandler() { @Override public int getSourceActions(JComponent c) { return COPY; } @Override public Transferable createTransferable(JComponent c) { Object o = selectedTableCell(table); return new StringSelection(str(o)); } }; tableEnableDrag(table, th); } public static boolean jmenuItem_newThreads; public static JMenuItem jmenuItem(final String text) { return jMenuItem(text, null); } public static JMenuItem jmenuItem(final String text, final Object r) { return swing(new F0() { public JMenuItem get() { try { Pair p = jmenu_autoMnemonic(text); JMenuItem mi = new JMenuItem(p.a); if (p.b != 0) mi.setMnemonic(p.b); mi.addActionListener(jmenuItem_newThreads ? actionListenerInNewThread(r) : actionListener(r)); return mi; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Pair p = jmenu_autoMnemonic(text);\r\n JMenuItem mi = new JMenuItem(..."; } }); } public static MenuItem menuItem(String text, final Object r) { MenuItem mi = new MenuItem(text); mi.addActionListener(actionListener(r)); return mi; } public static 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)); } public static Timer installTimer(JComponent component, Object r, long delay) { return installTimer(component, r, delay, delay); } public static Timer installTimer(RootPaneContainer frame, long delay, Object r) { return installTimer(frame.getRootPane(), r, delay, delay); } public static Timer installTimer(JComponent component, long delay, Object r) { return installTimer(component, r, delay, delay); } public static Timer installTimer(JComponent component, long delay, long firstDelay, Object r) { return installTimer(component, r, delay, firstDelay); } public static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) { return installTimer(component, r, delay, firstDelay, true); } public static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) { if (component == null) return null; return (Timer) swingAndWait(new F0() { public Object get() { try { final Var timer = new Var(); timer.set(new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { AutoCloseable __1441 = tempActivity(r); try { try { if (!allPaused()) if (isFalse(callF(r))) cancelTimer(timer.get()); } catch (Throwable __e) { _handleException(__e); } } finally { _close(__1441); } } 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..."; } }); } public static Timer installTimer(RootPaneContainer frame, long delay, long firstDelay, Object r) { return installTimer(frame.getRootPane(), delay, firstDelay, r); } public static long changeCount() { return db_mainConcepts().changes; } public static BufferedImage toBufferedImageOpt(Object o) { if (o instanceof BufferedImage) return (BufferedImage) o; if (o instanceof MakesBufferedImage) return ((MakesBufferedImage) o).getBufferedImage(); if (o instanceof File) if (isImageFile(((File) o))) return loadImage2(((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; } public static A callPostProcessor(Object f, A a) { return f == null ? a : (A) callF(f, a); } public static Pair fillTableWithData_makeData(List rows, List colNames) { return fillTableWithData_makeData(rows, asStringArray(colNames)); } public static Pair fillTableWithData_makeData(List rows, String... colNames) { Object[][] data = new Object[rows.size()][]; int w = 0; for (int i = 0; i < rows.size(); i++) { List l = rows.get(i); Object[] r = new Object[l.size()]; for (int j = 0; j < l.size(); j++) { Object o = l.get(j); if (o instanceof BufferedImage) o = imageIcon((BufferedImage) o); if (o instanceof RGBImage) o = imageIcon((RGBImage) o); r[j] = o; } data[i] = r; w = Math.max(w, l.size()); } Object[] columnNames = new Object[w]; for (int i = 0; i < w; i++) columnNames[i] = i < l(colNames) ? colNames[i] : "?"; return pair(data, columnNames); } public static void makeTableUneditable(JTable table) { for (int c = 0; c < table.getColumnCount(); c++) { Class col_class = table.getColumnClass(c); table.setDefaultEditor(col_class, null); } } public static boolean showTable_searcher = true; public static JTable showTable(Object data) { return dataToTable_uneditable(data); } public static JTable showTable(String title, Object data) { return showTable(data, title); } public static JTable showTable(Object data, String title) { return dataToTable_uneditable(data, title); } public static JTable showTable(JTable table, Object data) { return showTable(table, data, autoFrameTitle()); } public static JTable showTable(Object data, JTable table) { return showTable(table, data); } public static JTable showTable(JTable table, Object data, String title) { if (table == null) table = showTable(data, title); else { setFrameTitle(table, title); dataToTable_uneditable(table, data); } return table; } public static JTable showTable() { return showTable(new ArrayList>(), new ArrayList()); } public static JTable showTable(String title) { return showTable(new ArrayList>(), new ArrayList(), title); } public static JTable showTable(List> rows, List cols) { return showTable(rows, cols, autoFrameTitle()); } public static JTable showTable(List> rows, List cols, String title) { JTable tbl = sexyTable(); fillTableWithStrings(tbl, rows, cols); showFrame(title, tbl); return tbl; } public static 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) ..."; } }); } public static Object[] asArray(List l) { return toObjectArray(l); } public static A[] asArray(Class type, List l) { return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size())); } public static int tableRows(JTable table) { return table.getRowCount(); } public static Map rawTableLineAsMap(JTable tbl, int row) { if (row >= 0 && row < tbl.getModel().getRowCount()) { Map map = litorderedmap(); for (int i = 0; i < tbl.getModel().getColumnCount(); i++) mapPut(map, tbl.getModel().getColumnName(i), tbl.getModel().getValueAt(row, i)); return map; } return null; } public static void dataToTable_dynSet(List l, int i, Object s) { while (i >= l.size()) l.add(""); l.set(i, s); } public static List dataToTable_makeRow(Object x, List cols) { if (instanceOf(x, "DynamicObject")) x = get_raw(x, "fieldValues"); if (x instanceof Map) { Map m = (Map) (x); List row = new ArrayList(); for (Object _field : keysWithoutHidden(m)) { String field = (String) (_field); Object value = m.get(field); int col = cols.indexOf(field); if (col < 0) { cols.add(field); col = cols.size() - 1; } dataToTable_dynSet(row, col, dataToTable_wrapValue(value)); } return row; } return litlist(structureOrText(x)); } public static Object dataToTable_wrapValue(Object o) { if (o instanceof BufferedImage) return o; if (o instanceof MakesBufferedImage) return ((MakesBufferedImage) o).getBufferedImage(); if (o instanceof RGBImage) return o; if (o instanceof Boolean) return o; return structureOrTextForUser(o); } public static String structureOrTextForUser(Object o) { return o instanceof String ? (String) o : structureForUser(o); } public static JPanel westAndCenter(final Component w, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.WEST, wrap(w)); panel.add(BorderLayout.CENTER, wrap(c)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST..."; } }); } public static JLabel jlabel(final String text) { return swingConstruct(BetterLabel.class, text); } public static JLabel jlabel() { return jlabel(" "); } public static boolean boolOptParam(ThreadLocal tl) { return isTrue(optPar(tl)); } public static boolean boolOptParam(Object[] __, String name) { return isTrue(optParam(__, name)); } public static int withBottomMargin_defaultWidth = 6; public static JPanel withBottomMargin(Component c) { return withBottomMargin(withBottomMargin_defaultWidth, c); } public static 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..."; } }); } public static 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..."; } }); } public static JPanel showFormTitled_customArrangement(final boolean internalFrame, final F1, JPanel> arrange, final String title, final Object... _parts) { return swing(new F0() { public JPanel get() { try { List out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts)); JPanel panel = callF(arrange, out); showForm_makeFrame(title, panel); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "L out = showForm_arrange1(showForm_makeComponents(internalFrame, ..."; } }); } public static JPanel customLayoutPanel(final Object layouter) { return jpanel(layoutManagerFromFunction(layouter)); } public static JPanel customLayoutPanel(final Object layouter, final List components) { return addAllComponents(customLayoutPanel(layouter), components); } public static 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 "ret ((Container) c).getComponents();"; } })); } public static boolean containsATextArea(Component c) { return childOfType(c, JTextArea.class) != null; } public static int totalPreferredHeight(List l) { int h = 0; for (Component c : unnull(l)) h += c.getPreferredSize().height; return h; } public static List listWithoutIndicesInBitSet(List l, BitSet bs) { List out = new ArrayList(); for (int i = 0; i < l(l); i++) if (!bs.get(i)) out.add(l.get(i)); return out; } public static double doubleRatio(double x, double y) { return y == 0 ? 0 : x / y; } public static int iround(double d) { return (int) Math.round(d); } public static int iround(Number n) { return iround(toDouble(n)); } public static Dimension componentsBoundingSize(Container container, int insetBottomRight) { Rectangle r = new Rectangle(0, 0, 0, 0); for (Component c : container.getComponents()) r = rectangleUnion(r, c.getBounds()); return new Dimension(r.x + r.width + insetBottomRight, r.y + r.height + insetBottomRight); } public static A setHorizontalAlignment(final int pos, final A a) { if (a != null) { swing(new Runnable() { public void run() { try { a.setHorizontalAlignment(pos); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setHorizontalAlignment(pos);"; } }); } return a; } public static A setHorizontalAlignment(final int pos, final A a) { if (a != null) { swing(new Runnable() { public void run() { try { a.setHorizontalAlignment(pos); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setHorizontalAlignment(pos);"; } }); } return a; } public static A setFont(final Font font, final A a) { if (a != null) { swing(new Runnable() { public void run() { try { a.setFont(font); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setFont(font);"; } }); } return a; } public static A setFont(A a, Font font) { return setFont(font, a); } public static A setFont(final String fontID, float fontSize, final A a) { return setFont(loadFont_cached(fontID, fontSize), a); } public static JTextArea jTextArea() { return jTextArea(""); } public static JTextArea jTextArea(final String text) { return swingNu(JTextArea.class, text); } public static Font typeWriterFont() { return typeWriterFont(iround(14 * getSwingFontScale())); } public static Font typeWriterFont(int size) { return new Font("Courier", Font.PLAIN, size); } public static String strUnnull(Object o) { return o == null ? "" : str(o); } public static String jlabel_textAsHTML_center_ifNeeded(String text) { if (swic(text, "") && ewic(text, "")) return text; if (!containsNewLines(text)) return text; return jlabel_textAsHTML_center(text); } public static A componentPopupMenuItem(A c, final String name, final Object action) { componentPopupMenu(c, new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, name, action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, name, action);"; } }); return c; } public static void componentPopupMenuItem(JComponent c, final JMenuItem menuItem) { componentPopupMenu(c, new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, menuItem); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, menuItem);"; } }); } public static String copyTextToClipboard(Object _text) { String text = str(_text); StringSelection selection = new StringSelection(text); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection); vmBus_send("newClipboardContents", text); return text; } public static Set vm_generalWeakSet(Object name) { synchronized (get(javax(), "generalMap")) { Set set = (Set) (vm_generalMap_get(name)); if (set == null) vm_generalMap_put(name, set = newWeakHashSet()); return set; } } public static AbstractAction abstractAction(String name, final Object runnable) { return new AbstractAction(name) { public void actionPerformed(ActionEvent evt) { pcallF(runnable); } }; } public static Set asSet(Object[] array) { HashSet set = new HashSet(); for (Object o : array) if (o != null) set.add(o); return set; } public static Set asSet(String[] array) { TreeSet set = new TreeSet(); for (String o : array) if (o != null) set.add(o); return set; } public static Set asSet(Iterable l) { if (l instanceof Set) return (Set) l; HashSet set = new HashSet(); for (A o : unnull(l)) if (o != null) set.add(o); return set; } public static Set setMinus(Set set, Object... stuff) { Set s2 = cloneSet(set); for (Object o : stuff) s2.remove(o); return s2; } public static Set mergeSets(Set... l) { return joinSets(l); } public static Set allNonStaticNonTransientFields(Object o) { TreeSet fields = new TreeSet(); Class _c = _getClass(o); do { for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) == 0) fields.add(f.getName()); _c = _c.getSuperclass(); } while (_c != null); return fields; } public static boolean setAdd(Collection c, A a) { if (c == null || c.contains(a)) return false; c.add(a); return true; } public static boolean isUpperCaseLetter(char c) { return Character.isUpperCase(c); } public static ThreadLocal> holdInstance_l = new ThreadLocal(); public static AutoCloseable holdInstance(Object o) { if (o == null) return null; listThreadLocalAdd(holdInstance_l, o); return new AutoCloseable() { public void close() { listThreadLocalPopLast(holdInstance_l); } }; } public static void messageBox(final String msg) { if (headless()) print(msg); else { swing(new Runnable() { public void run() { try { JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES..."; } }); } } public static void messageBox(Throwable e) { printStackTrace(e); messageBox(hideCredentials(innerException2(e))); } public static void addConceptIndex(IConceptIndex index) { db_mainConcepts().addConceptIndex(index); } public static IConceptIndex simpleConceptIndex(final Runnable r) { return new IConceptIndex() { public void update(Concept c) { pcallF(r); } public void remove(Concept c) { pcallF(r); } }; } public static int imageIcon_cacheSize = 10; public static boolean imageIcon_verbose; public static Map imageIcon_cache; public static Lock imageIcon_lock = lock(); public static ThreadLocal imageIcon_fixGIF = new ThreadLocal(); public static ImageIcon imageIcon(String imageID) { try { if (imageID == null) return null; Lock __2272 = imageIcon_lock; lock(__2272); 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(__2272); } } catch (Exception __e) { throw rethrow(__e); } } public static ImageIcon imageIcon(Image img) { return new ImageIcon(img); } public static ImageIcon imageIcon(RGBImage img) { return imageIcon(img.getBufferedImage()); } public static void standardTitlePopupMenu(final JFrame frame) { if (isSubstanceLAF()) titlePopupMenu(frame, new VF1() { public void get(JPopupMenu menu) { try { boolean alwaysOnTop = frame.isAlwaysOnTop(); menu.add(jmenuItem("Restart Program", "restart")); menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram")); menu.add(jmenuItem("Show Console", "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)"; } })); menu.add(jMenuItem("Shoot Window", new Runnable() { public void run() { try { shootWindowGUI_external(frame, 500); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "shootWindowGUI_external(frame, 500)"; } })); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n menu.add(jmenuItem(\"Restar..."; } }); } public static A _recordNewSwingComponent(A c) { if (c != null) callF((Object) vm_generalMap_get("newSwingComponentRegistry"), c); return c; } public static JScrollPane jscroll(final Component c) { return swing(new F0() { public JScrollPane get() { try { return new JScrollPane(c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret new JScrollPane(c);"; } }); } public static Rectangle screenRectangle() { return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); } public static Random random_random = new Random(); public static int random(int n) { return n <= 0 ? 0 : random_random.nextInt(n); } public static double random(double max) { return random() * max; } public static double random() { return random_random.nextInt(100001) / 100000.0; } public static double random(double min, double max) { return min + random() * (max - min); } public static int random(int min, int max) { return min + random(max - min); } public static A random(List l) { return oneOf(l); } public static A random(Collection c) { if (c instanceof List) return random((List) c); int i = random(l(c)); return collectionGet(c, i); } public static JFrame consoleFrame() { return (JFrame) getOpt(get(getJavaX(), "console"), "frame"); } public static void autoVMExit() { call(getJavaX(), "autoVMExit"); } public static List keysList(Map map) { return cloneListSynchronizingOn(keys(map), map); } public static void tableEnableDrag(final JTable table, TransferHandler th) { if (table.getDragEnabled()) { print("Table drag already enabled"); return; } table.setDragEnabled(true); table.setTransferHandler(th); table.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getButton() == 1 && e.getClickCount() == 1) table.getTransferHandler().exportAsDrag(table, e, TransferHandler.COPY); } }); } public static JMenuItem jMenuItem(final String text) { return jmenuItem(text); } public static JMenuItem jMenuItem(String text, Object r) { return jmenuItem(text, r); } public static Pair jmenu_autoMnemonic(String s) { int i = indexOf(s, '&'); if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i + 1))) return pair(substring(s, 0, i) + substring(s, i + 1), (int) s.charAt(i + 1)); return pair(s, 0); } public static ActionListener actionListenerInNewThread(final Object runnable) { return actionListenerInNewThread(runnable, null); } public static ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) { if (runnable instanceof ActionListener) return (ActionListener) runnable; return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { startThread("Action Listener", new Runnable() { public void run() { try { AutoCloseable __1226 = holdInstance(instanceToHold); try { callF(runnable); } finally { _close(__1226); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __1226 = holdInstance(instanceToHold); try {\r\n callF(runna..."; } }); } catch (Throwable __e) { messageBox(__e); } } }; } public static AutoCloseable tempActivity(Object r) { return null; } public static boolean allPaused() { return ping_pauseAll; } public static void cancelTimer(javax.swing.Timer timer) { if (timer != null) timer.stop(); } public static void cancelTimer(java.util.Timer timer) { if (timer != null) timer.cancel(); } public static void cancelTimer(Object o) { if (o instanceof java.util.Timer) cancelTimer((java.util.Timer) o); else if (o instanceof javax.swing.Timer) cancelTimer((javax.swing.Timer) o); else if (o instanceof AutoCloseable) { try { ((AutoCloseable) o).close(); } catch (Throwable __e) { _handleException(__e); } } } public static void bindTimerToComponent(final Timer timer, JFrame f) { bindTimerToComponent(timer, f.getRootPane()); } public static void bindTimerToComponent(final Timer timer, JComponent c) { if (c.isShowing()) timer.start(); c.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { timer.start(); } public void ancestorRemoved(AncestorEvent event) { timer.stop(); } public void ancestorMoved(AncestorEvent event) { } }); } public static boolean isImageFile(File f) { return isImageFileName(fileName(f)); } public static BufferedImage loadImage2(String snippetIDOrURL) { return loadBufferedImage(snippetIDOrURL); } public static BufferedImage loadImage2(File file) { return loadBufferedImage(file); } public static String[] asStringArray(Collection c) { return toStringArray(c); } public static String[] asStringArray(Object o) { return toStringArray(o); } public static String autoFrameTitle_value; public static String autoFrameTitle() { return autoFrameTitle_value != null ? autoFrameTitle_value : getProgramTitle(); } public static void autoFrameTitle(Component c) { setFrameTitle(getFrame(c), autoFrameTitle()); } public static void fillTableWithStrings(final JTable table, List> rows, List colNames) { fillTableWithStrings(table, rows, toStringArray(colNames)); } public static void fillTableWithStrings(final JTable table, List> rows, String... colNames) { final DefaultTableModel model = fillTableWithStrings_makeModel(rows, colNames); swingNowOrLater(new Runnable() { public void run() { try { setTableModel(table, model); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setTableModel(table, model);"; } }); } public static DefaultTableModel fillTableWithStrings_makeModel(List> rows, String... colNames) { Object[][] data = new Object[rows.size()][]; int w = 0; for (int i = 0; i < rows.size(); i++) { List l = rows.get(i); Object[] r = new Object[l.size()]; for (int j = 0; j < l.size(); j++) r[j] = l.get(j); data[i] = r; w = Math.max(w, l.size()); } Object[] columnNames = new Object[w]; for (int i = 0; i < w; i++) columnNames[i] = i < l(colNames) ? colNames[i] : "?"; return new DefaultTableModel(data, columnNames); } public static void mapPut(Map map, A key, B value) { if (map != null && key != null && value != null) map.put(key, value); } public static boolean instanceOf(Object o, String className) { if (o == null) return false; String c = o.getClass().getName(); return eq(c, className) || eq(c, "main$" + className); } public static boolean instanceOf(Object o, Class c) { if (c == null) return false; return c.isInstance(o); } public static List keysWithoutHidden(Map map) { return filter(keys(map), new F1() { public Boolean get(Object o) { try { return !eq(o, "[hidden]") && !isStringStartingWith(o, "[hidden] "); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "!eq(o, \"[hidden]\") && !isStringStartingWith(o, \"[hidden] \")"; } }); } public static List showForm_arrange1(List> l) { int minW = showForm_leftWidth(l); List out = new ArrayList(); for (List row : l) out.add(westAndCenter(withRightMargin(showForm_gapBetweenColumns, jMinWidth(minW, first(row))), second(row))); return out; } public static List> showForm_makeComponents(final Boolean internalFrame, Object... _parts) { List> l = new ArrayList(); List parts = asList(_parts); JButton submitButton = null; for (int i = 0; i < l(parts); i++) { final Object o = parts.get(i), next = get(parts, i + 1); if (o instanceof String && next instanceof Component) setComponentID((Component) next, (String) o); if (o instanceof Component || o instanceof String || next instanceof Component) { l.add(mapLL("wrapForSmartAdd", o == null ? new JPanel() : o instanceof String ? humanizeFormLabel((String) o) : o, next)); if (next instanceof JButton && submitButton == null) submitButton = (JButton) next; i++; } else if (isRunnable(o)) l.add(mapLL("wrapForSmartAdd", null, submitButton = jbutton(showFormSubmitButtonName(), new Runnable() { public void run() { try { Object result = call(o); if (neq(Boolean.FALSE, result)) { if (isTrue(internalFrame)) disposeInternalFrame(heldInstance(JButton.class)); else if (isFalse(internalFrame)) disposeFrame(heldInstance(JButton.class)); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object result = call(o);\r\n if (neq(Boolean.FALSE, result)) {\r\n ..."; } }))); else print("showForm: Unknown element type: " + getClassName(o)); } if (submitButton != null) { final JButton _submitButton = submitButton; onEnterInAllTextFields(concatLists(l), new Runnable() { public void run() { try { clickButton(_submitButton); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "clickButton(_submitButton)"; } }); } for (List row : l) { JComponent left = first(row); if (left instanceof JLabel) makeBold((JLabel) left).setVerticalAlignment(JLabel.TOP); } return l; } public static JFrame showForm_makeFrame(String title, JPanel panel) { return handleEscapeKey(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400)); } public static JPanel jpanel(LayoutManager layout) { return swingNu(JPanel.class, layout); } public static JPanel jpanel() { return swingNu(JPanel.class); } public static LayoutManager layoutManagerFromFunction(final Object layouter) { return new AbstractLayoutManager() { public void layoutContainer(Container parent) { Dimension size = (Dimension) (callF(layouter, parent)); if (size != null) preferredSize = size; } }; } public static A addAllComponents(final A c, final List components) { if (nempty(components)) { swing(new Runnable() { public void run() { try { for (Component x : components) c.add(x); revalidate(c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "for (Component x : components)\r\n c.add(x);\r\n revalidate(c);"; } }); } return c; } public static A childOfType(Component c, Class theClass) { return first(childrenOfType(c, theClass)); } public static A childOfType(Class theClass, Component c) { return childOfType(c, theClass); } public static double toDouble(Object o) { if (o instanceof Number) return ((Number) o).doubleValue(); if (o instanceof BigInteger) return ((BigInteger) o).doubleValue(); if (o == null) return 0.0; throw fail(o); } public static Rectangle rectangleUnion(Rectangle a, Rectangle b) { return a == null ? b : b == null ? a : a.union(b); } public static Map loadFont_cached_cache = new HashMap(); public static synchronized Font loadFont_cached(String snippetID) { try { snippetID = formatSnippetID(snippetID); Font f = loadFont_cached_cache.get(snippetID); if (f == null) loadFont_cached_cache.put(snippetID, f = loadFont(snippetID, 12f)); return f; } catch (Exception __e) { throw rethrow(__e); } } public static synchronized Font loadFont_cached(String snippetID, float size) { try { return loadFont_cached(snippetID).deriveFont(size); } catch (Exception __e) { throw rethrow(__e); } } public static float getSwingFontScale() { return or((Float) vm_generalMap_get("swingFontScale_value"), 1f); } public static boolean containsNewLines(String s) { return containsNewLine(s); } public static String jlabel_textAsHTML_center(String text) { return "
" + replace(htmlencode(text), "\n", "
") + "
"; } public static Object vm_generalMap_put(Object key, Object value) { return mapPutOrRemove(vm_generalMap(), key, value); } public static
Set newWeakHashSet() { return synchroWeakHashSet(); } public static Set cloneSet(Set set) { if (set == null) return new HashSet(); synchronized (collectionMutex(set)) { Set s = similarEmptySet(set); s.addAll(set); return s; } } public static Set joinSets(Set... l) { TreeSet set = new TreeSet(); for (Set o : l) if (o != null) set.addAll(o); return set; } public static void duplicateThisProgram() { nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs")))); } public static void showConsole() { callOpt(get(javax(), "console"), "showConsole"); } public static int showForm_defaultGap = 4; public static int showForm_gapBetweenColumns = 10; public static JPanel showFormTitled(final String title, final Object... _parts) { JDesktopPane desktop = mainDesktopPane(); if (desktop != null) return showInternalFrameFormTitled(desktop, title, _parts); return swing(new F0() { public JPanel get() { try { final Var frame = new Var(); JPanel panel = showForm_makePanel(false, _parts); frame.set(showForm_makeFrame(title, panel)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new Var frame;\r\n JPanel panel = showForm_makePanel(false, _p..."; } }); } public static JPanel showForm_makePanel(Boolean internalFrame, Object... _parts) { List out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts)); return vstackWithSpacing(out, showForm_defaultGap); } public static void listThreadLocalAdd(ThreadLocal> tl, A a) { List l = tl.get(); if (l == null) tl.set(l = new ArrayList()); l.add(a); } public static A listThreadLocalPopLast(ThreadLocal> tl) { List l = tl.get(); if (l == null) return null; A a = popLast(l); if (empty(l)) tl.set(null); return a; } public static File loadBinarySnippet(String snippetID) { try { long id = parseSnippetID(snippetID); File f = DiskSnippetCache_getLibrary(id); if (fileSize(f) == 0) f = loadDataSnippetToFile(snippetID); return f; } catch (Exception __e) { throw rethrow(__e); } } public static boolean loadBufferedImageFixingGIFs_debug; public static ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal(); public static 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); } } public static boolean isSubstanceLAF() { return substanceLookAndFeelEnabled(); } public static 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; } } public static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) { final JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked); addActionListener(mi, new Runnable() { public void run() { try { callF(r, isChecked(mi)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(r, isChecked(mi))"; } }); return mi; } public static void toggleAlwaysOnTop(JFrame frame) { frame.setAlwaysOnTop(!frame.isAlwaysOnTop()); } public static void shootWindowGUI_external(JFrame frame) { call(hotwireOnce("#1007178"), "shootWindowGUI", frame); } public static void shootWindowGUI_external(final JFrame frame, int delay) { call(hotwireOnce("#1007178"), "shootWindowGUI", frame, delay); } public static A oneOf(List l) { return l.isEmpty() ? null : l.get(new Random().nextInt(l.size())); } public static char oneOf(String s) { return empty(s) ? '?' : s.charAt(random(l(s))); } public static String oneOf(String... l) { return oneOf(asList(l)); } public static 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; } public static ArrayList cloneListSynchronizingOn(Collection l, Object mutex) { if (l == null) return new ArrayList(); synchronized (mutex) { return new ArrayList(l); } } public static boolean isLetterOrDigit(char c) { return Character.isLetterOrDigit(c); } public static boolean isImageFileName(String s) { return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif"); } public static String fileName(File f) { return f == null ? null : f.getName(); } public static boolean loadBufferedImage_useImageCache = true; public static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try { if (snippetIDOrURLOrFile == null) return null; if (isURL(snippetIDOrURLOrFile)) return imageIO_readURL(snippetIDOrURLOrFile); if (isAbsolutePath(snippetIDOrURLOrFile)) return loadBufferedImage(new File(snippetIDOrURLOrFile)); if (!isSnippetID(snippetIDOrURLOrFile)) throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile); String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile); 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; } catch (Exception __e) { throw rethrow(__e); } } public static BufferedImage loadBufferedImage(File file) { try { return file.isFile() ? ImageIO.read(file) : null; } catch (Exception __e) { throw rethrow(__e); } } public static void swingNowOrLater(Runnable r) { if (isAWTThread()) r.run(); else swingLater(r); } public static boolean isStringStartingWith(Object o, String prefix) { return o instanceof String && ((String) o).startsWith(prefix); } public static int showForm_leftWidth(List> l) { int minW = 0; for (List row : l) minW = max(minW, getMinimumSize(first(row)).width); return minW; } public static int withRightMargin_defaultWidth = 6; public static JPanel withRightMargin(Component c) { return withRightMargin(withRightMargin_defaultWidth, c); } public static JPanel withRightMargin(final int w, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, w)); p.add(c); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat..."; } }); } public static A jMinWidth(final int w, final A c) { if (c == null) return null; return swing(new F0() { public A get() { try { Dimension size = c.getMinimumSize(); c.setMinimumSize(new Dimension(w, size.height)); return jPreferWidth(w, c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Dimension size = c.getMinimumSize();\r\n c.setMinimumSize(new Dimension(/*ma..."; } }); } public static void setComponentID(Component c, String id) { if (c != null) componentID_map.put(c, id); } public static List mapLL(Object f, Object... data) { return map(f, ll(data)); } public static Component wrapForSmartAdd(Object o) { if (o == null) return jpanel(); if (o instanceof String) return jlabel((String) o); return wrap(o); } public static boolean isRunnable(Object o) { return o instanceof Runnable || hasMethod(o, "get"); } public static String showFormSubmitButtonName() { return "Submit"; } public static void disposeInternalFrame(Component c) { final JInternalFrame f = getInternalFrame(c); if (f != null) { swing(new Runnable() { public void run() { try { f.dispose(); setOpt(f, "lastFocusOwner", null); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.dispose();\r\n setOpt(f, \"lastFocusOwner\" , null); // Help GC"; } }); } } public static A heldInstance(Class c) { List l = holdInstance_l.get(); for (int i = l(l) - 1; i >= 0; i--) { Object o = l.get(i); if (isInstanceOf(o, c)) return (A) o; } throw fail("No instance of " + className(c) + " held"); } public static void disposeFrame(final Component c) { disposeWindow(c); } public static void onEnterInAllTextFields(JComponent c, Object action) { if (action == null) return; for (Component tf : allChildren(c)) onEnterIfTextField(tf, action); } public static void onEnterInAllTextFields(List c, Object action) { for (Object o : unnull(c)) if (o instanceof JComponent) onEnterInAllTextFields((JComponent) o, action); } public static void clickButton(final JButton b) { if (b != null) { swing(new Runnable() { public void run() { try { if (b.isEnabled()) b.doClick(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (b.isEnabled())\r\n b.doClick();"; } }); } } public static A makeBold(final A c) { if (c != null) { swing(new Runnable() { public void run() { try { c.setFont(c.getFont().deriveFont(Font.BOLD)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.setFont(c.getFont().deriveFont(Font.BOLD));"; } }); } return c; } public static JFrame handleEscapeKey(final JFrame frame) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); frame.getRootPane().registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { frame.dispose(); } }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); return frame; } public static JFrame minFrameWidth(JFrame frame, int w) { if (frame != null && frame.getWidth() < w) frame.setSize(w, frame.getHeight()); return frame; } public static JFrame minFrameWidth(int w, JFrame frame) { return minFrameWidth(frame, w); } public static JFrame showPackedFrame(String title, Component contents) { return packFrame(showFrame(title, contents)); } public static JFrame showPackedFrame(Component contents) { return packFrame(showFrame(contents)); } public static List childrenOfType(Component c, Class theClass) { List l = new ArrayList(); scanForComponents(c, theClass, l); return l; } public static List childrenOfType(Class theClass, Component c) { return childrenOfType(c, theClass); } public static Font loadFont(String snippetID) { try { return loadFont(snippetID, 12f); } catch (Exception __e) { throw rethrow(__e); } } public static Font loadFont(InputStream in) { try { return Font.createFont(Font.TRUETYPE_FONT, in); } catch (Exception __e) { throw rethrow(__e); } } public static Font loadFont(String snippetID, float fontSize) { return loadFont(loadLibrary(snippetID), fontSize); } public static Font loadFont(File f, float fontSize) { try { return Font.createFont(Font.TRUETYPE_FONT, f).deriveFont(fontSize); } catch (Exception __e) { throw rethrow(__e); } } public static Font loadFont(InputStream in, float fontSize) { try { return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(fontSize); } catch (Exception __e) { throw rethrow(__e); } } public static boolean containsNewLine(String s) { return contains(s, '\n'); } public static List replace(List l, A a, A b) { for (int i = 0; i < l(l); i++) if (eq(l.get(i), a)) l.set(i, b); return l; } public static String replace(String s, String a, String b) { return s == null ? null : a == null || b == null ? s : s.replace(a, b); } public static String replace(String s, char a, char b) { return s == null ? null : s.replace(a, b); } public static String htmlencode(Object o) { return htmlencode(str(o)); } public static String htmlencode(String s) { if (s == null) return ""; StringBuilder out = new StringBuilder(Math.max(16, s.length())); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') out.append("&#").append((int) c).append(';'); else out.append(c); } return out.toString(); } public static B mapPutOrRemove(Map map, A key, B value) { if (map != null && key != null) if (value != null) return map.put(key, value); else return map.remove(key); return null; } public static Set synchroWeakHashSet() { return Collections.newSetFromMap((Map) newWeakHashMap()); } public static Map componentID_map = weakHashMap(); public static String componentID(Component c) { return c == null ? null : componentID_map.get(c); } public static String smartJoin(String[] args) { 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); } public static String smartJoin(List args) { return smartJoin(toStringArray(args)); } public static JDesktopPane mainDesktopPane_value; public static JDesktopPane mainDesktopPane() { return mainDesktopPane_value; } public static JPanel showInternalFrameFormTitled(final JDesktopPane desktop, final String title, final Object... _parts) { JPanel panel = showForm_makePanel(true, _parts); showForm_makeInternalFrame(desktop, title, panel); return panel; } public static int vstackWithSpacing_default = 10; public static JPanel vstackWithSpacing(final List parts) { return vstackWithSpacing(parts, vstackWithSpacing_default); } public static JPanel vstackWithSpacing(final List parts, final int spacing) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.insets = new Insets(spacing / 2, 0, spacing / 2, 0); smartAddWithLayout(panel, gbc, toObjectArray(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..."; } }); } public static JPanel vstackWithSpacing(Component... parts) { return vstackWithSpacing(asList(parts), vstackWithSpacing_default); } public static 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 void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { saveBinaryFile(DiskSnippetCache_file(snippetID), data); } public static byte[] loadDataSnippetImpl(String snippetID) throws IOException { byte[] data; try { URL url = new URL(dataSnippetLink(snippetID)); print("Loading library: " + hideCredentials(url)); try { data = loadBinaryPage(url.openConnection()); } catch (RuntimeException e) { data = null; } if (data == null || data.length == 0) { url = new URL("http://data.tinybrain.de/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; } public static long fileSize(String path) { return getFileSize(path); } public static long fileSize(File f) { return getFileSize(f); } public static File loadDataSnippetToFile(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("http://data.tinybrain.de/blobs/" + psI(snippetID))); 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) { printStackTrace(e); errors.add(e); throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors)); } return f; } catch (Exception __e) { throw rethrow(__e); } } public static byte[] isGIF_magic = bytesFromHex("47494638"); public static boolean isGIF(byte[] data) { return byteArrayStartsWith(data, isGIF_magic); } public static boolean isGIF(File f) { return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic))); } public static void setVar(IVar v, A value) { if (v != null) v.set(value); } public static boolean substanceLookAndFeelEnabled() { return startsWith(getLookAndFeel(), "org.pushingpixels."); } public static 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; } public static RootPaneContainer getPossiblyInternalFrame(Component c) { JInternalFrame f = getInternalFrame(c); if (f != null) return f; return optCast(RootPaneContainer.class, getWindow(c)); } public static void addActionListener(JTextField tf, final Runnable action) { onEnter(tf, action); } public static void addActionListener(final JComboBox cb, final Runnable action) { if (cb != null) { swing(new Runnable() { public void run() { try { cb.addActionListener(actionListener(action)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.addActionListener(actionListener(action));"; } }); } } public static void addActionListener(final AbstractButton b, final Runnable action) { if (b != null) { swing(new Runnable() { public void run() { try { b.addActionListener(actionListener(action)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "b.addActionListener(actionListener(action));"; } }); } } public static A listGet(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } public static boolean eqicOneOf(String s, String... l) { for (String x : l) if (eqic(s, x)) return true; return false; } public static boolean isURL(String s) { return startsWithOneOf(s, "http://", "https://", "file:"); } public static BufferedImage imageIO_readURL(String url) { try { if (startsWith(url, "https:")) disableCertificateValidation(); return ImageIO.read(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } public static boolean isAbsolutePath(String s) { return s != null && new File(s).isAbsolute(); } public static boolean isAbsolutePath(File f) { return f != null && f.isAbsolute(); } public static File imageSnippetsCacheDir() { return javaxCachesDir("Image-Snippets"); } public static String snippetImageURL_http(String snippetID) { return snippetImageURL_http(snippetID, "png"); } public static String snippetImageURL_http(String snippetID, String contentType) { return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080"); } public static Dimension getMinimumSize(final Component c) { return c == null ? null : swing(new F0() { public Dimension get() { try { return c.getMinimumSize(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getMinimumSize();"; } }); } public static A jPreferWidth(int w, A c) { Dimension size = c.getPreferredSize(); c.setPreferredSize(new Dimension(w, size.height)); return c; } public static boolean hasMethod(Object o, String method, Object... args) { return findMethod(o, method, args) != null; } public static JInternalFrame getInternalFrame(final Object _o) { return _o == null ? null : swing(new F0() { public JInternalFrame get() { try { Object o = _o; if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof JInternalFrame) return (JInternalFrame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; } }); } public static boolean isInstanceOf(Object o, Class type) { return type.isInstance(o); } public static void disposeWindow(final Window window) { if (window != null) { swing(new Runnable() { public void run() { try { window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); myFrames_list.remove(window); window.dispose(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //..."; } }); } } public static void disposeWindow(final Component c) { disposeWindow(getWindow(c)); } public static void disposeWindow(Object o) { if (o != null) disposeWindow(((Component) o)); } public static void disposeWindow() { disposeWindow(heldInstance(Component.class)); } public static List allChildren(Component c) { return childrenOfType(c, Component.class); } public static void onEnterIfTextField(Component c, Object action) { if (action == null) return; if (c instanceof JTextField) onEnter((JTextField) c, action); else if (c instanceof JComboBox) onEnter((JComboBox) c, action); } public static int packFrame_minw = 150, packFrame_minh = 50; public static A packFrame(final A c) { { swing(new Runnable() { public void run() { try { Window w = getWindow(c); if (w != null) { w.pack(); int maxW = getScreenWidth() - 50, maxH = getScreenHeight() - 50; w.setSize(min(maxW, max(w.getWidth(), packFrame_minw)), min(maxH, max(w.getHeight(), packFrame_minh))); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Window w = getWindow(c);\r\n if (w != null) {\r\n w.pack();\r\n int ma..."; } }); } return c; } public static JFrame packFrame(ButtonGroup g) { return packFrame(getFrame(g)); } public static void scanForComponents(final Component c, final Class theClass, final List l) { if (theClass.isInstance(c)) l.add((A) c); if (c instanceof Container) { swing(new Runnable() { public void run() { try { for (Component comp : ((Container) c).getComponents()) scanForComponents(comp, theClass, l); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "for (Component comp : ((Container) c).getComponents())\r\n scanForComponen..."; } }); } } public static File loadLibrary(String snippetID) { return loadBinarySnippet(snippetID); } public static JInternalFrame showForm_makeInternalFrame(JDesktopPane desktop, String title, JPanel panel) { JInternalFrame f = addInternalFrame(desktop, title, withMargin(panel)); minInternalFrameWidth(f, 400); packInternalFrameVertically(f); centerInternalFrame(f); return f; } public static JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) { for (Object o : parts) panel.add(wrapForSmartAdd(o), layout); return panel; } public static JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) { return smartAddWithLayout(panel, layout, asList(flattenArray2(parts))); } public static Component jrigid() { return javax.swing.Box.createRigidArea(new Dimension(0, 0)); } public static File getGlobalCache() { File file = new File(javaxCachesDir(), "Binary Snippets"); file.mkdirs(); return file; } 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); } } public static byte[] saveBinaryFile(File fileName, byte[] contents) { return saveBinaryFile(fileName.getPath(), contents); } public static String dataSnippetLink(String snippetID) { long id = parseSnippetID(snippetID); if (id >= 1100000 && id < 1200000) return imageServerURL() + id; if (id >= 1400000 && id < 1500000) return "http://butter.botcompany.de:8080/files/" + id + "?_pass=" + muricaPassword(); if (id >= 1200000 && id < 1300000) { String pw = muricaPassword(); if (empty(pw)) throw fail("Please set 'murica password by running #1008829"); return "http://butter.botcompany.de:8080/1008823/raw/" + id + "?_pass=" + pw; } else return "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=application/binary"; } public static ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal(); public static ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal(); public static byte[] loadBinaryPage(String url) { try { print("Loading " + url); return loadBinaryPage(loadPage_openConnection(new URL(url))); } catch (Exception __e) { throw rethrow(__e); } } public static byte[] loadBinaryPage(URLConnection con) { try { Map extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders); setHeaders(con); for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key)); return loadBinaryPage_noHeaders(con); } catch (Exception __e) { throw rethrow(__e); } } public static byte[] loadBinaryPage_noHeaders(URLConnection con) { try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); InputStream inputStream = con.getInputStream(); loadBinaryPage_responseHeaders.set(con.getHeaderFields()); long len = 0; try { len = con.getContentLength(); } 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 long getFileSize(String path) { return path == null ? 0 : new File(path).length(); } public static long getFileSize(File f) { return f == null ? 0 : f.length(); } public static A addAndReturn(Collection c, A a) { if (c != null) c.add(a); return a; } public static void loadBinaryPageToFile(String url, File file) { try { print("Loading " + url); loadBinaryPageToFile(openConnection(new URL(url)), file); } catch (Exception __e) { throw rethrow(__e); } } public static void loadBinaryPageToFile(URLConnection con, File file) { try { setHeaders(con); loadBinaryPageToFile_noHeaders(con, file); } catch (Exception __e) { throw rethrow(__e); } } public static void loadBinaryPageToFile_noHeaders(URLConnection con, File file) { try { File ftemp = new File(f2s(file) + "_temp"); FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp)); try { InputStream inputStream = con.getInputStream(); long len = 0; try { len = con.getContentLength(); } 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); } } public static URLConnection openConnection(URL url) { try { ping(); callOpt(javax(), "recordOpenURLConnection", str(url)); return url.openConnection(); } catch (Exception __e) { throw rethrow(__e); } } public static List allToString(Collection c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } public static List allToString(Object[] c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } public static byte[] bytesFromHex(String s) { return hexToBytes(s); } public static boolean byteArrayStartsWith(byte[] a, byte[] b) { if (a == null || b == null) return false; if (a.length < b.length) return false; for (int i = 0; i < b.length; i++) if (a[i] != b[i]) return false; return true; } public static byte[] loadBeginningOfBinaryFile(File file, int maxBytes) { return loadBinaryFilePart(file, 0, maxBytes); } public static String getLookAndFeel() { return getClassName(UIManager.getLookAndFeel()); } public static JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) { return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane"); } public static A optCast(Class c, Object o) { return isInstance(c, o) ? (A) o : null; } public static Window getWindow(Object o) { if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof Window) return (Window) c; c = c.getParent(); } return null; } public static JTextField onEnter(final JTextField tf, final Object action) { if (action == null || tf == null) return tf; tf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { tf.selectAll(); callF(action); } catch (Throwable __e) { messageBox(__e); } } }); return tf; } public static JButton onEnter(JButton btn, final Object action) { if (action == null || btn == null) return btn; btn.addActionListener(actionListener(action)); return btn; } public static JList onEnter(JList list, Object action) { list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action))); return list; } public static JComboBox onEnter(final JComboBox cb, final Object action) { { swing(new Runnable() { public void run() { try { if (cb.isEditable()) { JTextField text = (JTextField) cb.getEditor().getEditorComponent(); onEnter(text, action); } else { cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter"); cb.getActionMap().put("enter", abstractAction("", new Runnable() { public void run() { try { cb.hidePopup(); callF(action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.hidePopup(); callF(action);"; } })); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (cb.isEditable()) {\r\n JTextField text = (JTextField) cb.getEditor().g..."; } }); } return cb; } public static JTable onEnter(final JTable table, final Object action) { table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter"); table.getActionMap().put("Enter", new AbstractAction() { public void actionPerformed(ActionEvent e) { callF(action, table.getSelectedRow()); } }); return table; } public static JTextField onEnter(Object action, JTextField tf) { return onEnter(tf, action); } public static boolean startsWithOneOf(String s, String... l) { for (String x : l) if (startsWith(s, x)) return true; return false; } public static volatile boolean disableCertificateValidation_attempted; public static void disableCertificateValidation() { try { if (disableCertificateValidation_attempted) return; disableCertificateValidation_attempted = true; try { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (Throwable __e) { _handleException(__e); } } catch (Exception __e) { throw rethrow(__e); } } public static String snippetImageURL(String snippetID) { return snippetImageURL(snippetID, "png"); } public static String snippetImageURL(String snippetID, String contentType) { if (isURL(snippetID)) return snippetID; long id = parseSnippetID(snippetID); String url; if (id == 1000010 || id == 1000012) url = "http://tinybrain.de:8080/tb/show-blobimage.php?id=" + id; else if (isImageServerSnippet(id)) url = imageServerLink(id); else url = "https://www.botcompany.de:8443/img/" + id; return url; } public static Method findMethod(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Method m = findMethod_static((Class) o, method, args, false); if (m == null) return null; m.setAccessible(true); return m; } else { Method m = findMethod_instance(o, method, args, false); if (m == null) return null; m.setAccessible(true); return m; } } catch (Exception e) { throw new RuntimeException(e); } } public static Method findMethod_static(Class c, String method, Object[] args, boolean debug) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters"); ; if (!m.getName().equals(method)) { if (debug) System.out.println("Method name mismatch: " + method); continue; } if ((m.getModifiers() & Modifier.STATIC) == 0 || !findMethod_checkArgs(m, args, debug)) continue; return m; } c = c.getSuperclass(); } return null; } public static Method findMethod_instance(Object o, String method, Object[] args, boolean debug) { Class c = o.getClass(); while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters"); ; if (m.getName().equals(method) && findMethod_checkArgs(m, args, debug)) return m; } c = c.getSuperclass(); } return null; } public static boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } public static int getScreenWidth() { return getScreenSize().width; } public static int getScreenHeight() { return getScreenSize().height; } public static ThreadLocal addInternalFrame_dontSelect = new ThreadLocal(); public static ThreadLocal addInternalFrame_layer = new ThreadLocal(); public static ThreadLocal addInternalFrame_toBack = new ThreadLocal(); public static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h) { return addInternalFrame(desktop, title, x, y, w, h, null); } public static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h, final Component contents) { return addInternalFrame(desktop, title, rect(x, y, w, h), contents); } public static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Component contents) { return addInternalFrame(desktop, title, null, contents); } public static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Rect r, final Component contents) { final boolean dontSelect = isTrue(optParam(addInternalFrame_dontSelect)); final boolean toBack = isTrue(optParam(addInternalFrame_toBack)); final Integer layer = optParam(addInternalFrame_layer); return swing(new F0() { public JInternalFrame get() { try { JInternalFrame frame; if (contents instanceof JInternalFrame) frame = (JInternalFrame) contents; else { frame = jInternalFrame(title); setInternalFrameContents(frame, contents); } frame.setVisible(true); desktop.add(frame, layer); if (r != null) setBounds(frame, r); else internalFrameDefaultPosition(frame); if (dontSelect) if (toBack) frame.toBack(); else frame.toFront(); else frame.setSelected(true); return fixInternalFrame(frame); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JInternalFrame frame;\r\n if (contents instanceof JInternalFrame)\r\n fra..."; } }); } public static JInternalFrame addInternalFrame(JDesktopPane desktop, String title) { return addInternalFrame(desktop, title, jpanel()); } public static JInternalFrame minInternalFrameWidth(final JInternalFrame frame, final int w) { { swing(new Runnable() { public void run() { try { if (frame != null && frame.getWidth() < w) frame.setSize(w, frame.getHeight()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (frame != null && frame.getWidth() < w)\r\n frame.setSize(w, frame.getH..."; } }); } return frame; } public static JInternalFrame minInternalFrameWidth(int w, JInternalFrame frame) { return minInternalFrameWidth(frame, w); } public static A packInternalFrameVertically(A c) { return packInternalFrameVertically(-1, c); } public static A packInternalFrameVertically(int width, A c) { final JInternalFrame win = getInternalFrame(c); if (win == null) return c; final int w = width < 0 ? win.getWidth() : width; { swing(new Runnable() { public void run() { try { win.pack(); win.setSize(w, win.getHeight()); fixInternalFrame(win); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "win.pack();\r\n win.setSize(w, win.getHeight());\r\n fixInternalFrame(win);"; } }); } return c; } public static JInternalFrame centerInternalFrame(final JInternalFrame f) { { swing(new Runnable() { public void run() { try { Container c = f.getParent(); if (c != null) { f.setLocation((c.getWidth() - f.getWidth()) / 2, (c.getHeight() - f.getHeight()) / 2); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Container c = f.getParent();\r\n if (c != null) {\r\n //print(\"Container ..."; } }); } return f; } public static JInternalFrame centerInternalFrame(final int w, final int h, final JInternalFrame f) { { swing(new Runnable() { public void run() { try { f.setSize(w, h); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.setSize(w, h);"; } }); } return centerInternalFrame(f); } public static Object[] flattenArray2(Object... a) { List l = new ArrayList(); if (a != null) for (Object x : a) if (x instanceof Object[]) l.addAll(asList((Object[]) x)); else if (x instanceof Collection) l.addAll((Collection) x); else l.add(x); return asObjectArray(l); } public static int loadPage_defaultTimeout = 60000; public static ThreadLocal loadPage_charset = new ThreadLocal(); public static boolean loadPage_allowGzip = true, loadPage_debug; public static boolean loadPage_anonymous; public static int loadPage_verboseness = 100000; public static int loadPage_retries = 1; public static ThreadLocal loadPage_silent = new ThreadLocal(); public static volatile int loadPage_forcedTimeout; public static ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal(); public static ThreadLocal>> loadPage_responseHeaders = new ThreadLocal(); public static ThreadLocal> loadPage_extraHeaders = 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 (url.getProtocol().equals("https")) disableCertificateValidation(); 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 (loadPageThroughProxy_enabled) { print("Trying proxy because of: " + e); try { return loadPageThroughProxy(str(url)); } catch (Throwable e2) { print(" " + exceptionToStringShort(e2)); } } else if (loadPage_debug) print(exceptionToStringShort(e)); if (tries < loadPage_retries - 1) sleepSeconds(1); } throw e; } catch (Exception __e) { throw rethrow(__e); } } public static String loadPage_preprocess(String url) { if (url.startsWith("tb/")) url = tb_mainServer() + "/" + url; if (url.indexOf("://") < 0) url = "http://" + url; return url; } public static 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); } } public static String loadPage(URL url) { return loadPage(url.toExternalForm()); } public static String loadPage(URLConnection con, URL url) throws IOException { return loadPage(con, url, true); } public static String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException { Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders); 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 = con.getInputStream(); 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; } StringBuilder buf = new StringBuilder(); int n = 0; while (true) { int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; if ((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(); } } public static 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"); } public static 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; } public static A println(A a) { return print(a); } public static File mkdirsFor(File file) { return mkdirsForFile(file); } public static 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(total, 100000)))); total += n; } } catch (Exception __e) { throw rethrow(__e); } } public static void renameFile_assertTrue(File a, File b) { try { 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)); } catch (Exception __e) { throw rethrow(__e); } } public static 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); } } public static Component childWithClassNameEndingWith(Component c, String suffix) { if (endsWith(className(c), suffix)) return c; Component x; for (Component comp : getComponents(c)) if ((x = childWithClassNameEndingWith(comp, suffix)) != null) return x; return null; } public static KeyListener enterKeyListener(final Object action) { return new KeyAdapter() { public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_ENTER) pcallF(action); } }; } public static Runnable rCallOnSelectedListItem(final JList list, final Object action) { return new Runnable() { public void run() { try { pcallF(action, getSelectedItem(list)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, getSelectedItem(list))"; } }; } public static String imageServerLink(String md5OrID) { if (possibleMD5(md5OrID)) return "https://botcompany.de/images/md5/" + md5OrID; return imageServerLink(parseSnippetID(md5OrID)); } public static String imageServerLink(long id) { return "https://botcompany.de/images/" + id; } public static Dimension getScreenSize() { return Toolkit.getDefaultToolkit().getScreenSize(); } public static Rect rect(int x, int y, int w, int h) { return new Rect(x, y, w, h); } public static boolean jInternalFrame_iconifiable = true; public static JInternalFrame jInternalFrame() { return jInternalFrame(""); } public static JInternalFrame jInternalFrame(final String title) { return swing(new F0() { public JInternalFrame get() { try { JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame_iconifiable); f.setVisible(true); return f; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame..."; } }); } public static void setInternalFrameContents(final Component c, final Object contents) { { swing(new Runnable() { public void run() { try { JInternalFrame frame = getInternalFrame(c); if (frame == null) return; frame.getContentPane().removeAll(); frame.getContentPane().setLayout(new BorderLayout()); if (contents != null) frame.getContentPane().add(wrap(contents)); revalidate(frame); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JInternalFrame frame = getInternalFrame(c);\r\n if (frame == null) return;\r\n..."; } }); } } public static A setBounds(final int x, final int y, final int w, final int h, final A a) { if (a != null) { swing(new Runnable() { public void run() { try { a.setBounds(x, y, w, h); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setBounds(x, y, w, h);"; } }); } return a; } public static A setBounds(final A a, final Rect r) { if (a != null) { swing(new Runnable() { public void run() { try { a.setBounds(toRectangle(r)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setBounds(toRectangle(r));"; } }); } return a; } public static A setBounds(A a, int x, int y, int w, int h) { return setBounds(x, y, w, h, a); } public static void internalFrameDefaultPosition(JInternalFrame f) { f.setSize(500, 300); centerInternalFrame(f); } public static int fixInternalFrame_borderTopLeft = 0; public static int fixInternalFrame_borderBottomRight = 40; public static JInternalFrame fixInternalFrame(final JInternalFrame f) { return swing(new F0() { public JInternalFrame get() { try { Container c = f.getParent(); if (c == null) return f; Rect r = toRect(f.getBounds()); int a = fixInternalFrame_borderTopLeft, b = fixInternalFrame_borderBottomRight; Rect outer = new Rect(a, a, c.getWidth() - b, c.getHeight() - b); if (!rectContains(outer, r)) f.setLocation(max(a, min(r.x, outer.x2())), max(a, min(r.y, outer.y2()))); if (r.w > c.getWidth() || r.h > c.getHeight()) f.setSize(c.getWidth() - a, c.getHeight() - a); return f; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Container c = f.getParent();\r\n if (c == null) ret f;\r\n Rect r = toRect(..."; } }); } public static boolean networkAllowanceTest(String url) { return isAllowed("networkAllowanceTest", url); } public static final boolean loadPageThroughProxy_enabled = false; public static String loadPageThroughProxy(String url) { return null; } public static void sleepSeconds(double s) { if (s > 0) sleep(round(s * 1000)); } public static A printWithTime(A a) { print(hmsWithColons() + ": " + a); return a; } public static Map vm_generalSubMap(Object name) { synchronized (get(javax(), "generalMap")) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = synchroMap()); return map; } } public static String toHex(byte[] bytes) { return bytesToHex(bytes); } public static String toHex(byte[] bytes, int ofs, int len) { return bytesToHex(bytes, ofs, len); } public static 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; } public static int roundDownTo(int x, int n) { return x / n * n; } public static long roundDownTo(long x, long n) { return x / n * n; } public static String getSelectedItem(JList l) { return (String) l.getSelectedValue(); } public static String getSelectedItem(JComboBox cb) { return strOrNull(cb.getSelectedItem()); } public static boolean possibleMD5(String s) { return isMD5(s); } public static Rectangle toRectangle(Rect r) { return r == null ? null : r.getRectangle(); } public static Rect toRect(Rectangle r) { return r == null ? null : new Rect(r); } public static 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; } public static boolean rectContains(Rect a, Rect b) { return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2(); } public static volatile Object isAllowed_function; public static volatile boolean isAllowed_all = true; public static 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)); } public static long round(double d) { return Math.round(d); } public static String hmsWithColons() { return hmsWithColons(now()); } public static String hmsWithColons(long time) { return new SimpleDateFormat("HH:mm:ss").format(time); } public static String strOrNull(Object o) { return o == null ? null : str(o); } public static boolean isMD5(String s) { return l(s) == 32 && isLowerHexString(s); } public static boolean isLowerHexString(String s) { for (int i = 0; i < l(s); i++) { char c = s.charAt(i); if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { } else return false; } return true; } public static class Rect { public int x, y, w, h; public Rect() { } public Rect(Rectangle r) { x = r.x; y = r.y; w = r.width; h = r.height; } public Rect(int x, int y, int w, int h) { this.h = h; this.w = w; this.y = y; this.x = x; } public Rect(Pt p, int w, int h) { this.h = h; this.w = w; x = p.x; y = p.y; } public Rect(Rect r) { x = r.x; y = r.y; w = r.w; h = r.h; } public Rectangle getRectangle() { return new Rectangle(x, y, w, h); } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } public String toString() { return x + "," + y + " / " + w + "," + h; } public int x2() { return x + w; } public int y2() { return y + h; } public boolean contains(Pt p) { return contains(p.x, p.y); } public boolean contains(int _x, int _y) { return _x >= x && _y >= y && _x < x + w && _y < y + h; } public boolean empty() { return w <= 0 || h <= 0; } } public static class AutoComboBox extends JComboBox { public String[] keyWord = { "item1", "item2", "item3" }; public Vector myVector = new Vector(); public boolean acceptOnTab; public AutoComboBox() { setModel(new DefaultComboBoxModel(myVector)); setSelectedIndex(-1); setEditable(true); JTextField text = (JTextField) this.getEditor().getEditorComponent(); text.setFocusable(true); text.setText(""); text.addKeyListener(new ComboListener(this, myVector)); if (acceptOnTab) text.setFocusTraversalKeysEnabled(false); setMyVector(); } public void setKeyWord(String[] keyWord) { this.keyWord = keyWord; setMyVector(); } public void setKeyWord(Collection keyWord) { setKeyWord(toStringArray(keyWord)); } public final void setMyVector() { copyArrayToVector(keyWord, myVector); } public class ComboListener extends KeyAdapter { public JComboBox cb; public Vector vector; public ComboListener(JComboBox cb, Vector vector) { this.vector = vector; this.cb = cb; } public void keyPressed(KeyEvent key) { if (key.getKeyCode() == KeyEvent.VK_ENTER) return; if (key.getKeyCode() == KeyEvent.VK_ESCAPE) { cb.hidePopup(); return; } if (acceptOnTab && key.getKeyCode() == KeyEvent.VK_TAB) { _print("Have tab event (modifiers=" + key.getModifiers() + ")"); if ((key.getModifiers() & ActionEvent.SHIFT_MASK) == 0 && cb.isPopupVisible()) { cb.setSelectedIndex(0); cb.hidePopup(); } else swing_standardTabBehavior(key); return; } JTextField tf = (JTextField) (cb.getEditor().getEditorComponent()); if (tf.getCaretPosition() != l(tf.getText())) return; String text = ((JTextField) key.getSource()).getText(); Vector list = getFilteredList(text); if (nempty(list)) { cb.setModel(new DefaultComboBoxModel(list)); cb.setSelectedIndex(-1); tf.setText(text); cb.showPopup(); } else cb.hidePopup(); } public Vector getFilteredList(String text) { return new Vector(scoredSearch(text, vector)); } } } public static class PNGFile extends Concept { public String pngPath; public Rect r; public PNGFile() { } public PNGFile(String pngPath) { this.pngPath = pngPath; } public PNGFile(RGBImage img) { this(img.getBufferedImage()); } public File pngFile() { if (pngPath == null) { pngPath = _programID() + "/" + id + ".png"; change(); } return prepareFile(new File(javaxDataDir(), pngPath)); } public PNGFile(BufferedImage img) { savePNG(pngFile(), img); } public BufferedImage loadImage() { return loadImage2(pngFile()); } public BufferedImage getImage() { return loadImage(); } public BufferedImage getImageSafe() { try { return loadImage(); } catch (Throwable __e) { _handleException(__e); } return null; } public String md5() { try { return md5OfBufferedImage(getImage()); } catch (Throwable __e) { _handleException(__e); } return "-"; } public boolean hasImage() { return pngFile().exists(); } } public static class Pt { public int x, y; public Pt() { } public Pt(Point p) { x = p.x; y = p.y; } public Pt(int x, int y) { this.y = y; this.x = x; } public Point getPoint() { return new Point(x, y); } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } public String toString() { return x + ", " + y; } } public static class AlphanumComparator implements Comparator { public boolean ignoreCase; public final boolean isDigit(char ch) { return ((ch >= 48) && (ch <= 57)); } public final 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; } } public abstract static class AbstractLayoutManager implements LayoutManager { public Dimension preferredSize = new Dimension(100, 100); public void addLayoutComponent(String name, Component comp) { } public void removeLayoutComponent(Component comp) { } public Dimension preferredLayoutSize(Container parent) { layoutContainer(parent); return preferredSize; } public Dimension minimumLayoutSize(Container parent) { return new Dimension(10, 10); } } public abstract static class F2 { public abstract C get(A a, B b); } public static class RightAlignedLine extends JPanel { public RightAlignedLine(Component... components) { setLayout(LetterLayout.rightAlignedRow()); for (Component component : components) add(component); } public void add(String text) { add(new JLabel(text)); } } public static class LetterLayout implements LayoutManager { public String[] lines; public Map map = new TreeMap(); 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; public static final int STALACTITE = 1, LEFT_ALIGNED_ROW = 2, CENTERED_ROW = 3, FORM = 4, RIGHT_ALIGNED_ROW = 5; public boolean debug; 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()); } public static class DummyComponent extends JComponent { } public static class Cell { public boolean aux; public int minWidth, minHeight; public Component component; public int colspan, rowspan; public double weightX, weightY; } public static 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 removeLayoutComponent(Component component) { map.values().remove(component); } 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; } } } } public final 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); } public final boolean allWeightsZero(RC[] rcs) { for (int i = 0; i < rcs.length; i++) if (rcs[i].weightSum != 0.0) return false; return true; } public static int getMinimumHeight(Component c) { return c.getMinimumSize().height; } public final 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) }; } } public final String makeSingleRow(Container container) { Component[] components = container.getComponents(); StringBuffer buf = new StringBuffer(); map.clear(); for (int i = 0; i < components.length; i++) { String s = String.valueOf(makeAlternateIndexChar(i)); map.put(s, components[i]); buf.append(s); } return buf.toString(); } public static 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) { map.put(s, 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; } public final 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); } public static 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); } } public static boolean stdEq2(Object a, Object b) { if (a == null) return b == null; if (b == null) return false; if (a.getClass() != b.getClass()) return false; for (String field : allFields(a)) if (neq(getOpt(a, field), getOpt(b, field))) return false; return true; } public static int stdHash2(Object a) { if (a == null) return 0; return stdHash(a, toStringArray(allFields(a))); } public static void setSelectedIndex(final JList l, final int i) { if (l != null) { swing(new Runnable() { public void run() { try { l.setSelectedIndex(i); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "l.setSelectedIndex(i);"; } }); } } public static void setSelectedIndex(final JComboBox cb, final int i) { if (cb != null) { swing(new Runnable() { public void run() { try { cb.setSelectedIndex(i); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.setSelectedIndex(i);"; } }); } } public static void copyArrayToVector(Object[] array, Vector v) { v.clear(); v.addAll(toList(array)); } public static A _print(A a) { return print(a); } public static void _print() { print(); } public static void swing_standardTabBehavior(KeyEvent key) { if ((key.getModifiers() & ActionEvent.SHIFT_MASK) != 0) KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent(); else KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(); } public static List scoredSearch(String query, Iterable data) { Map scores = new HashMap(); List prepared = scoredSearch_prepare(query); for (String s : data) { int score = scoredSearch_score(s, prepared); if (score != 0) scores.put(s, score); } return keysSortedByValuesDesc(scores); } public static File prepareFile(File file) { return mkdirsForFile(file); } public static void savePNG(BufferedImage img, File file) { try { File tempFile = new File(file.getPath() + "_temp"); CriticalAction ca = beginCriticalAction("Save " + f2s(file)); try { ImageIO.write(img, "png", mkdirsFor(tempFile)); file.delete(); tempFile.renameTo(file); } finally { ca.done(); } } catch (Exception __e) { throw rethrow(__e); } } public static void savePNG(File file, BufferedImage img) { savePNG(img, file); } public static void savePNG(File file, RGBImage img) { savePNG(file, img.getBufferedImage()); } public static RGBImage loadImage(String snippetIDOrURL) { return new RGBImage(loadBufferedImage(snippetIDOrURL)); } public static RGBImage loadImage(File f) { return new RGBImage(loadBufferedImage(f)); } public static String md5OfBufferedImage(BufferedImage img) { return img == null ? null : rgbMD5(new RGBImage(img)); } public static Set allFields(Object o) { TreeSet fields = new TreeSet(); Class _c = _getClass(o); do { for (Field f : _c.getDeclaredFields()) fields.add(f.getName()); _c = _c.getSuperclass(); } while (_c != null); return fields; } public static int stdHash(Object a, String... fields) { if (a == null) return 0; int hash = getClassName(a).hashCode(); for (String field : fields) hash = hash * 2 + hashCode(getOpt(a, field)); return hash; } public static List scoredSearch_prepare(String query) { return splitAtSpace(query); } public static int scoredSearch_score(String s, List words) { int score = 0; for (String word : words) score += scoredSearch_score_single(s, word); return score; } public static int scoredSearch_score(String s, String query) { return scoredSearch_score(s, scoredSearch_prepare(query)); } public static List keysSortedByValuesDesc(final Map map) { List l = new ArrayList(map.keySet()); sort(l, mapComparatorDesc(map)); return l; } public static String rgbMD5(RGBImage img) { return md5OfRGBImage(img); } public static int hashCode(Object a) { return a == null ? 0 : a.hashCode(); } public static 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; } public static void sort(T[] a, Comparator c) { Arrays.sort(a, c); } public static void sort(T[] a) { Arrays.sort(a); } public static void sort(List a, Comparator c) { Collections.sort(a, c); } public static void sort(List a) { Collections.sort(a); } public static Comparator mapComparatorDesc(final Map map) { return new Comparator() { public int compare(A a, A b) { return cmp(map.get(b), map.get(a)); } }; } public static String md5OfRGBImage(RGBImage img) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(intToBytes(img.getWidth())); int[] pixels = img.getPixels(); for (int i = 0; i < l(pixels); i++) m.update(intToBytes(pixels[i])); return bytesToHex(m.digest()); } catch (Exception __e) { throw rethrow(__e); } } public static 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; } public static int cmp(Number a, Number b) { return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue()); } public static int cmp(double a, double b) { return a < b ? -1 : a == b ? 0 : 1; } public static int cmp(Object a, Object b) { if (a == null) return b == null ? 0 : -1; if (b == null) return 1; return ((Comparable) a).compareTo(b); } public static byte[] intToBytes(int i) { return new byte[] { (byte) (i >>> 24), (byte) (i >>> 16), (byte) (i >>> 8), (byte) i }; } }