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.fail; import static x30_pkg.x30_util.indexOf; import static x30_pkg.x30_util.getOpt; import static x30_pkg.x30_util.setOpt; import static x30_pkg.x30_util.callOpt; import static x30_pkg.x30_util.newWeakHashMap; import static x30_pkg.x30_util.newDangerousWeakHashMap; import static x30_pkg.x30_util.get; import static x30_pkg.x30_util.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 x30_pkg.x30_util.DynamicObject; import loadableUtils.utils; import static loadableUtils.utils._threadInfo; import static loadableUtils.utils._threadInheritInfo; import static loadableUtils.utils._threadInfo_addMakerAndRetriever; 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_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.loadPage_utf8; 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.componentPopupMenu_initForComponent; import static loadableUtils.utils.componentPopupMenu_getEvent; import static loadableUtils.utils.listPopupMenu; import static loadableUtils.utils.tablePopupMenu; import static loadableUtils.utils.rowSorter_setComparators; 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 static loadableUtils.utils.makeConceptsTable_idWidth; import static loadableUtils.utils.showConceptsTable_afterUpdate; import static loadableUtils.utils.dynamicObjectIsLoading; import loadableUtils.utils.F0; import loadableUtils.utils.F1; import loadableUtils.utils.IF1; 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.RGB; import loadableUtils.utils.BWImage; import loadableUtils.utils.MakesBufferedImage; import loadableUtils.utils.MultiSet; 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.SimpleCRUD; import loadableUtils.utils.PersistableThrowable; import loadableUtils.utils.DynModule; import loadableUtils.utils.DynPrintLog; import loadableUtils.utils.DynObjectTable; import loadableUtils.utils.DynImageSurface; import loadableUtils.utils.DynCalculatedList; import loadableUtils.utils.Rect; import loadableUtils.utils.Pt; import java.text.NumberFormat; import net.dv8tion.jda.core.events.guild.member.*; import javax.net.ssl.*; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import net.dv8tion.jda.core.*; import net.dv8tion.jda.core.entities.*; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.hooks.*; import net.dv8tion.jda.core.events.message.*; import net.dv8tion.jda.core.events.message.react.*; import java.text.*; import java.util.TimeZone; class main { public static class GreeterBot extends DynTalkBot { public String msg = "Welcome ! Rules and regulations apply. And stuff."; public String goodbyeMsg = " just left us"; public long channelToGreetIn; public void start() { super.start(); useAGIBlueForDropPunctuation = false; preprocessAtSelfToMyName = false; dropPunctuation = false; dm_vmBus_onMessage_q("discordGuildLeave", new VF1() { public void get(Map map) { try { { if (!(map.get("module") == module())) return; } Object user = rcall("getUser", map.get("event")); String name = (String) (rcall("getName", user)); postInChannel(channelToGreetIn, replace(goodbyeMsg, "", or2(name, "an unknown user"))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret unless map.get('module) == module();\r\n O user = rcall getUser(map.ge..."; } }); } public void onUserJoin(long userID, Object... __) { String msg = replace(this.msg, "", discordAt(userID)); if (channelToGreetIn == 0) setField("channelToGreetIn", preferredChannelID); if (channelToGreetIn == 0) throw fail("Have no greeting channel"); postInChannel(channelToGreetIn, msg); } public String processSimplifiedLine(String s, Object... __) { { String _a_8 = super.processSimplifiedLine(s, __); if (!empty(_a_8)) return _a_8; } Matches m = new Matches(); String sOld = s; s = dropPrefixOrNull(myPrefix(), s); if (s == null) { print("no got prefix: " + quote(myPrefix()) + " / " + quote(sOld)); return null; } if (eqic(s, "prefer this channel")) { { String _a_9 = checkAuth(__); if (!empty(_a_9)) return _a_9; } long channelID = longPar("channelID", __); if (channelID == 0) return "No channel"; setField("channelToGreetIn", channelID); return "OK, will greet here from now on."; } if (eqic(s, "simulate greeting")) { onUserJoin(longPar("userID", __), __); return "Greeting simulated"; } if (eqic(s, "get message")) return msg; if (eqic(s, "get goodbye message")) return goodbyeMsg; if (swic_trim(s, "set message:", m)) { { String _a_10 = checkAuth(__); if (!empty(_a_10)) return _a_10; } setField("msg", m.rest()); return "Message changed to: " + msg; } if (swic_trim(s, "set goodbye message:", m)) { { String _a_11 = checkAuth(__); if (!empty(_a_11)) return _a_11; } setField("goodbyeMsg", m.rest()); return "Goodbye message changed to: " + msg; } if (eqic(s, "enable")) { { String _a_12 = checkAuth(__); if (!empty(_a_12)) return _a_12; } setField("enabled", true); return "Enabled. Will greet every new arrival!"; } if (eqic(s, "disable")) { { String _a_13 = checkAuth(__); if (!empty(_a_13)) return _a_13; } setField("enabled", true); return "Disabled. Will not greet anyone."; } if (eqic(s, "dump")) return struct(objectToMap_nonTransient_singleClass(GreeterBot.class, GreeterBot.this)); if (eqic(s, "help")) return trim("\r\nI am a simple greeter (and farewell) bot. Status: " + enabledDisabled(enabled) + ". Commands:\r\n\r\n@me **simulate greeting** -- I greet you so you can test me\r\n@me **get message** -- show current greeting message\r\n@me **set message: Hello ! Bla bla...** -- change greeting. is replaced with user name\r\n@me **simulate goodbye** -- I pretend you walked away (although I know you didn't)\r\n@me **get goodbye message** -- show current goodbye message (what I post when people leave)\r\n@me **set goodbye message: just left us\r\n@me **prefer this channel** -- posts greetings in the channel you write this in\r\n@me **enable/disable** -- enable/disable the auto-greeting\r\n@me **masters**/**add master**/**delete master** -- change bot ownership\r\n@me **source**/**support channel** -- see sources or join the support discord\r\n\r\n[Bot made by https://BotCompany.de]\r\n").replace("@me", atSelf()); return null; } } public static boolean _moduleClass_GreeterBot = false; public static Object callF(Object f, Object... args) { try { if (f instanceof String) return callMC((String) f, args); return x30_util.callF(f, args); } catch (Exception __e) { throw rethrow(__e); } } public static A callF(F0 f) { return f == null ? null : f.get(); } public static A callF(IF0 f) { return f == null ? null : f.get(); } public static B callF(F1 f, A a) { return f == null ? null : f.get(a); } public static B callF(IF1 f, A a) { return f == null ? null : f.get(a); } public static C callF(F2 f, A a, B b) { return f == null ? null : f.get(a, b); } public static void callF(VF1 f, A a) { if (f != null) f.get(a); } public static Object callMC(String method, Object... args) { return call(mc(), method, args); } public static Object call(Object o) { return callF(o); } public static Object call(Object o, String method, Object... args) { return call_withVarargs(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 = false; public static Object print_byThread_lock = new Object(); public static volatile ThreadLocal print_byThread; public static volatile Object print_allThreads; public static volatile Object print_preprocess; 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 = getThreadLocal(print_byThread_dontCreate()); if (f == null) f = print_allThreads; if (f != null) if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s))) return; print_raw(s); } public static void print_raw(String s) { if (print_preprocess != null) s = (String) callF(print_preprocess, s); s = fixNewLines(s); Appendable loc = local_log; Appendable buf = print_log; int loc_max = print_log_max; if (buf != loc && buf != null) { print_append(buf, s, print_log_max); loc_max = local_log_max; } if (loc != null) print_append(loc, s, loc_max); System.out.print(s); } public static void print_autoRotate() { } public static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) { return print_byThread().get() == null ? tempInterceptPrint(f) : null; } public static AutoCloseable dm_vmBus_onMessage_q(final String msg, final VF1 onMessage) { final DynModule m = dm_current_mandatory(); return dm_vmBus_onMessage(msg, new VF1() { public void get(final A a) { try { m.q().add(new Runnable() { public void run() { try { callF(onMessage, a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, a);"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "switch to m.q();\r\n callF(onMessage, a);"; } }); } public static AutoCloseable dm_vmBus_onMessage_q(final String msg, final VF2 onMessage) { final DynModule m = dm_current_mandatory(); return dm_vmBus_onMessage(msg, new VF2() { public void get(final A a, final B b) { try { m.q().add(new Runnable() { public void run() { try { callF(onMessage, a, b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, a, b);"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "switch to m.q();\r\n callF(onMessage, a, b);"; } }); } public static AutoCloseable dm_vmBus_onMessage_q(final String msg, final Runnable onMessage) { final DynModule m = dm_current_mandatory(); return dm_vmBus_onMessage(msg, new VF1() { public void get(final A a) { try { m.q().add(new Runnable() { public void run() { try { callF(onMessage); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage);"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "switch to m.q();\r\n callF(onMessage);"; } }); } public static Object rcall(String method, Object o, Object... args) { return call_withVarargs(o, method, args); } public static String getName() { return getProgramName(); } 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 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 RuntimeException rethrow(Throwable t) { if (t instanceof Error) _handleError((Error) t); throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } public static RuntimeException rethrow(String msg, Throwable t) { throw new RuntimeException(msg, t); } public static String discordAt(long userID) { return userID == 0 ? "unknown person" : "<@" + userID + ">"; } public static boolean empty(Collection c) { return c == null || c.isEmpty(); } public static boolean empty(CharSequence s) { return s == null || s.length() == 0; } public static boolean empty(Map map) { return map == null || map.isEmpty(); } public static boolean empty(Object[] o) { return o == null || o.length == 0; } public static boolean empty(Object o) { if (o instanceof Collection) return empty((Collection) o); if (o instanceof String) return empty((String) o); if (o instanceof Map) return empty((Map) o); if (o instanceof Object[]) return empty((Object[]) o); if (o instanceof byte[]) return empty((byte[]) o); if (o == null) return true; throw fail("unknown type for 'empty': " + getType(o)); } public static boolean empty(Iterator i) { return i == null || !i.hasNext(); } public static boolean empty(float[] a) { return a == null || a.length == 0; } public static boolean empty(int[] a) { return a == null || a.length == 0; } public static boolean empty(long[] a) { return a == null || a.length == 0; } public static boolean empty(byte[] a) { return a == null || a.length == 0; } public static boolean empty(short[] a) { return a == null || a.length == 0; } public static boolean empty(MultiSet ms) { return ms == null || ms.isEmpty(); } public static boolean empty(File f) { return getFileSize(f) == 0; } public static String dropPrefixOrNull(String prefix, String s) { return s != null && s.startsWith(prefix) ? s.substring(l(prefix)) : null; } 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 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 long longPar(String name, Object[] params) { return toLong(optPar(name, params)); } public static boolean swic_trim(String a, String b, Matches m) { if (!swic(a, b)) return false; m.m = new String[] { trim(substring(a, l(b))) }; return true; } public static Map objectToMap_nonTransient_singleClass(Class c, A o) { TreeMap map = new TreeMap(); if (c != null) for (Field f : c.getDeclaredFields()) if ((f.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) == 0) { try { map.put(f.getName(), f.get(o)); } catch (Throwable __e) { _handleException(__e); } } return map; } 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 String enabledDisabled(boolean enabled) { return enabled ? "enabled" : "disabled"; } public static Class mc() { return main.class; } public static Object call_withVarargs(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findStaticMethod(method, args); if (me != null) return invokeMethod(me, null, args); List methods = cache.cache.get(method); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } { if (!(isStaticMethod(m))) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, null, newArgs); } throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found"); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(method, args); if (me != null) return invokeMethod(me, o, args); List methods = cache.cache.get(method); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, o, newArgs); } throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found in " + c); } } catch (Exception __e) { throw rethrow(__e); } } 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 = defaultDefaultClassFinder(); 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 Object getThreadLocal(Object o, String name) { ThreadLocal t = (ThreadLocal) (getOpt(o, name)); return t != null ? t.get() : null; } public static A getThreadLocal(ThreadLocal tl) { return tl == null ? null : tl.get(); } public static A getThreadLocal(ThreadLocal tl, A defaultValue) { return or(getThreadLocal(tl), defaultValue); } public static ThreadLocal print_byThread_dontCreate() { return print_byThread; } 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 StringBuffer) rotateStringBuffer(((StringBuffer) buf), max); else if (buf instanceof StringBuilder) rotateStringBuilder(((StringBuilder) buf), max); } } catch (Exception __e) { throw rethrow(__e); } } public static ThreadLocal print_byThread() { synchronized (print_byThread_lock) { if (print_byThread == null) print_byThread = new ThreadLocal(); } return print_byThread; } public static AutoCloseable tempInterceptPrint(F1 f) { return tempSetThreadLocal(print_byThread(), f); } public static AutoCloseable dm_vmBus_onMessage(final String msg, final VF1 onMessage) { return dm_ownResource(vmBus_onMessage(msg, onMessage)); } public static AutoCloseable dm_vmBus_onMessage(String msg, final VF2 onMessage) { return dm_ownResource(vmBus_onMessage(msg, onMessage)); } public static AutoCloseable dm_vmBus_onMessage(String msg, Runnable onMessage) { return dm_ownResource(vmBus_onMessage(msg, onMessage)); } public static String getProgramName_cache; public static String getProgramName() { Lock __306 = downloadLock(); lock(__306); try { if (getProgramName_cache == null) getProgramName_cache = getSnippetTitleOpt(programID()); return getProgramName_cache; } finally { unlock(__306); } } 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 boolean eq(Object a, Object b) { return a == b || (a == null ? b == null : b != null && a.equals(b)); } public static boolean nempty(Collection c) { return !empty(c); } public static boolean nempty(CharSequence s) { return !empty(s); } public static boolean nempty(Object[] o) { return !empty(o); } public static boolean nempty(byte[] o) { return !empty(o); } public static boolean nempty(int[] o) { return !empty(o); } public static boolean nempty(Map m) { return !empty(m); } public static boolean nempty(Iterator i) { return i != null && i.hasNext(); } public static boolean nempty(Object o) { return !empty(o); } public static void _handleError(Error e) { call(javax(), "_handleError", e); } public static String getType(Object o) { return getClassName(o); } 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 String str(Object o) { return o == null ? "null" : o.toString(); } public static String str(char[] c) { return new String(c); } public static String asString(Object o) { return o == null ? null : o.toString(); } 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 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 Object optPar(Object[] params, String name) { return optParam(params, name); } public static Object optPar(String name, Object[] params) { return optParam(params, name); } public static Object optPar(String name, Map params) { return optParam(name, params); } public static A optPar(Object[] params, String name, A defaultValue) { return optParam(params, name, defaultValue); } public static A optPar(String name, Object[] params, A defaultValue) { return optParam(params, name, defaultValue); } 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 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 final Map callOpt_cache = newDangerousWeakHashMap(); public static Object callOpt_cached(Object o, String methodName, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me == null || (me.getModifiers() & Modifier.STATIC) == 0) return null; return invokeMethod(me, null, args); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me == null) return null; return invokeMethod(me, o, args); } } catch (Exception __e) { throw rethrow(__e); } } public static _MethodCache callOpt_getCache(Class c) { synchronized (callOpt_cache) { _MethodCache cache = callOpt_cache.get(c); if (cache == null) callOpt_cache.put(c, cache = new _MethodCache(c)); return cache; } } public static Object invokeMethod(Method m, Object o, Object... args) { try { try { return m.invoke(o, args); } catch (InvocationTargetException e) { throw rethrow(getExceptionCause(e)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args))); } } catch (Exception __e) { throw rethrow(__e); } } public static boolean isStaticMethod(Method m) { return methodIsStatic(m); } public static Object[] massageArgsForVarArgsCall(Method m, Object[] args) { Class[] types = m.getParameterTypes(); int n = types.length - 1, nArgs = args.length; if (nArgs < n) return null; for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i])) return null; Class varArgType = types[n].getComponentType(); for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType)) return null; Object[] newArgs = new Object[n + 1]; arraycopy(args, 0, newArgs, 0, n); Object[] varArgs = arrayOfType(varArgType, nArgs - n); arraycopy(args, n, varArgs, 0, nArgs - n); newArgs[n] = varArgs; return newArgs; } public static String joinWithComma(Collection c) { return join(", ", c); } public static String joinWithComma(String... c) { return join(", ", c); } public static String joinWithComma(Pair p) { return p == null ? "" : joinWithComma(str(p.a), str(p.b)); } public static List classNames(Collection l) { return getClassNames(l); } public static List classNames(Object[] l) { return getClassNames(Arrays.asList(l)); } 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 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 Object defaultDefaultClassFinder() { return new F1() { public Class get(String name) { try { Class c = findClass_fullName(name); if (c != null) return c; if (startsWith(name, "loadableUtils.utils$")) return findClass_fullName("main" + substring(name, 19)); 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 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 = false; public static int ping_sleep = 100; public static volatile boolean ping_anyActions = false; 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 A or(A a, A b) { return a != null ? a : b; } public static void rotateStringBuffer(StringBuffer buf, int max) { try { if (buf == null) return; synchronized (buf) { if (buf.length() <= max) return; try { int newLength = max / 2; int ofs = buf.length() - newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } buf.trimToSize(); } } catch (Exception __e) { throw rethrow(__e); } } public static void rotateStringBuilder(StringBuilder buf, int max) { try { if (buf == null) return; synchronized (buf) { if (buf.length() <= max) return; try { int newLength = max / 2; int ofs = buf.length() - newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } buf.trimToSize(); } } catch (Exception __e) { throw rethrow(__e); } } 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 A dm_ownResource(A resource) { dm_currentModuleMandatory().ownResource(resource); return resource; } 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 Lock downloadLock_lock = fairLock(); public static Lock downloadLock() { return downloadLock_lock; } 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 String getSnippetTitleOpt(String s) { return isSnippetID(s) ? getSnippetTitle(s) : s; } 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 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 String getClassName(Object o) { return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName(); } public static long parseLong(String s) { if (empty(s)) return 0; return Long.parseLong(dropSuffix("L", s)); } public static long parseLong(Object s) { return Long.parseLong((String) s); } public static A optParam(ThreadLocal tl, A defaultValue) { return optPar(tl, defaultValue); } public static A optParam(ThreadLocal tl) { return optPar(tl); } public static Object optParam(String name, Map params) { return mapGet(params, name); } public static A optParam(Object[] opt, String name, A defaultValue) { int n = l(opt); if (n == 1 && opt[0] instanceof Map) { Map map = (Map) (opt[0]); return map.containsKey(name) ? (A) map.get(name) : defaultValue; } if (!even(l(opt))) throw fail("Odd parameter length"); for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name)) return (A) opt[i + 1]; return defaultValue; } public static Object optParam(Object[] opt, String name) { return optParam(opt, name, null); } public static boolean startsWithIgnoreCase(String a, String b) { return regionMatchesIC(a, 0, b, 0, b.length()); } 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); if (a != null) 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 Throwable getExceptionCause(Throwable e) { Throwable c = e.getCause(); return c != null ? c : e; } public static String joinWithSpace(Collection c) { return join(" ", c); } public static String joinWithSpace(String... c) { return join(" ", c); } public static boolean methodIsStatic(Method m) { return (m.getModifiers() & Modifier.STATIC) != 0; } public static boolean argumentCompatibleWithType(Object arg, Class type) { return arg == null ? !type.isPrimitive() : isInstanceX(type, arg); } public static void arraycopy(Object[] a, Object[] b) { if (a != null && b != null) arraycopy(a, 0, b, 0, min(a.length, b.length)); } public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) { if (n != 0) System.arraycopy(src, srcPos, dest, destPos, n); } public static A[] arrayOfType(Class type, int n) { return makeArray(type, n); } public static A[] arrayOfType(int n, Class type) { return arrayOfType(type, n); } public static String join(String glue, Iterable strings) { if (strings == null) return ""; if (strings instanceof Collection) { if (((Collection) strings).size() == 1) return str(first(((Collection) strings))); } StringBuilder buf = new StringBuilder(); Iterator i = strings.iterator(); if (i.hasNext()) { buf.append(i.next()); while (i.hasNext()) buf.append(glue).append(i.next()); } return buf.toString(); } public static String join(String glue, String... strings) { return join(glue, Arrays.asList(strings)); } public static String join(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 List getClassNames(Collection l) { List out = new ArrayList(); if (l != null) for (Object o : l) out.add(o == null ? null : getClassName(o)); return out; } public static String getStackTrace2(Throwable e) { return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n"); } 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 A setThreadLocal(ThreadLocal tl, A value) { if (tl == null) return null; A old = tl.get(); tl.set(value); return old; } public static DynModule dm_currentModuleMandatory() { return dm_current_mandatory(); } 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(Iterable l) { if (l == null) return null; Iterator it = iterator(l); if (!it.hasNext()) return null; it.next(); return it.hasNext() ? it.next() : null; } 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 char second(String s) { return charAt(s, 1); } public static A third(List l) { return _get(l, 2); } public static A third(Iterable l) { if (l == null) return null; Iterator it = iterator(l); for (int _repeat_94 = 0; _repeat_94 < 2; _repeat_94++) { if (!it.hasNext()) return null; it.next(); } return it.hasNext() ? it.next() : null; } 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 ReentrantLock fairLock() { return new ReentrantLock(true); } public static A printStackTrace(A 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 printStackTrace(String msg, Throwable e) { printStackTrace(new Throwable(msg, e)); } 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 String getSnippetTitle(String id) { try { if (id == null) return null; if (!isSnippetID(id)) return "?"; IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.getSnippetTitle(id); 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 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 dropSuffix(String suffix, String s) { return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s; } public static B mapGet(Map map, A a) { return map == null || a == null ? null : map.get(a); } public static B mapGet(A a, Map map) { return map == null || a == null ? null : map.get(a); } public static boolean even(int i) { return (i & 1) == 0; } public static boolean even(long i) { return (i & 1) == 0; } 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 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(List l) { return l; } public static Object collectionMutex(Object o) { if (o instanceof List) return 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 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 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 A[] makeArray(Class type, int n) { return (A[]) Array.newInstance(type, n); } public static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); } public static String hideCredentials(String url) { try { if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url))) return url; } catch (Throwable e) { print("HideCredentials", e); } return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2="); } public static String hideCredentials(Object o) { return hideCredentials(str(o)); } 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 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 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 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 Iterator iterator(Iterable c) { return c == null ? emptyIterator() : c.iterator(); } public static char charAt(String s, int i) { return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0'; } 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 Object _get(String field, Object o) { return get(o, field); } public static A _get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } public static IResourceLoader vm_getResourceLoader() { return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader")); } 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://code.botcompany.de:8081"; 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 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 String fsI(String id) { return formatSnippetID(id); } public static String fsI(long id) { return formatSnippetID(id); } 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 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 eqOneOf(Object o, Object... l) { for (Object x : l) if (eq(o, x)) return true; return false; } public static boolean startsWithOneOf(String s, String... l) { for (String x : l) if (startsWith(s, x)) return true; return false; } public static boolean isAGIBlueDomain(String domain) { return domainIsUnder(domain, theAGIBlueDomain()); } public static String hostNameFromURL(String url) { try { return new URL(url).getHost(); } catch (Exception __e) { throw rethrow(__e); } } 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 Set synchroHashSet() { return Collections.synchronizedSet(new HashSet()); } public static Iterator emptyIterator() { return Collections.emptyIterator(); } public static A proxy(Class intrface, final Object target) { if (target == null) return null; if (isInstance(intrface, target)) return (A) target; return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) { return call(target, method.getName(), unnull(args)); } }); } public static A proxy(Object target, Class intrface) { return proxy(intrface, target); } public static Object vm_generalMap_get(Object key) { return vm_generalMap().get(key); } 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 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 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 String htmlQuery(Map params) { return empty(params) ? "" : "?" + makePostData(params); } public static String htmlQuery(Object... data) { return empty(data) ? "" : "?" + makePostData(data); } public static Object[] muricaCredentials() { String pass = muricaPassword(); return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0]; } 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 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 Pair unnull(Pair p) { return p != null ? p : new Pair(null, null); } 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 WeakReference newWeakReference(A a) { return a == null ? null : new WeakReference(a); } public static boolean domainIsUnder(String domain, String mainDomain) { return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain); } public static String theAGIBlueDomain() { return "agi.blue"; } public static boolean isInstance(Class type, Object arg) { return type.isInstance(arg); } 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 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 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_1101 = 0; _repeat_1101 < n; _repeat_1101++) { if (it.hasNext()) l.add(it.next()); else break; } return l; } 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 ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal(); public static void checkFileNotTooBigToRead(File f) { callF(checkFileNotTooBigToRead_tl.get(), f); } 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 File newFile(String base, String... names) { return newFile(newFile(base), names); } public static String _userHome; public static String userHome() { if (_userHome == null) return actualUserHome(); return _userHome; } public static File userHome(String path) { return new File(userDir(), path); } public static String makePostData(Map map) { StringBuilder buf = new StringBuilder(); for (Map.Entry e : map.entrySet()) { String key = (String) (e.getKey()); Object val = e.getValue(); if (val != null) { String value = str(val); if (nempty(buf)) buf.append("&"); buf.append(urlencode(key)).append("=").append(urlencode((value))); } } return str(buf); } public static String makePostData(Object... params) { StringBuilder buf = new StringBuilder(); int n = l(params); for (int i = 0; i + 1 < n; i += 2) { String key = (String) (params[i]); Object val = params[i + 1]; if (val != null) { String value = str(val); if (nempty(buf)) buf.append("&"); buf.append(urlencode(key)).append("=").append(urlencode((value))); } } return str(buf); } public static volatile boolean muricaPassword_pretendNotAuthed = false; public static String muricaPassword() { if (muricaPassword_pretendNotAuthed) return null; return trim(loadTextFile(muricaPasswordFile())); } public static File getProgramDir() { return programDir(); } public static File getProgramDir(String snippetID) { return programDir(snippetID); } public static String standardCredentialsUser() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username")))); } public static String standardCredentialsPass() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass")))); } public static String urlencode(String x) { try { return URLEncoder.encode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } 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 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(Object[] l) { return emptyList(l(l)); } public static ArrayList emptyList(Class c) { return new ArrayList(); } public static Map emptyMap() { return new HashMap(); } 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 File associatedInfosFile(File f) { return replaceExtension(f, ".infos"); } public static String lines(Iterable lines) { return fromLines(lines); } public static String lines(Object[] lines) { return fromLines(asList(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 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; int n = l(l); startIndex = max(0, startIndex); endIndex = min(n, endIndex); if (startIndex >= endIndex) return ll(); if (startIndex == 0 && endIndex == n) return l; return cloneList(l.subList(startIndex, endIndex)); } public static String actualUserHome_value; public static String actualUserHome() { if (actualUserHome_value == null) { if (isAndroid()) actualUserHome_value = "/storage/emulated/0/"; else actualUserHome_value = System.getProperty("user.home"); } return actualUserHome_value; } public static File actualUserHome(String sub) { return newFile(new File(actualUserHome()), sub); } public static File userDir() { return new File(userHome()); } public static File userDir(String path) { return new File(userHome(), path); } public static File muricaPasswordFile() { return new File(javaxSecretDir(), "murica/muricaPasswordFile"); } 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 oneOfTheFiles(String... paths) { if (paths != null) for (String path : paths) if (fileExists(path)) return newFile(path); return null; } public static File oneOfTheFiles(File... files) { if (files != null) for (File f : files) if (fileExists(f)) return f; return null; } 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 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 long now_virtualTime; public static long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } 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 void vmBus_send(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); pcallFAll(vm_busListeners_live(), msg, arg); pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg); } public static void vmBus_send(String msg) { vmBus_send(msg, (Object) null); } 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 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 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(Iterable 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 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 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 volatile String caseID_caseID; public static String caseID() { return caseID_caseID; } public static void caseID(String id) { caseID_caseID = id; } 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 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 String n2(MultiSet ms, String singular, String plural) { return n_fancy2(ms, 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 String f2s(File f) { return f == null ? null : f.getAbsolutePath(); } public static String f2s(String s) { return f2s(newFile(s)); } 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 void _registerIO(Object object, String path, boolean opened) { } public static Object vmBus_wrapArgs(Object... args) { return empty(args) ? null : l(args) == 1 ? args[0] : args; } 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 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 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 static String addPrefixOptIfNempty(String prefix, String s) { return addPrefixIfNotEmpty2(prefix, s); } 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 CloseableIterableIterator linesFromFile(String path) { return linesFromFile(newFile(path)); } 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 String n_fancy2(MultiSet ms, String singular, String plural) { return n_fancy2(l(ms), 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 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 void pcallF(VF1 f, A a) { try { if (f != null) f.get(a); } catch (Throwable __e) { _handleException(__e); } } public static String addPrefixIfNotEmpty2(String prefix, String s) { return empty(s) ? "" : addPrefix(prefix, s); } 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 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 formatWithThousandsSeparator(long l) { return NumberFormat.getInstance(new Locale("en_US")).format(l); } public static Object pcallFunction(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); } return null; } public static String addPrefix(String prefix, String s) { return s.startsWith(prefix) ? s : prefix + s; } 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 = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } public void getNext() { if (done || a != null) return; a = f.get(); done = a == null; } public void close() throws Exception { if (closeable != null) closeable.close(); } } ; return new IFF2(); } 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 Object callFunction(Object f, Object... args) { return callF(f, args); } public static final class _MethodCache { public final Class c; public final HashMap> cache = new HashMap(); public _MethodCache(Class c) { this.c = c; _init(); } public void _init() { Class _c = c; while (_c != null) { for (Method m : _c.getDeclaredMethods()) if (!reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); _c = _c.getSuperclass(); } for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); } public Method findMethod(String method, Object[] args) { try { List m = cache.get(method); if (m == null) return null; int n = m.size(); for (int i = 0; i < n; i++) { Method me = m.get(i); if (call_checkArgs(me, args, false)) return me; } return null; } catch (Exception __e) { throw rethrow(__e); } } public Method findStaticMethod(String method, Object[] args) { try { List m = cache.get(method); if (m == null) return null; int n = m.size(); for (int i = 0; i < n; i++) { Method me = m.get(i); if (isStaticMethod(me) && call_checkArgs(me, args, false)) return me; } return null; } catch (Exception __e) { throw rethrow(__e); } } } public abstract static class DynTalkBot extends DynDiscordHopper { public static boolean _switchableField_myName = true; public String myName = "Anonymous bot"; public transient boolean useAGIBlueForDropPunctuation = true; public transient boolean preprocessAtSelfToMyName = true; public transient boolean dropPunctuation = true; public List authorizedUsers = ll(547706854680297473L); public void start() { super.start(); dm_vmBus_onMessage_q("discordGuildJoin", new VF1() { public void get(Map map) { try { { if (!(map.get("module") == module())) return; } print("Got join"); onUserJoin(getLong("userID", map), map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret unless map.get('module) == module();\r\n print(\"Got join\");\r\n onU..."; } }); } public void onUserJoin(long userID, Object... __) { } @Override public String answer(String input, Map map) { { String _a_7 = super.answer(input, map); if (!empty(_a_7)) return _a_7; } return mapEachLine_tlft_nempties(input, s -> { return processLine(s, map); }); } public String processLine(String s, Object... __) { s = preprocess(s, __); return processSimplifiedLine(s, __); } public String preprocess(String s, Object... __) { if (preprocessAtSelfToMyName && discordBotID != 0) s = replace(s, atSelf(), " " + myName + " "); if (dropPunctuation) s = dropPunctuation3_withAGIBlue(useAGIBlueForDropPunctuation, s); s = trim(simpleSpaces_noTok(s)); print("simplified >> " + quote(s)); return s; } public String myPrefix() { return preprocessAtSelfToMyName ? myName + " " : (dropPunctuation ? replace(atSelf(), "@", "") : atSelf()) + " "; } public String processSimplifiedLine(String input, Object... __) { Matches m = new Matches(); input = dropPrefixOrNull(myPrefix(), input); if (input == null) return null; if (eqicOneOf(input, "support channel", "support server", "support")) return "Get support for me here: " + nextGenBotsDiscordInvite(); if (eqicOneOf(input, "source", "sources", "source code")) return snippetLink(programID()); if (swic_trim(input, "add master ", m)) { { String _a_8 = checkAuth(__); if (!empty(_a_8)) return _a_8; } add(authorizedUsers, parseFirstLong(m.rest())); change(); return "Okidoki. Have " + n2(l(authorizedUsers), "master"); } if (eqic(input, "masters")) return empty(authorizedUsers) ? "I have no masters." : "My masters are: " + joinWithComma(map("discordAtPlusID", authorizedUsers)); if (swic_trim(input, "delete master ", m)) { { String _a_9 = checkAuth(__); if (!empty(_a_9)) return _a_9; } remove(authorizedUsers, parseFirstLong(m.rest())); change(); return "Okidoki. Have " + n2(l(authorizedUsers), "master"); } return null; } public boolean authed(Object... __) { return contains(authorizedUsers, optPar("userID", __)); } public String checkAuth(Object... __) { long userID = longPar("userID", __); boolean result = authed(__); print("Auth-checking user ID: " + userID + " => " + result); if (!result) return "You are not authorized"; return null; } } public abstract static class CloseableIterableIterator extends IterableIterator implements AutoCloseable { public void close() throws Exception { } } public abstract static class VF2 { public abstract void get(A a, B b); } public static interface IResourceLoader { public String loadSnippet(String snippetID); public String getTranspiled(String snippetID); public int getSnippetType(String snippetID); public String getSnippetTitle(String snippetID); public File loadLibrary(String snippetID); public File pathToJavaXJar(); public File getSnippetJar(String snippetID, String transpiledSrc); } public abstract static class IterableIterator implements Iterator, Iterable { public Iterator iterator() { return this; } public void remove() { unsupportedOperation(); } } public abstract static class DynDiscordHopper extends DynPrintLogAndEnabled { public static boolean _switchableField_discordToken = true; public String discordToken; public String discordBotName; public long discordBotID; public boolean reactToBots = true; public transient JDA discord; public transient Color discordImageEmbedMysteriousLineColor = colorFromHex("36393f"); public void startDiscord() { if (!discordEnabled()) { print("Not enabled"); return; } vm_cleanPrints(); logModuleOutput(); discord = discordBot(new ListenerAdapter() { @Override public void onMessageUpdate(MessageUpdateEvent e) { try { AutoCloseable __18 = enter(); try { { if (!discordEnabled() || !licensed()) return; } long msgID = e.getMessage().getIdLong(); String content = e.getMessage().getContentRaw(); Object lineConcept = dm_discord_lineForMsgID_unimported(msgID); String rendered = msgID + ": " + content; if (lineConcept == null) { print("Weird: Message edited, but not found: " + rendered); return; } call(lineConcept, "_setField", "editedText", content); print("Message edited: " + rendered); } finally { _close(__18); } } catch (Throwable __e) { _handleException(__e); } } @Override public void onMessageReceived(MessageReceivedEvent e) { try { AutoCloseable __19 = enter(); try { { if (!discordEnabled() || !licensed()) return; } User user = e.getAuthor(); if (!reactToUser(user)) return; boolean bot = user.isBot(); long msgID = e.getMessage().getIdLong(); long userID = user.getIdLong(); long guildID = toLong(call(e.getGuild(), "getIdLong")); Member member = e.getMember(); String userName = member == null ? null : member.getNickname(); if (userName == null && member != null) userName = member.getEffectiveName(); if (userName == null) userName = e.getAuthor().getName(); final Message msg = e.getMessage(); MessageChannel channel = e.getChannel(); long channelID = channel.getIdLong(); print("Channel type: " + e.getChannelType()); boolean isPrivate = e.getChannelType() == ChannelType.PRIVATE; String content = trim(msg.getContentRaw()); print("Msg from " + userName + ": " + content); if (empty(content)) return; vmBus_send("incomingDiscordMessage", litmapparams("fromBot", bot, "module", dm_me(), "msgID", msgID, "userID", userID, "userName", userName, "event", e, "guildID", guildID, "content", content, "isPrivate", isPrivate, "channelID", channelID, "channel", channel)); } finally { _close(__19); } } catch (Throwable __e) { _handleException(__e); } } @Override public void onMessageReactionAdd(MessageReactionAddEvent e) { try { AutoCloseable __20 = enter(); try { { if (!discordEnabled() || !licensed()) return; } MessageReaction r = e.getReaction(); if (!reactToUser(e.getUser())) return; boolean bot = e.getUser().isBot(); long msgID = r.getMessageIdLong(); String emoji = r.getReactionEmote().getName(); vmBus_send("incomingDiscordReaction", litmapparams("fromBot", bot, "module", dm_me(), "msgID", msgID, "emoji", emoji)); } finally { _close(__20); } } catch (Throwable __e) { _handleException(__e); } } @Override public void onGuildMemberJoin(GuildMemberJoinEvent event) { try { AutoCloseable __21 = enter(); try { print("Got guild join"); { if (!discordEnabled() || !licensed()) return; } print("Join >> getting user ID"); long userID = rcall_long("getIdLong", rcall("getUser", event.getMember())); print("Join >> sending"); vmBus_send("discordGuildJoin", litmapparams("module", dm_me(), "event", event, "userID", userID)); } finally { _close(__21); } } catch (Throwable __e) { _handleException(__e); } } @Override public void onGuildMemberLeave(GuildMemberLeaveEvent event) { try { AutoCloseable __22 = enter(); try { print("Got guild leave"); { if (!discordEnabled() || !licensed()) return; } long userID = rcall_long("getIdLong", rcall("getUser", event.getMember())); vmBus_send("discordGuildLeave", litmapparams("module", dm_me(), "event", event, "userID", userID)); } finally { _close(__22); } } catch (Throwable __e) { _handleException(__e); } } }, "token", discordToken); dm_registerAs("liveDiscordModule"); dm_vmBus_answerToMessage("activeDiscordTokens", new F0>() { public List get() { try { return ll(discordToken); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret ll(discordToken);"; } }); try { setField("discordBotName", jda_selfUserName(discord)); setField("discordBotID", jda_selfUserID(discord)); } catch (Throwable __e) { _handleException(__e); } print("Bot name: " + discordBotName); } public void cleanMeUp() { if (discord != null) { try { print("Shutting down discord"); discord.shutdown(); print("Bot shut down"); } catch (Throwable __e) { _handleException(__e); } } discord = null; } public Object userConcept(User user) { String crud = dm_gazelle_linesCRUD(); Object userConcept = dm_call(crud, "uniqUser", user.getIdLong()); dm_call(crud, "cset", userConcept, litobjectarray("name", user.getName())); return userConcept; } public MessageChannel getChannel(long channelID) { return discord.getTextChannelById(channelID); } public void postInChannel(long channelID, String msg) { if (channelID == 0) return; postInChannel(getChannel(channelID), msg); } public void postInChannel(MessageChannel channel, String msg) { msg = shortenForDiscord(msg); String postID = (String) (dm_call(gazelle_postedLinesCRUD(), "postingLine", channel.getId(), msg)); print("Posting in channel " + channel + ": " + msg); channel.sendMessage(msg).queue(m -> { dm_call(gazelle_postedLinesCRUD(), "donePosting", postID, "discord msg " + m.getId()); }); } public void postInChannel(String channel, String msg) { long id = dm_discord_channelID(channel); if (id == 0) throw fail("Channel not found: " + channel); postInChannel(id, msg); } public void postInChannel(MessageChannel channel, String msg, IVF1 onPost) { String postID = (String) (dm_call(gazelle_postedLinesCRUD(), "postingLine", channel.getId(), msg)); channel.sendMessage(msg).queue(msg2 -> { dm_pcall(gazelle_postedLinesCRUD(), "donePosting", postID, "discord msg " + msg2.getId()); pcallF(onPost, msg2); final long msgId = msg2.getIdLong(); print("I sent msg: " + msgId); }, error -> _handleException(error)); } public void postImage(Map msgMap, String url) { postImage(msgMap, url, ""); } public void postImage(Map msgMap, String url, String description) { postImage((MessageChannel) get("channel", msgMap), url, description); } public void postImage(MessageChannel channel, String url, String description) { channel.sendMessage(new EmbedBuilder().setImage(absoluteURL(url)).setDescription(unnull(description)).setColor(discordImageEmbedMysteriousLineColor).build()).queue(); } public void editMessage(long channelID, long msgID, String text) { getChannel(channelID).editMessageById(str(msgID), text).queue(); } public void sendPM(long userID, String text) { discord.getUserById(userID).openPrivateChannel().queue(channel -> { channel.sendMessage(shortenForDiscord(text)).queue(); }); } public void reply(Map msgMap, String text) { if (empty(text = trim(text))) return; postInChannel((MessageChannel) msgMap.get("channel"), text); } public void iAmTyping(Map msgMap) { try { ((MessageChannel) msgMap.get("channel")).sendTyping().queue(); } catch (Throwable __e) { _handleException(__e); } } public String startKeepAliveModule() { AutoCloseable __23 = enter(); try { return dm_discord_startKeepAliveModule(module()); } finally { _close(__23); } } public boolean reactToUser(User user) { boolean bot = user.isBot(); if (bot && !reactToBots) return false; if (user.getIdLong() == discordBotID) return false; return true; } public boolean discordEnabled() { return enabled; } public boolean printToModule() { return true; } public long preferredChannelID; public void enhanceFrame(Container f) { super.enhanceFrame(f); internalFramePopupMenuItem(f, "Start keep-alive module", runnableThread(new Runnable() { public void run() { try { startKeepAliveModule(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "startKeepAliveModule();"; } })); } public void start() { super.start(); startDiscord(); dm_vmBus_onMessage_q("incomingDiscordMessage", new VF1() { public void get(Map map) { try { if (!enabled) return; Object module = map.get("module"); if (!dm_isMe(module)) return; String s = getString("content", map); long channelID = toLong(map.get("channelID")); if (channelID != 0 && preferredChannelID == 0) setField("preferredChannelID", channelID); String answer = answer(s, map); if (nempty(answer)) dm_call(module, "reply", map, answer); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!enabled) ret;\r\n O module = map.get('module);\r\n if (!dm_isMe(mo..."; } }); } public String answer(String s, Map map) { if (eq(s, "!bot count")) return lstr(dm_activeDiscordTokens()); List tokens = extractPossibleDiscordTokens(s); for (String token : unnull(tokens)) { String answer = "That's a Discord token!"; if (contains(concatLists((List>) vmBus_queryAll("activeDiscordTokens")), token)) answer += " And I'm there already."; else { answer += " Jumping there!!"; dm_showNewModuleWithParams(dm_moduleLibID(), "discordToken", token); } reply(map, answer); } return null; } public String atSelf() { return discordAt(discordBotID); } public String migrateToType(String moduleLibID) { String moduleID = assertNotNull(dm_showNewModuleWithParams(moduleLibID, "discordToken", discordToken)); print("Migrated to new module " + moduleID + ", disabling me"); setEnabled(false); dm_reload(); return moduleID; } } public abstract static class DynPrintLogAndEnabled extends DynPrintLog { public volatile boolean enabled = true; public transient JPanel buttons; public JComponent visualize() { return dm_visualizeWithEnabled(super.visualize()); } public JComponent dm_visualizeWithEnabled(JComponent main) { return centerAndSouthWithMargins(main, buttons = jrightalignedline(dm_fieldCheckBox("enabled"))); } public void setEnabled(boolean b) { setField("enabled", b); } } public static String discordAtPlusID(long userID) { return userID == 0 ? "unknown person" : "<@" + userID + "> (" + userID + ")"; } public static boolean reflection_isForbiddenMethod(Method m) { return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives"); } public static void multiMapPut(Map> map, A a, B b) { List l = map.get(a); if (l == null) map.put(a, l = new ArrayList()); l.add(b); } public static Field makeAccessible(Field f) { try { f.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error", e, f); } return f; } public static Method makeAccessible(Method m) { try { m.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error", e, m); } return m; } public static Constructor makeAccessible(Constructor c) { try { c.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error", e, c); } return c; } public static Set allInterfacesImplementedBy(Class c) { if (c == null) return null; HashSet set = new HashSet(); allInterfacesImplementedBy_find(c, set); return set; } public static void allInterfacesImplementedBy_find(Class c, Set set) { if (c.isInterface() && !set.add(c)) return; do { for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set); } while ((c = c.getSuperclass()) != null); } public static Method findMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args); } 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 boolean call_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != args.length) { if (debug) print("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) { Object arg = args[i]; if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) { if (debug) print("Bad parameter " + i + ": " + arg + " vs " + types[i]); return false; } } return true; } public static Method findStaticMethod(Class c, String method, Object... args) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (!m.getName().equals(method)) continue; if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args)) continue; return m; } c = c.getSuperclass(); } return null; } public static boolean findStaticMethod_checkArgs(Method m, Object[] args) { Class[] types = m.getParameterTypes(); if (types.length != args.length) return false; for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) return false; return true; } public static long getLong(Object o, String field) { return toLong(getOpt(o, field)); } public static long getLong(String field, Object o) { return getLong(o, field); } public static String mapEachLine_tlft_nempties(Object f, String text) { return lines_possiblyRTrim(text, nempties(mapLines_tlft(f, text))); } public static String mapEachLine_tlft_nempties(String text, Object f) { return mapEachLine_tlft_nempties(f, text); } public static String mapEachLine_tlft_nempties(String text, IF1 f) { return mapEachLine_tlft_nempties(f, text); } public static String dropPunctuation3_withAGIBlue(boolean useAGIBlue, String s) { return useAGIBlue ? dropPunctuation3_withAGIBlue(s) : dropPunctuation3(s); } public static String dropPunctuation3_withAGIBlue(String s) { if (!agiBlue_validPageName(s)) return dropPunctuation3(s); String y = dropPunctuation3_cache.get(s); if (y != null) return y; { String _a_31 = agiBlue_lookupInSlice_pcall("xwxxvxozhdlwsxzj", s, "dropPunctuation"); if (!empty(_a_31)) return _a_31; } y = dropPunctuation3(s); agiBlue_postInSlice_pcall("xwxxvxozhdlwsxzj", s, "dropPunctuation", y); return y; } public static String simpleSpaces_noTok(String s) { return s == null ? null : s.replaceAll("\\s+", " "); } public static boolean eqicOneOf(String s, String... l) { for (String x : l) if (eqic(s, x)) return true; return false; } public static String nextGenBotsDiscordInvite() { return "https://discord.gg/SEAjPqk"; } public static String snippetLink(String id) { return empty(id) ? id : "http://code.botcompany.de/" + parseSnippetID(id); } 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 long parseFirstLong(String s) { return parseLong(jextract("", s)); } public static void change() { callOpt(getOptMC("mainConcepts"), "allChanged"); } 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 (A o : l) x.add(callF(f, o)); return x; } public static List map(IF1 f, Iterable l) { return map(l, f); } public static List map(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : l) x.add(f.get(o)); return x; } public static List map(IF1 f, A[] l) { return map(l, f); } public static List map(A[] l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : l) x.add(f.get(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 List map(Map map, IF2 f) { return map(map, (Object) f); } 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 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 File loadLibrary(String snippetID) { return loadBinarySnippet(snippetID); } public static UnsupportedOperationException unsupportedOperation() { throw new UnsupportedOperationException(); } public static void internalFramePopupMenuItem(Container f, final String name, final Object action) { internalFrameTitlePopupMenuItem(((JInternalFrame) f), name, action); } public static Runnable runnableThread(final Runnable r) { return new Runnable() { public void run() { try { startThread(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "startThread(r)"; } }; } public static boolean dm_isMe(Object mod) { return dm_getModule(mod) == dm_current_mandatory(); } 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 String getString(String key, Object o) { return getString(o, (Object) key); } public static Object dm_call(Object moduleOrID, String method, Object... args) { Object mod = dm_getModule(moduleOrID); if (mod == null) return null; AutoCloseable __310 = dm_enter(mod); try { return call_withVarargs(mod, method, args); } finally { _close(__310); } } public static String lstr(Map map) { return str(l(map)); } public static String lstr(Collection c) { return str(l(c)); } public static String lstr(String s) { return str(l(s)); } public static List dm_activeDiscordTokens() { return concatLists((List>) vmBus_queryAll("activeDiscordTokens")); } public static List extractPossibleDiscordTokens(String s) { return regexpAll(discordTokenRegexp(), s); } public static List concatLists(Collection... lists) { List l = new ArrayList(); if (lists != null) for (Collection list : lists) if (list != null) l.addAll(list); return l; } public static List concatLists(Collection> lists) { List l = new ArrayList(); if (lists != null) for (Collection list : lists) if (list != null) l.addAll(list); return l; } public static List vmBus_queryAll(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); List out = new ArrayList(); for (Object o : unnull(vm_busListeners_live())) addIfNotNull(out, pcallF(o, msg, arg)); for (Object o : unnull(vm_busListenersByMessage_live().get(msg))) addIfNotNull(out, pcallF(o, msg, arg)); return out; } public static String dm_showNewModuleWithParams(String moduleLibID, Object... params) { String moduleID = dm_makeNewModuleWithParams(moduleLibID, params); dm_showModule(moduleID); return moduleID; } public static String dm_moduleLibID() { return programID() + "/" + shortClassName(dm_current_mandatory()); } public static String dm_moduleLibID(Object mod) { if (mod == null) return null; mod = dm_getModule(mod); if (hasSuperclassShortNamed(mod, "DynModule")) return programID(mod) + "/" + shortClassName(mod); return null; } 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 A setEnabled(A c, boolean enable) { if (c != null) { swing(new Runnable() { public void run() { try { c.setEnabled(enable); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.setEnabled(enable);"; } }); } return c; } public static A setEnabled(boolean enable, A c) { return setEnabled(c, enable); } public static void dm_reload() { dm_reloadMe(); } public static Method findMethod_cached(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { _MethodCache cache = callOpt_getCache(((Class) o)); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false)) return m; return null; } else { _MethodCache cache = callOpt_getCache(o.getClass()); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) if (findMethod_checkArgs(m, args, false)) return m; return null; } } catch (Exception __e) { throw rethrow(__e); } } public static String lines_possiblyRTrim(String originalText, List lines) { return endsWithNewLine(originalText) ? lines(lines) : lines_rtrim(lines); } public static List nempties(Collection c) { return filterNempty(c); } public static List mapLines_tlft(Object f, String text) { return map(f, tlft(text)); } public static List mapLines_tlft(String text, F1 f) { return mapLines_tlft(f, text); } public static List mapLines_tlft(F1 f, String text) { return map(f, tlft(text)); } public static List dropPunctuation3_keep = ll("*", "<", ">"); public static Map dropPunctuation3_cache = defaultSizeMRUCache(); public static List dropPunctuation3(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)) && !dropPunctuation3_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 dropPunctuation3(String s) { return getOrCreate_f0(dropPunctuation3_cache, s, () -> join(dropPunctuation3(javaTokNoQuotes(s)))); } public static boolean agiBlue_validPageName(String s) { s = trim(s); return nempty(s) && !containsNewLine(s); } public static String agiBlue_lookupInSlice_pcall(String sliceID, String q, String... keys) { try { return agiBlue_lookupInSlice(sliceID, q, keys); } catch (Throwable __e) { return null; } } public static String agiBlue_postInSlice_pcall(String slice, String a, String b, String c) { try { return agiBlue_postInSlice(slice, a, b, c); } catch (Throwable __e) { return null; } } 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 String jextract(String pat, String s) { return jextract(pat, javaTok(s)); } public static String jextract(String pat, List tok) { List tokpat = javaTok(pat); jfind_preprocess(tokpat); int i = jfind(tok, tokpat); if (i < 0) return null; int j = i + l(tokpat) - 2; return joinSubList(tok, i, j); } public static Object getOptMC(String field) { return getOpt(mc(), field); } public static File loadBinarySnippet(String snippetID) { try { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadLibrary(snippetID); long id = parseSnippetID(snippetID); if (isImageServerSnippet(id)) return loadImageAsFile(snippetID); File f = DiskSnippetCache_getLibrary(id); if (fileSize(f) == 0) f = loadDataSnippetToFile(snippetID); return f; } catch (Exception __e) { throw rethrow(__e); } } public static void internalFrameTitlePopupMenuItem(JInternalFrame f, final String name, final Object action) { internalFrameTitlePopupMenu(f, new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, name, action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, name, action)"; } }); } public static Object dm_getModule(Object moduleOrID) { if (moduleOrID == null || eq(moduleOrID, "")) return null; if (isString(moduleOrID) && isIdentifier(((String) moduleOrID))) return dm_getService(((String) moduleOrID)); if (isStringOrIntOrLong(moduleOrID)) return dm_callOS("getDynModuleByID", str(moduleOrID)); return dm_resolveModule(moduleOrID); } public static AutoCloseable dm_enter(Object mod) { return (AutoCloseable) callOpt(dm_getModule(mod), "enter"); } 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 List regexpAll(String pattern, String text) { List matches = new ArrayList(); Matcher matcher = regexp(pattern, text); while (matcher.find()) matches.add(matcher.group()); return matches; } public static String discordTokenRegexp() { return "[MN][A-Za-z\\d]{23}\\.[\\w-]{6}\\.[\\w-]{27}"; } public static void addIfNotNull(Collection l, A a) { if (a != null && l != null) l.add(a); } public static void addIfNotNull(MultiSet ms, A a) { if (a != null && ms != null) ms.add(a); } public static String dm_makeNewModuleWithParams(String moduleLibID, Object... params) { return (String) dm_callOS("makeNewModule", moduleLibID, false, "beforeStart", new VF1() { public void get(Object mod) { try { print("Got module: " + dm_mod(mod)); dm_call(mod, "setFields", params); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "print(\"Got module: \" + dm_mod(mod));\r\n dm_call(mod, 'setFields, params);"; } }); } public static void dm_showModule(Object module) { Object stem = dm_getStem(module); if (stem != null) dm_callOS("showModule", stem); } public static void dm_showModule() { dm_showModule(dm_current_mandatory_generic()); } 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 boolean hasSuperclassShortNamed(Object o, String name) { Class c = _getClass(o); while (c != null) if (shortClassNameIs(c, name)) return true; else c = c.getSuperclass(); return false; } public static Object swing(Object f) { return swingAndWait(f); } public static A swing(F0 f) { return (A) swingAndWait(f); } public static A swing(IF0 f) { return (A) swingAndWait(f); } public static void dm_reloadMe() { dm_reloadModule(dm_currentModule()); } public static boolean endsWithNewLine(String s) { return endsWith(s, "\n"); } public static String lines_rtrim(Collection lines) { return rtrim_fromLines(lines); } public static List filterNempty(Collection c) { List l = new ArrayList(); for (String x : unnull(c)) if (nempty(x)) l.add(x); return l; } public static List tlft(String s) { return toLinesFullTrim(s); } public static List tlft(File f) { return toLinesFullTrim(f); } public static Map defaultSizeMRUCache() { return mruCache(defaultStringTransformerCacheSize()); } public static B getOrCreate_f0(Map map, A key, F0 create) { B b = map.get(key); if (b == null) mapPut(map, key, b = callF(create)); return b; } public static B getOrCreate_f0(Map map, A key, IF0 create) { B b = map.get(key); if (b == null) mapPut(map, key, b = callF(create)); return b; } public static List javaTokNoQuotes(String s) { return quotelessJavaTok(s); } public static boolean containsNewLine(String s) { return contains(s, '\n'); } public static String agiBlue_lookupInSlice(String sliceID, String q, String... keys) { return first((List) loadJSONPage(printHidingCredentials(agiBlue_linkForPhrase(q, paramsPlus(paramsWithSameKey("get", keys), "slice", sliceID))))); } public static ThreadLocal>> agiBlue_postInSlice_queue = new ThreadLocal(); public static String agiBlue_postInSlice(String slice, String a, String b, String c) { List> queue = agiBlue_postInSlice_queue.get(); if (queue != null) { queue.add(ll(slice, a, b, c)); return "Queued"; } else return loadPage(agiBlueURL() + "/bot/post" + hquery("slice", slice, "q", a, "key", b, "value", c)); } public static int javaTok_n, javaTok_elements; public static boolean javaTok_opt = false; 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)) || s.charAt(j) == '\'')); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else if (c == '[' && d == '[') { do ++j; while (j + 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 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) { return jfind(tok, startIdx, javaTokForJFind_array(in), 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, String[] tokinC, Object condition) { return findCodeTokens(tok, startIdx, false, tokinC, condition); } public static int jfind(List tok, int startIdx, List tokin, Object condition) { return findCodeTokens(tok, startIdx, false, codeTokensAsStringArray(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 joinSubList(List l, int i, int j) { return join(subList(l, i, j)); } public static String joinSubList(List l, int i) { return join(subList(l, i)); } public static File loadImageAsFile(String snippetIDOrURL) { try { if (isURL(snippetIDOrURL)) throw fail("not implemented"); if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL); String snippetID = "" + parseSnippetID(snippetIDOrURL); File file = imageSnippetCacheFile(snippetID); if (fileSize(file) > 0) return file; String imageURL = snippetImageURL_noHttps(snippetID); System.err.println("Loading image: " + imageURL); byte[] data = loadBinaryPage(imageURL); saveBinaryFile(file, data); return file; } catch (Exception __e) { throw rethrow(__e); } } 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); IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadLibrary(snippetID); File f = DiskSnippetCache_file(parseSnippetID(snippetID)); List urlsTried = new ArrayList(); List errors = new ArrayList(); try { URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID))); print("Loading library: " + hideCredentials(url)); try { loadBinaryPageToFile(openConnection(url), f); if (fileSize(f) == 0) throw fail(); } catch (Throwable e) { errors.add(e); url = addAndReturn(urlsTried, new URL("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) { 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 void internalFrameTitlePopupMenu(final JInternalFrame f, final Object... params) { { swing(new Runnable() { public void run() { try { Object menuMaker; if (l(params) == 1 && !(params[0] instanceof JMenu)) menuMaker = params[0]; else menuMaker = new VF1() { public void get(JPopupMenu menu) { try { addMenuItems(menu, params); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItems(menu, params)"; } }; Component titleComponent = getInternalFrameTitlePaneComponent(f); if (!(titleComponent instanceof JComponent)) print("Can't add internal frame title popup menu!"); else { componentPopupMenu((JComponent) titleComponent, menuMaker); setOpt(componentPopupMenu_initForComponent((JComponent) titleComponent), "internalFrameLeftButtonMagic", isTrue(vm_generalMap_get("internalFramePopupOnLeftButton"))); } componentPopupMenu(f, menuMaker); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object menuMaker;\r\n if (l(params) == 1 && !(params[0] instanceof JMenu))\r\n..."; } }); } } 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 boolean isString(Object o) { return o instanceof String; } public static boolean isIdentifier(String s) { return isJavaIdentifier(s); } public static Object dm_getService(String serviceName) { return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName))); } public static boolean isStringOrIntOrLong(Object o) { return o instanceof String || o instanceof Integer || o instanceof Long; } public static Object dm_callOS(String functionName, Object... args) { return call(dm_os(), functionName, args); } public static Object dm_resolveModule(Object moduleOrStem) { return dm_callOS("resolveModule", moduleOrStem); } public static Matcher regexp(String pat, String s) { return regexp(compileRegexp(pat), unnull(s)); } public static Matcher regexp(Pattern pat, String s) { return pat.matcher(unnull(s)); } public static Pattern regexp(String pat) { return compileRegexp(pat); } public static Object dm_mod(Object moduleOrID) { return dm_getModule(moduleOrID); } public static Object dm_getStem(Object moduleOrID) { if (isStringOrIntOrLong(moduleOrID)) return dm_getStemByID(moduleOrID); return or(getOpt(dm_getModule(moduleOrID), "_host"), moduleOrID); } 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 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 boolean shortClassNameIs(Object o, String name) { return eq(shortClassName(o), name); } 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 void dm_reloadModule(Object module) { dm_reloadModuleInBackground(module); } public static void dm_reloadModule() { dm_reloadModuleInBackground(); } public static boolean loadBufferedImage_useImageCache = true; public static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try { ping(); 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); IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return loadBufferedImage(rl.loadLibrary(snippetID)); File dir = imageSnippetsCacheDir(); if (loadBufferedImage_useImageCache) { dir.mkdirs(); File file = new File(dir, snippetID + ".png"); if (file.exists() && file.length() != 0) try { return ImageIO.read(file); } catch (Throwable e) { e.printStackTrace(); } } String imageURL = snippetImageURL_http(snippetID); print("Loading image: " + imageURL); BufferedImage image = imageIO_readURL(imageURL); if (loadBufferedImage_useImageCache) { File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis()); ImageIO.write(image, "png", tempFile); tempFile.renameTo(new File(dir, snippetID + ".png")); } return image; } 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 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 String rtrim_fromLines(Collection lines) { StringBuilder buf = new StringBuilder(); if (lines != null) { boolean first = true; for (Object line : lines) { if (first) first = false; else buf.append('\n'); buf.append(str(line)); } } return buf.toString(); } 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 Map mruCache(int maxSize) { return synchronizedMRUCache(maxSize); } public static int defaultStringTransformerCacheSize() { return 1000; } public static void mapPut(Map map, A key, B value) { if (map != null && key != null && value != null) map.put(key, value); } public static List quotelessJavaTok(String s) { ArrayList tok = 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; } 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 (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; tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } public static Object loadJSONPage(String url) { return jsonDecode(loadPage(url)); } public static A printHidingCredentials(A o) { print(hideCredentials(str(o))); return o; } public static String agiBlue_linkForPhrase(String phrase, Object... additionalParams) { return agiBlueURL() + hquery(arrayPlus(additionalParams, "q", phrase)); } public static Object[] paramsPlus(Object[] a1, Object... a2) { if (a2 == null) return a1; if (a1 == null) return a2; if (l(a1) == 1 && a1[0] instanceof Map) return new Object[] { mapPlus((Map) a1[0], a2) }; assertEvenLength(a1); assertEvenLength(a2); Map map = paramsToOrderedMap(a1); int n = l(a2); for (int i = 0; i < n; i += 2) { Object key = a2[i]; if (key != null) map.put(key, a2[i + 1]); } return mapToParams(map); } public static Object[] paramsWithSameKey(Object key, Collection values) { return paramsWithSameKey(key, asObjectArray(values)); } public static Object[] paramsWithSameKey(Object key, Object... values) { int n = l(values); Object[] o = new Object[n * 2]; for (int i = 0; i < n; i++) { o[i * 2] = key; o[i * 2 + 1] = values[i]; } return o; } public static boolean agiBlueURL_noHTTPS = false; public static String agiBlueURL_url = "https://agi.blue"; public static String agiBlueURL() { return agiBlueURL_noHTTPS ? replacePrefix("https://", "http://", agiBlueURL_url) : agiBlueURL_url; } public static String hquery(Map params) { return htmlQuery(params); } public static String hquery(Object... data) { return htmlQuery(data); } 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 Map javaTokForJFind_array_cache = synchronizedMRUCache(1000); public static String[] javaTokForJFind_array(String s) { String[] tok = javaTokForJFind_array_cache.get(s); if (tok == null) javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s)))); return tok; } 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 HashSet findCodeTokens_specials = lithashset("*", "", "", "", "\\*"); public static boolean findCodeTokens_debug = false; 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++; } int end = tok.size() - tokens.length * 2 + 2, nTokens = tokens.length; int i = startIdx | 1; String firstToken = tokens[0]; if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) { while (i < end && !firstToken.equals(tok.get(i))) i += 2; } outer: for (; i < end; i += 2) { for (int j = 0; j < nTokens; j++) { String p = tokens[j], t = tok.get(i + j * 2); boolean match = false; 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[] codeTokensAsStringArray(List tok) { int n = max(0, (l(tok) - 1) / 2); String[] out = new String[n]; for (int i = 0; i < n; i++) out[i] = tok.get(i * 2 + 1); return out; } public static ArrayList litlist(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } 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 List subList(List l, int startIndex) { return subList(l, startIndex, l(l)); } public static List subList(int startIndex, int endIndex, List l) { return subList(l, startIndex, endIndex); } public static List subList(List l, int startIndex, int endIndex) { if (l == null) return null; int n = l(l); startIndex = Math.max(0, startIndex); endIndex = Math.min(n, endIndex); if (startIndex >= endIndex) return ll(); if (startIndex == 0 && endIndex == n) return l; return l.subList(startIndex, endIndex); } public static boolean isURL(String s) { return startsWithOneOf(s, "http://", "https://", "file:"); } public static File imageSnippetCacheFile(String snippetID) { File dir = imageSnippetsCacheDir(); if (!loadBufferedImage_useImageCache) return null; return new File(dir, parseSnippetID(snippetID) + ".png"); } public static String snippetImageURL_noHttps(String snippetID) { return snippetImageURL_noHttps(snippetID, "png"); } public static String snippetImageURL_noHttps(String snippetID, String contentType) { return snippetImageURL(snippetID, contentType).replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/").replace("https://botcompany.de/", "http://botcompany.de/"); } 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 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 File getGlobalCache() { File file = new File(javaxCachesDir(), "Binary Snippets"); file.mkdirs(); return file; } 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 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(String url) { try { return openConnection(new URL(url)); } 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(Iterable 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 void addMenuItems(JMenu m, Object... x) { fillJMenu(m, x); } public static void addMenuItems(JPopupMenu m, Object... x) { fillJPopupMenu(m, x); } public static JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) { return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane"); } public static boolean jmenuItem_newThreads = false; 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(dropPrefix("[disabled] ", text)); JMenuItem mi = new JMenuItem(p.a); if (startsWith(text, "[disabled] ")) disableMenuItem(mi); if (p.b != 0) mi.setMnemonic(p.b); mi.addActionListener(jmenuItem_newThreads ? actionListenerInNewThread(r) : actionListener(r)); return mi; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Pair p = jmenu_autoMnemonic(dropPrefix(\"[disabled] \", text));\r\n JM..."; } }); } public static MenuItem menuItem(String text, final Object r) { MenuItem mi = new MenuItem(text); mi.addActionListener(actionListener(r)); return mi; } 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 Object vmBus_query(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); { Object __686 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg); if (__686 != null) return __686; } return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg); } public static Object vmBus_query(String msg) { return vmBus_query(msg, (Object) null); } public static String assertIdentifier(String s) { return assertIsIdentifier(s); } public static String assertIdentifier(String msg, String s) { return assertIsIdentifier(msg, s); } public static Object dm_os() { { Object __691 = vm_generalMap_get("stefansOS"); if (__691 != null) return __691; } return creator(); } 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 Object dm_getStemByID(Object id) { return dm_callOS("getModuleByID", str(id)); } 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 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 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 void dm_reloadModuleInBackground(Object module) { dm_callOS("reloadModuleInBackground", dm_getStem(module)); } public static void dm_reloadModuleInBackground() { dm_reloadModuleInBackground(dm_current_mandatory_generic()); } 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 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 Map synchronizedMRUCache(int maxSize) { return synchroMap(new MRUCache(maxSize)); } 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 Object[] arrayPlus(Object[] a1, Object... a2) { return concatArrays(a1, a2); } public static Map mapPlus(Map m, Object... data) { m = cloneMap(m); litmap_impl(m, data); return m; } public static Object[] assertEvenLength(Object[] a) { assertTrue(even(l(a))); return a; } public static LinkedHashMap paramsToOrderedMap(Object... params) { return asLinkedHashMap(paramsToMap(params)); } public static Object[] mapToParams(Map map) { return mapToObjectArray(map); } public static Object[] asObjectArray(Collection l) { return toObjectArray(l); } public static HashSet lithashset(A... items) { HashSet set = new HashSet(); for (A a : items) set.add(a); return set; } public static boolean isQuoted(String s) { if (isNormalQuoted(s)) return true; return isMultilineQuoted(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 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 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 String snippetImageURL(long snippetID) { return snippetImageURL(fsI(snippetID)); } 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 int loadPage_defaultTimeout = 60000; public static ThreadLocal loadPage_charset = new ThreadLocal(); public static boolean loadPage_allowGzip = true, loadPage_debug; public static boolean loadPage_anonymous = false; 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 = urlConnection_getInputStream(con); if (loadPage_debug) print("Put stream in map: " + currentThread()); String contentType = con.getContentType(); if (contentType == null) { throw new IOException("Page could not be read: " + hideCredentials(url)); } String charset = loadPage_charset == null ? null : loadPage_charset.get(); if (charset == null) charset = loadPage_guessCharset(contentType); if ("gzip".equals(con.getContentEncoding())) { if (loadPage_debug) print("loadPage: Using gzip."); in = newGZIPInputStream(in); } Reader r; try { r = new InputStreamReader(in, unquote(charset)); } catch (UnsupportedEncodingException e) { print(toHex(utf8(charset))); throw e; } boolean silent = isTrue(loadPage_silent.get()); StringBuilder buf = new StringBuilder(); int n = 0; while (true) { int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; if (!silent && (n % loadPage_verboseness) == 0) print(" " + n + " chars read"); } return buf.toString(); } finally { if (loadPage_debug) print("loadPage done"); vm_generalSubMap("URLConnection per thread").remove(currentThread()); if (in != null) in.close(); } } 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 getAndClearThreadLocal(ThreadLocal tl) { A a = tl.get(); tl.set(null); return a; } 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 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(MultiSet ms) { return ms.keySet(); } 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 void fillJMenu(final JMenu m, Object... x) { if (x == null) return; for (int i = 0; i < l(x); i++) { Object o = x[i], y = get(x, i + 1); if (o instanceof List) fillJMenu(m, asArray((List) o)); else if (isMenuSeparatorIndicator(o)) { if (menuItemCount(m) != 0) m.addSeparator(); } else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) { final LiveValue lv = (LiveValue) o; final JMenuItem mi = jmenuItem(or2(unCurlyBracket(lv.get()), "..."), y); bindLiveValueListenerToComponent(mi, lv, new Runnable() { public void run() { try { String s = lv.get(); if (isCurlyBracketed(s)) { setEnabled(mi, false); s = unCurlyBracket(s); } else setEnabled(mi, true); setText(mi, s); revalidate(m); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = lv.get();\r\n if (isCurlyBracketed(s)) {\r\n setEnable..."; } }); print("bound live value " + lv + " to menu item " + mi); m.add(mi); ++i; } else if (o instanceof String && isRunnableX(y)) { m.add(jmenuItem((String) o, y)); ++i; } else if (o instanceof JMenuItem) m.add((JMenuItem) o); else if (o instanceof String || o instanceof Action || o instanceof Component) call(m, "add", o); else if (o == null && y instanceof Runnable) ++i; else print("Unknown menu item: " + o); } } public static void fillJPopupMenu(JPopupMenu m, Object... x) { if (x == null) return; for (int i = 0; i < l(x); i++) { Object o = x[i], y = get(x, i + 1); if (o instanceof List) fillJPopupMenu(m, asArray((List) o)); else if (isMenuSeparatorIndicator(o)) m.addSeparator(); else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) { final LiveValue lv = (LiveValue) o; final JMenuItem mi = jmenuItem("", y); bindLiveValueListenerToComponent(mi, lv, new Runnable() { public void run() { try { String s = lv.get(); if (isCurlyBracketed(s)) { setEnabled(mi, false); s = unCurlyBracket(s); } else setEnabled(mi, true); setText(mi, s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = lv.get();\r\n if (isCurlyBracketed(s)) {\r\n setEnable..."; } }); m.add(mi); } else if (o instanceof String && isRunnableX(y)) { m.add(jmenuItem((String) o, y)); ++i; } else if (o instanceof JMenuItem) m.add((JMenuItem) o); else if (o instanceof String || o instanceof Action || o instanceof Component) call(m, "add", o); else if (o != null) print("Unknown menu item: " + o); } } 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 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 String dropPrefix(String prefix, String s) { return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s; } public static JMenuItem disableMenuItem(final JMenuItem mi) { if (mi != null) { swing(new Runnable() { public void run() { try { mi.setEnabled(false); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "mi.setEnabled(false);"; } }); } return mi; } 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 __1401 = holdInstance(instanceToHold); try { callF(runnable); } finally { _close(__1401); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __1401 = holdInstance(instanceToHold); try {\r\n callF(runna..."; } }); } catch (Throwable __e) { messageBox(__e); } } }; } 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 __907 = holdInstance(instanceToHold); try { callF(runnable); } finally { _close(__907); } } catch (Throwable __e) { messageBox(__e); } } }; } public static Object pcallFAll_returnFirstNotNull(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) { Object __755 = pcallF(f, args); if (__755 != null) return __755; } return null; } public static Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) { while (it.hasNext()) { Object __756 = pcallF(it.next(), args); if (__756 != null) return __756; } return null; } public static String assertIsIdentifier(String s) { if (!isIdentifier(s)) throw fail("Not an identifier: " + quote(s)); return s; } public static String assertIsIdentifier(String msg, String s) { if (!isIdentifier(s)) throw fail(msg + " - Not an identifier: " + quote(s)); return s; } public static WeakReference creator_class; public static Object creator() { return creator_class == null ? null : creator_class.get(); } public static Map syncMRUCache(int size) { return synchroMap(new MRUCache(size)); } public static Runnable asRunnable(Object o) { return toRunnable(o); } public static void _inheritThreadInfo(Object info) { _threadInheritInfo(info); } public static volatile boolean disableCertificateValidation_attempted = false; 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 Map synchroMap() { return synchroHashMap(); } public static Map synchroMap(Map map) { return Collections.synchronizedMap(map); } 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 double parseDouble(String s) { return Double.parseDouble(s); } 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 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 HashMap litmap(Object... x) { HashMap map = new HashMap(); litmap_impl(map, x); return map; } public static void litmap_impl(Map map, Object... x) { if (x != null) for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null) map.put(x[i], x[i + 1]); } 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 Map paramsToMap(Object... params) { int n = l(params); if (l(params) == 1 && params[0] instanceof Map) return (Map) params[0]; LinkedHashMap map = new LinkedHashMap(); for (int i = 0; i + 1 < n; i += 2) mapPut(map, params[i], params[i + 1]); return map; } 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[] toObjectArray(Collection c) { List l = asList(c); return l.toArray(new Object[l.size()]); } 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 boolean checkCondition(IF1 condition, A arg) { return isTrue(callF(condition, arg)); } 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 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 InputStream urlConnection_getInputStream(URLConnection con) throws IOException { UnknownHostException lastException = null; for (int _repeat_709 = 0; _repeat_709 < 2; _repeat_709++) { try { if (con instanceof HttpURLConnection) if (((HttpURLConnection) con).getResponseCode() == 500) throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con)))); return con.getInputStream(); } catch (UnknownHostException e) { lastException = e; print("Retrying because of: " + e); continue; } } throw lastException; } 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 byte[] utf8(String s) { return toUtf8(s); } public static Matcher regexpMatcher(String pat, String s) { return compileRegexp(pat).matcher(unnull(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 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 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 String getComputerID_quick() { return computerID(); } 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 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 boolean isMenuSeparatorIndicator(Object o) { return eqOneOf(o, "***", "---", "===", ""); } public static int menuItemCount(JMenu menu) { return menu == null ? 0 : swing(() -> menu.getItemCount()); } public static boolean isRunnableX(Object o) { if (o == null) return false; if (o instanceof String) return hasMethod(mc(), (String) o); return o instanceof Runnable || hasMethod(o, "get"); } public static String unCurlyBracket(String s) { return tok_unCurlyBracket(s); } public static A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) { if (lv != null) bindToComponent(component, new Runnable() { public void run() { try { lv.onChangeAndNow(listener); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindLiveValueListenerToComponent_debug\r\n print(\"bindLiveValueL..."; } }, new Runnable() { public void run() { try { lv.removeOnChangeListener(listener); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lv.removeOnChangeListener(listener)"; } }); return component; } public static boolean isCurlyBracketed(String s) { return isCurlyBraced(s); } public static boolean setText_opt = true; public static A setText(A c, Object text) { setText((JComponent) 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((JComponent) c, text); } public static JButton setText(JButton c, Object text) { setText((JComponent) 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 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(JFrame f) { revalidate((Component) f); } public static void revalidate(JInternalFrame f) { revalidate((Component) f); } 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 isLetterOrDigit(char c) { return Character.isLetterOrDigit(c); } 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 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 Map synchroHashMap() { return Collections.synchronizedMap(new HashMap()); } public static boolean possibleMD5(String s) { return isMD5(s); } 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 volatile boolean sleep_noSleep = false; 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 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 Object vm_generalMap_put(Object key, Object value) { return mapPutOrRemove(vm_generalMap(), key, value); } public static String joinNemptiesWithColonSpace(String... strings) { return joinNempties(": ", strings); } public static String joinNemptiesWithColonSpace(Collection strings) { return joinNempties(": ", strings); } public static String tryToReadErrorStreamFromURLConnection(URLConnection conn) { try { if (conn instanceof HttpURLConnection) return stream2string(((HttpURLConnection) conn).getErrorStream()); return null; } catch (Throwable __e) { return null; } } 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 int parseInt(String s) { return empty(s) ? 0 : Integer.parseInt(s); } public static int parseInt(char c) { return Integer.parseInt(str(c)); } public static String _computerID; public static Lock computerID_lock = lock(); public static String computerID() { if (_computerID == null) { Lock __979 = computerID_lock; lock(__979); 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(__979); } } return _computerID; } public static boolean hasMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args) != null; } public static String tok_unCurlyBracket(String s) { return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s; } public static boolean isCurlyBraced(String s) { List tok = tok_combineCurlyBrackets_keep(javaTok(s)); return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}"); } 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 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 boolean headless() { return isHeadless(); } public static boolean isMD5(String s) { return l(s) == 32 && isLowerHexString(s); } 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 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 String joinNempties(String sep, String... strings) { return joinStrings(sep, strings); } public static String joinNempties(String sep, Collection strings) { return joinStrings(sep, strings); } public static String stream2string(InputStream in) { return utf8streamToString(in); } public static File computerIDFile() { return javaxDataDir("Basic Info/computer-id.txt"); } 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 makeRandomID(Random r, int length) { return makeRandomID(length, r); } public static List dropFirstThreeAndLastThree(List l) { return dropFirstAndLast(3, l); } public static List tok_combineCurlyBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eq(t, "{")) { int j = findEndOfCurlyBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } public static boolean startsWithAndEndsWith(String s, String prefix, String suffix) { return startsWith(s, prefix) && endsWith(s, suffix); } public static boolean containsNewLines(String s) { return containsNewLine(s); } public static String jlabel_textAsHTML_center(String text) { return "
" + replace(htmlencode(text), "\n", "
") + "
"; } public static
A popLast(List l) { return liftLast(l); } 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 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 String joinStrings(String sep, String... strings) { return joinStrings(sep, Arrays.asList(strings)); } public static String joinStrings(String sep, Collection strings) { StringBuilder buf = new StringBuilder(); for (String s : unnull(strings)) if (nempty(s)) { if (nempty(buf)) buf.append(sep); buf.append(s); } return str(buf); } public static String utf8streamToString(InputStream in) { return readerToString(utf8bufferedReader(in)); } public static Random defaultRandomGenerator() { return ThreadLocalRandom.current(); } public static List dropFirstAndLast(int n, List l) { return new ArrayList(subList(l, n, l(l) - n)); } public static List dropFirstAndLast(List l) { return dropFirstAndLast(1, l); } public static String dropFirstAndLast(String s) { return substring(s, 1, l(s) - 1); } 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 int findEndOfCurlyBracketPart(List cnc, int i) { int j = i + 2, level = 1; while (j < cnc.size()) { if (eq(cnc.get(j), "{")) ++level; else if (eq(cnc.get(j), "}")) --level; if (level == 0) return j + 1; ++j; } return cnc.size(); } 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 == '&') { int cp = s.codePointAt(i); out.append("&#x"); out.append(intToHex_flexLength(cp)); out.append(';'); i += Character.charCount(cp) - 1; } else out.append(c); } return out.toString(); } 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 String readerToString(Reader r) { try { try { StringBuilder buf = new StringBuilder(); int n = 0; while (true) { int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; } return buf.toString(); } finally { r.close(); } } catch (Exception __e) { throw rethrow(__e); } } public static String intToHex_flexLength(int i) { return Integer.toHexString(i); } 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 Object _serialize() { return ll(maxSize, cloneLinkedHashMap(this)); } public void _deserialize(List l) { maxSize = (int) first(l); putAll((LinkedHashMap) second(l)); } } public static interface IF0 { public A get(); } public static interface IF2 { public C get(A a, B b); } public static class Var implements IVar { public Var() { } public Var(A v) { this.v = v; } public A v; public synchronized void set(A a) { if (v != a) { v = a; notifyAll(); } } public synchronized A get() { return v; } public synchronized boolean has() { return v != null; } public synchronized void clear() { v = null; } public String toString() { return str(get()); } } public static interface IVF1 { public void get(A a); } public abstract static class TokCondition { public abstract boolean get(List tok, int i); } public abstract static class LiveValue { public abstract Class getType(); public abstract A get(); public abstract void onChange(Runnable l); public abstract void removeOnChangeListener(Runnable l); public void onChangeAndNow(Runnable l) { onChange(l); callF(l); } } 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 interface IVar { public void set(A a); public A get(); public boolean has(); public void clear(); } public static java.awt.Color colorFromHex(String hex) { return awtColor(hex); } public static void vm_cleanPrints() { print_preprocess = new F1() { public String get(String x) { try { return vm_cleanForPrint(x); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "vm_cleanForPrint(x)"; } }; } public static boolean logModuleOutput_installed = false; public static void logModuleOutput() { if (logModuleOutput_installed) return; logModuleOutput_installed = true; final File logFile = getProgramFile("output.txt"); final LineBuffer buf = new LineBuffer(new VF1() { public void get(String line) { try { appendToTextFile(logFile, "[" + localDateWithMilliseconds() + "] " + line + "\n"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "appendToTextFile(logFile, \"[\" + localDateWithMilliseconds() + \"] \" + line + \"..."; } }); print_forAllThreads(new VF1() { public void get(String s) { try { buf.append(s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "buf.append(s);"; } }); } public static JDA discordBot(final VF1 onMessage) { return discordBot(new ListenerAdapter() { @Override public void onMessageReceived(MessageReceivedEvent e) { if (e.getAuthor().isBot()) { print(" Msg from bot, skipping"); return; } pcallF(onMessage, e); } }); } public static JDA discordBot(ListenerAdapter listener, Object... __) { try { JDABuilder builder = new JDABuilder(AccountType.BOT); String token = stringPar("token", __); if (empty(token)) { File tokenFile = javaxSecretDir("discord-bot-token"); token = assertNempty("Need: " + tokenFile, trim(loadTextFile(tokenFile))); } builder.setToken(token); builder.addEventListener(listener); JDA jda = builder.build(); jda.awaitReady(); print("Started Discord bot (token: " + shorten(token, 7) + ")"); return jda; } catch (Exception __e) { throw rethrow(__e); } } public static Object dm_discord_lineForMsgID_unimported(long msgID) { return dm_call(dm_gazelle_linesCRUD(), "lineForID", msgID); } public static Object[] litmapparams(Object... l) { return new Object[] { litmap(l) }; } public static DynModule dm_me() { return dm_current_mandatory(); } public static long rcall_long(String method, Object o, Object... args) { return toLong(rcall(method, o, args)); } public static AutoCloseable dm_registerAs(String... msgs) { F0 f = new F0() { public String get() { try { return dm_moduleID(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret dm_moduleID();"; } }; return combineAutoCloseables(map(msgs, msg -> dm_vmBus_answerToMessage(msg, f))); } public static AutoCloseable dm_vmBus_answerToMessage(String msg, final IF0 f) { final DynModule m = dm_current_mandatory(); return dm_ownResource(vmBus_addListener_basic(msg, new F2() { public Object get(String _msg, Object arg) { try { AutoCloseable __939 = m.enter(); try { return callF(f); } finally { _close(__939); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n ret callF(f);"; } })); } public static AutoCloseable dm_vmBus_answerToMessage(String msg, final F0 f) { final DynModule m = dm_current_mandatory(); return dm_ownResource(vmBus_addListener_basic(msg, new F2() { public Object get(String _msg, Object arg) { try { AutoCloseable __941 = m.enter(); try { return callF(f); } finally { _close(__941); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n ret callF(f);"; } })); } public static AutoCloseable dm_vmBus_answerToMessage(String msg, final F1 f) { final DynModule m = dm_current_mandatory(); return dm_ownResource(vmBus_addListener_basic(msg, new F2() { public Object get(String _msg, Object arg) { try { AutoCloseable __942 = m.enter(); try { return callF(f, arg); } finally { _close(__942); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n ret callF(f, arg);"; } })); } public static String jda_selfUserName(JDA jda) { return jda_selfUser(jda).getName(); } public static long jda_selfUserID(JDA jda) { return jda.getSelfUser().getIdLong(); } public static String dm_gazelle_linesCRUD() { return dm_require("#1021628/GLines"); } public static Object[] litobjectarray(Object... l) { return litObjectArray(l); } public static String getChannel() { return getChannelName(); } public static String shortenForDiscord(String msg) { return shorten(msg, 2000); } public static String gazelle_postedLinesCRUD() { return dm_require("#1022603/GPostedLines"); } public static long dm_discord_channelID(String name) { return (long) dm_call(dm_gazelle_linesCRUD(), "getChannelID", name); } public static Object dm_pcall(Object moduleOrID, String method, Object... args) { try { return dm_call(moduleOrID, method, args); } catch (Throwable __e) { return null; } } public static String absoluteURL(String url) { return isAbsoluteURL(url) ? url : "http://" + url; } public static String dm_discord_startKeepAliveModule(Object mod) { String discordToken = (String) (dm_get(mod, "discordToken")); return dm_showNewModuleWithParams("#1024196/DiscordKeepAlive", "discordToken", discordToken); } public static JPanel centerAndSouthWithMargins(Component c, Component s) { return applyDefaultMargin(centerAndSouth(c, withTopMargin(s))); } public static JPanel jrightalignedline(Component... components) { return jrightAlignedLine(components); } public static JPanel jrightalignedline(List components) { return jrightAlignedLine(components); } public static JCheckBox dm_fieldCheckBox(String field) { return dm_fieldCheckBox(humanizeFormLabel(field), field); } public static JCheckBox dm_fieldCheckBox(String text, String field) { if (isIdentifier(text) && !isIdentifier(field)) { String temp = field; field = text; text = temp; } return jLiveValueCheckBox(text, dm_fieldLiveValue(field)); } public static LinkedHashMap cloneLinkedHashMap(Map map) { return map == null ? new LinkedHashMap() : new LinkedHashMap(map); } public static Map putAll(Map a, Map b) { if (a != null && b != null) a.putAll(b); return a; } public static A onChange(A spinner, Object r) { { swing(new Runnable() { public void run() { try { spinner.addChangeListener(changeListener(r)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "spinner.addChangeListener(changeListener(r));"; } }); } return spinner; } public static A onChange(A b, Object r) { { swing(new Runnable() { public void run() { try { b.addItemListener(itemListener(r)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "b.addItemListener(itemListener(r));"; } }); } return b; } public static void onChange(JTextComponent tc, Object r) { onUpdate(tc, r); } public static A onChange(A slider, final Object r) { { swing(new Runnable() { public void run() { try { slider.addChangeListener(changeListener(r)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "slider.addChangeListener(changeListener(r));"; } }); } return slider; } public static JComboBox onChange(Object r, JComboBox cb) { return onChange(cb, r); } public static JComboBox onChange(JComboBox cb, final Object r) { if (isEditableComboBox(cb)) onChange(textFieldFromComboBox(cb), r); else onSelectedItem(cb, new VF1() { public void get(String s) { try { callF(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(r)"; } }); return cb; } public static int hashCodeFor(Object a) { return a == null ? 0 : a.hashCode(); } public static java.awt.Color awtColor(String hex) { byte[] b = bytesFromHex(dropPrefix("#", hex)); return new Color(ubyteToInt(b[0]), ubyteToInt(b[1]), ubyteToInt(b[2])); } public static String vm_cleanForPrint(Object o) { String s = str(o); return or((String) vmBus_query("cleanForPrint", s), s); } public static void appendToTextFile(File file, String s) { appendToFile(file, s); } public static void appendToTextFile(String file, String s) { appendToTextFile(programFile(file), s); } public static String localDateWithMilliseconds(Date time) { return localDateWithMilliseconds(time.getTime()); } public static String localDateWithMilliseconds(long time) { SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss''SSSS"); return format.format(time); } public static String localDateWithMilliseconds() { return localDateWithMilliseconds(now()); } public static void print_forAllThreads(Object f) { assertNull("todo", print_allThreads); print_allThreads = f; } public static String stringPar(Object[] params, String name) { return stringOptPar(params, name); } public static String stringPar(String name, Object[] params) { return stringOptPar(params, name); } public static String stringPar(String name, Map params) { return (String) optPar(name, params); } public static String stringPar(String name, Object[] params, String defaultValue) { return optPar(name, params, defaultValue); } public static A assertNempty(A a) { return assertNempty("empty", a); } public static A assertNempty(String msg, A a) { if (empty(a)) throw fail(msg + ": " + a); return a; } 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 String dm_moduleID(Object module) { return strOrNull(getOpt(dm_getStem(module), "id")); } public static String dm_moduleID() { return dm_moduleID(dm_current_mandatory_generic()); } public static AutoCloseable combineAutoCloseables(final AutoCloseable a, final AutoCloseable b) { return a == null ? b : b == null ? a : new AutoCloseable() { public String toString() { return "a.close(); b.close();"; } public void close() throws Exception { a.close(); b.close(); } }; } public static AutoCloseable combineAutoCloseables(AutoCloseable a, AutoCloseable b, AutoCloseable c, AutoCloseable... more) { return combineAutoCloseables(concatLists(ll(a, b, c), asList(more))); } public static AutoCloseable combineAutoCloseables(Iterable l) { return foldl(new F2() { public AutoCloseable get(AutoCloseable a, AutoCloseable b) { try { return combineAutoCloseables(a, b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "combineAutoCloseables(a,b)"; } }, null, l); } public static AutoCloseable vmBus_addListener_basic(String msg, Object listener) { Map map = vm_busListenersByMessage_live(); synchronized (map) { Set listeners = map.get(msg); if (listeners == null) map.put(msg, listeners = syncIdentityHashSet()); return tempAdd(listeners, listener); } } public static SelfUser jda_selfUser(JDA jda) { return jda.getSelfUser(); } public static String dm_require(String moduleLibID) { return dm_makeModule(moduleLibID); } public static Object[] litObjectArray(Object... l) { return l; } public static String getChannelName() { return (String) callOpt(getMainBot(), "getChannelName"); } public static boolean isAbsoluteURL(String s) { return contains(s, "://"); } public static Object dm_get(Object moduleOrID, String field) { return get(dm_getModule(moduleOrID), field); } public static Object dm_get(String field, long moduleID) { return dm_get(moduleID, field); } public static A applyDefaultMargin(final A c) { if (c != null) { swing(new Runnable() { public void run() { try { c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMarg..."; } }); } return c; } 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 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 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 JCheckBox jLiveValueCheckBox(String text, final SimpleLiveValue lv) { final JCheckBox cb = jCheckBox(text); bindCheckBoxToLiveValue(cb, lv); return cb; } public static SimpleLiveValue dm_fieldLiveValue(String fieldName) { return dm_fieldLiveValue(dm_current_mandatory(), fieldName); } public static SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) { Lock __1024 = module.lock; lock(__1024); try { Class type = getFieldType(module, fieldName); final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName)); module.onChange(new Runnable() { public void run() { try { Object o = get(module, fieldName); value.set(o); ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting \" + fi..."; } }); value.onChange(new Runnable() { public void run() { try { module.setField(fieldName, value.get()); ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting 2 \" + ..."; } }); return value; } finally { unlock(__1024); } } public static ChangeListener changeListener(final Object r) { return new ChangeListener() { public void stateChanged(ChangeEvent e) { pcallF(r); } }; } public static ItemListener itemListener(final Object r) { return new ItemListener() { public void itemStateChanged(ItemEvent e) { pcallF(r); } }; } 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 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 JTextField textFieldFromComboBox(JComboBox cb) { return (JTextField) cb.getEditor().getEditorComponent(); } public static JComboBox onSelectedItem(final JComboBox cb, final VF1 f) { addActionListener(cb, new Runnable() { public void run() { try { pcallF(f, selectedItem(cb)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(f, selectedItem(cb))"; } }); return cb; } 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 byte[] bytesFromHex(String s) { return hexToBytes(s); } public static int ubyteToInt(byte b) { return b & 0x0FF; } public static Lock appendToFile_lock = lock(); public static boolean appendToFile_keepOpen = false; public static HashMap appendToFile_writers = new HashMap(); public static void appendToFile(String path, String s) { try { Lock __996 = appendToFile_lock; lock(__996); try { mkdirsForFile(new File(path)); path = getCanonicalPath(path); Writer writer = appendToFile_writers.get(path); if (writer == null) { writer = new BufferedWriter(new OutputStreamWriter(newFileOutputStream(path, true), "UTF-8")); if (appendToFile_keepOpen) appendToFile_writers.put(path, writer); } writer.write(s); if (!appendToFile_keepOpen) writer.close(); } finally { unlock(__996); } } catch (Exception __e) { throw rethrow(__e); } } public static void appendToFile(File path, String s) { if (path != null) appendToFile(path.getPath(), s); } public static void cleanMeUp_appendToFile() { AutoCloseable __998 = tempCleaningUp(); try { Lock __997 = appendToFile_lock; lock(__997); try { closeAllWriters(values(appendToFile_writers)); appendToFile_writers.clear(); } finally { unlock(__997); } } finally { _close(__998); } } public static File programFile(String name) { return prepareProgramFile(name); } public static File programFile(String progID, String name) { return prepareProgramFile(progID, name); } public static SimpleDateFormat simpleDateFormat_local(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(localTimeZone()); return sdf; } public static A assertNull(A a) { assertTrue(a == null); return a; } public static A assertNull(String msg, A a) { assertTrue(msg, a == null); return a; } public static String stringOptPar(Object[] params, String name) { return (String) optPar(params, name); } public static String strOrNull(Object o) { return o == null ? null : str(o); } public static A foldl(F2 f, A seed, Iterable l) { A a = seed; if (l != null) for (B b : l) a = callF(f, a, b); return a; } public static A foldl(F2 f, A seed, B[] l) { A a = seed; if (l != null) for (B b : l) a = callF(f, a, b); return a; } public static A foldl(Object f, A seed, B[] l) { A a = seed; if (l != null) for (B b : l) a = (A) callF(f, a, b); return a; } public static String dm_makeModule(String moduleLibID) { return (String) dm_callOS("makeModule", moduleLibID); } public static Object mainBot; public static Object getMainBot() { return mainBot; } public static JComponent wrap(Object swingable) { return _recordNewSwingComponent(wrap_2(swingable)); } public static JComponent wrap_2(Object swingable) { if (swingable == null) return null; JComponent c; if (swingable instanceof Component) c = componentToJComponent(((Component) swingable)); else c = componentToJComponent((Component) callOpt(swingable, "swing")); if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree) return jscroll(c); return c == null ? jlabel(str(swingable)) : c; } public static boolean containsSpace(String s) { return containsSpaces(s); } public static String firstToUpper(String s) { if (empty(s)) return s; return Character.toUpperCase(s.charAt(0)) + s.substring(1); } 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 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 A bindCheckBoxToLiveValue(final A cb, final SimpleLiveValue lv) { bindLiveValueListenerToComponent(cb, lv, new Runnable() { public void run() { try { setChecked(cb, isTrue(lv.get())); ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se..."; } }); onChange(cb, new Runnable() { public void run() { try { lv.set(isChecked(cb)); ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se..."; } }); return cb; } public static Class getFieldType(Object o, String field) { return fieldType(o, field); } 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 String selectedItem(JList l) { return getSelectedItem(l); } public static String selectedItem(JComboBox cb) { return getSelectedItem(cb); } 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 String getCanonicalPath(File f) { try { return f == null ? null : f.getCanonicalPath(); } catch (Exception __e) { throw rethrow(__e); } } public static String getCanonicalPath(String path) { return getCanonicalPath(newFile(path)); } public static AutoCloseable tempCleaningUp() { return tempSetTL(ping_isCleanUpThread, true); } public static void closeAllWriters(Collection l) { for (Writer w : unnull(l)) { try { w.close(); } catch (Throwable __e) { _handleException(__e); } } } public static Collection values(Map map) { return map == null ? emptyList() : map.values(); } public static File prepareProgramFile(String name) { return mkdirsForFile(getProgramFile(name)); } public static File prepareProgramFile(String progID, String name) { return mkdirsForFile(getProgramFile(progID, name)); } public static TimeZone localTimeZone() { return getTimeZone(standardTimeZone()); } public static A _recordNewSwingComponent(A c) { if (c != null) callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c); return c; } 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 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 JLabel jlabel(final String text) { return swingConstruct(BetterLabel.class, text); } public static JLabel jlabel() { return jlabel(" "); } public static boolean containsSpaces(String s) { return indexOf(s, ' ') >= 0; } public static A getOrKeep(Map map, A a) { if (map == null) return 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(); if (isAllUpperCase(s)) { l.add(s); return l; } 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 A swingNu(final Class c, final Object... args) { return swingConstruct(c, args); } public static void setChecked(final JCheckBox checkBox, final boolean b) { if (checkBox != null) { swing(new Runnable() { public void run() { try { if (isChecked(checkBox) != b) checkBox.setSelected(b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (isChecked(checkBox) != b)\r\n checkBox.setSelected(b);"; } }); } } 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 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 String getSelectedItem(JList l) { return (String) l.getSelectedValue(); } public static String getSelectedItem(JComboBox cb) { return strOrNull(cb.getSelectedItem()); } 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 AutoCloseable tempSetTL(ThreadLocal tl, A a) { return tempSetThreadLocal(tl, a); } public static TimeZone getTimeZone(String name) { return TimeZone.getTimeZone(name); } public static String standardTimeZone_name = "Europe/Berlin"; public static String standardTimeZone() { return standardTimeZone_name; } 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 boolean isAllUpperCase(String s) { return hasLettersAllUpperCase(s); } public static boolean isUpperCaseLetter(char c) { return Character.isUpperCase(c); } 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 AbstractAction abstractAction(String name, final Object runnable) { return new AbstractAction(name) { public void actionPerformed(ActionEvent evt) { pcallF(runnable); } }; } 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 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); makeAccessible(m); 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 boolean hasLettersAllUpperCase(String s) { return hasLetters(s) && !containsLowerCase(s); } public static char stringToChar(String s) { if (l(s) != 1) throw fail("bad stringToChar: " + s); return firstChar(s); } public static Map classForName_cache = synchroHashMap(); public static Class classForName(String name) { try { if (classForName_cache == null) return Class.forName(name); 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())) { makeAccessible(m); 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 hasLetters(String s) { for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i))) return true; return false; } public static boolean containsLowerCase(String s) { for (int i = 0; i < l(s); i++) if (isLowerCase(s.charAt(i))) return true; return false; } public static char firstChar(String s) { return s.charAt(0); } public static boolean isLowerCase(char c) { return Character.isLowerCase(c); } public static class SimpleLiveValue extends LiveValue { public Class type; public volatile A value; public transient List onChange = synchroList(); public SimpleLiveValue(Class type) { this.type = type; } public SimpleLiveValue(Class type, A value) { this.value = value; this.type = type; } public Class getType() { return type; } public A get() { return value; } public void onChange(Runnable l) { onChange.add(l); } public void onChangeAndNow(Runnable l) { onChange(l); callF(l); } public void removeOnChangeListener(Runnable l) { onChange.remove(l); } public void fireChanged() { pcallFAll(onChange); } public void set(A a) { if (neq(value, a)) { value = a; fireChanged(); } } } public static class LineBuffer { public VF1 onLine; public StringBuilder currentLine = new StringBuilder(); public LineBuffer() { } public LineBuffer(VF1 onLine) { this.onLine = onLine; } public void append(String s) { append(s, onLine); } public void append(String s, VF1 onLine) { currentLine.append(s); if (contains(s, '\n')) { int i = 0, j; s = str(currentLine); while ((j = indexOf(s, i, '\n')) >= 0) { String line = dropTrailingBackslashR(substring(s, i, j)); callF(onLine, line); i = j + 1; } currentLine = new StringBuilder(substring(s, i)); } } public int size() { return l(currentLine); } } 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 = false; public void setLeftBorder(int border) { insetLeft = border; } public void setRightBorder(int border) { insetRight = border; } public static JComponent withBorder(JComponent component, int border) { JPanel panel = new JPanel(new LetterLayout("C").setBorder(border)); panel.add("C", component); return panel; } public static JPanel panel(String... lines) { return new JPanel(new LetterLayout(lines)); } public static JPanel stalactitePanel() { return new JPanel(stalactite()); } public static class DummyComponent extends JComponent { } public static class Cell { public boolean aux = false; 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 String dropTrailingBackslashR(String s) { int i = l(s); while (i > 0 && s.charAt(i - 1) == '\r') --i; return substring(s, 0, i); } }