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 org.jsoup.*; import org.jsoup.nodes.*; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.text.*; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; import net.dv8tion.jda.core.events.Event; import net.dv8tion.jda.core.events.user.update.*; import net.dv8tion.jda.core.events.guild.member.*; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.requests.restaction.MessageAction; import net.dv8tion.jda.core.requests.RestAction; import java.util.function.Consumer; import javax.swing.border.*; import java.awt.datatransfer.StringSelection; import javax.swing.event.AncestorListener; import javax.swing.event.AncestorEvent; import javax.swing.Timer; import javax.swing.undo.UndoManager; import javax.imageio.metadata.*; import javax.imageio.stream.*; import java.awt.geom.*; 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.*; class main { static class NLRulesBot extends DynTalkBot2 { void init() { super.init(); makeByServer = () -> new ByServer(); useAGIBlueForDropPunctuation = false; preprocessAtSelfToMyName = false; dropPunctuation = false; print("Total rules in all guilds: " + totalRuleCount()); } static class Rule { GlobalID globalID = aGlobalIDObj(); String text, comment; Rule() {} Rule(String text) { this.text = text;} } String renderRule(Rule r) { return r == null ? null : appendNewLineIfNempty(r.comment) + "Rule " + r.globalID + ": " + r.text; } class ByServer extends DynTalkBot2.ByServer { List rules = new ArrayList(); Set priorityChannels = new HashSet(); // where we always respond boolean enableMagicQuotes = true; Map topicByChannel = new HashMap(); SimpleFactStore factStore = new SimpleFactStore(); StringClustersWithIDs synonyms = new StringClustersWithIDs(); void _doneLoading() { synonyms.onChange(new Runnable() { public void run() { try { change(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "change();"; }}); } String processSimplifiedLine(String s, Object... __) { String __2 = super.processSimplifiedLine(s, __); if (!empty(__2)) return __2; return fullTrim(processSimplifiedLine2(s, __)); } String processSimplifiedLine2(String s, Object... __) { Lock __0 = myLock(); lock(__0); try { String __3 = factStore_cmds(factStore, s, authed(__)); if (!empty(__3)) return __3; { String __4 = philosophyBotWithFactStore_discordAnswer( ai_weightChangeBot_theory(), factStore, s, __); if (!empty(__4)) return __4; } long channelID = longPar("channelID",__); Matches m = new Matches(); String s2 = dropMyPrefixOrNull(s); if (s2 != null) s = s2; else if (!contains(priorityChannels, channelID)) return null; Message msg = (Message) (optPar("msg",__)); Message.Attachment attachment = msg == null ? null : first(msg.getAttachments()); if (attachment != null) { File file = prepareCacheProgramFile(guildID + "/" + attachment.getFileName()); print("Downloading attachment: " + file); deleteFile(file); if (!attachment.download(file)) return "Couldn't download attachment"; List lines = tlft(loadTextFile(file)); print("First line: " + first(lines)); if (!swic(first(lines), "rule ")) print("File does not contain rules"); else { List> toImport = new ArrayList(); // (globalID, text, comment) List comment = new ArrayList(); for (String line : lines) { List l = regexpICFullMatch_groups("Rule ([a-z]+):(.*)$", line); if (nempty(l)) { toImport.add(t3(first(l), second(l), lines_rtrim(comment))); comment.clear(); } else comment.add(line); } String found = "Found " + nRules(toImport) + " in attachment"; int oldCount = l(rules); Map existing = indexByField("globalID",rules); int updated = 0, added = 0; for (T3 rule : toImport) { GlobalID id = new GlobalID(rule.a); String text = trim(rule.b); Rule r = existing.get(id); if (r == null) { r = new Rule(text); r.globalID = id; r.comment = rule.c; rules.add(r); existing.put(id, r); ++added; } else if (neq(r.text, text)) { r.comment = rule.c; r.text = text; ++updated; } } if (added+updated > 0) change(); return found + ". Had: " + oldCount + ". Added: " + added + ". Updated: " + updated + ". New count: " + l(rules); } } // duplicated patterns go here if (match("on * say *", s, m) || match("on * or * say *", s, m) || match("on keyword * and * say *", s, m) || match("on keyword * and keyword * say *", s, m) || match("on keyword * or * say *", s, m) || match("on keyword * say *", s, m) || match("on *, image-google X", s, m) || match("on *, google X", s, m) || match("when <*> comes online, say *", s, m) || match("on bot keyword * and keyword *, say *", s, m) || match("on conversation keyword * and *, say *", s, m) || match("on topic * and *, say *", s, m) || match("on topic * and keyword *, say *", s, m)) { Rule r = firstWhereIC(rules, "text" , s); if (r != null) return "Rule exists: " + r.globalID; rules.add(r = new Rule(s)); change(); return "Rule added with ID " + r.globalID; } if (match("rules", s) || match("rules as file", s)) { if (empty(rules)) return "No rules defined yet"; uploadFileInChannel(channelID, toUtf8(lines(map(r -> renderRule(r), rules))), genericTextFileName(), null, null); return null; } if (match("delete rule *", s, m) || match("delete rule with id *", s, m)) { String __5 = checkAuth(__); if (!empty(__5)) return __5; Rule r = firstWhere(rules, "globalID" , new GlobalID(m.unq(0))); if (r == null) return "Rule " + m.unq(0) + " not found"; rules.remove(r); change(); return "Rule deleted, " + nRule(rules) + " remain"; } if (match("delete all rules", s)) { appendToTextFile(programFile("backups.txt"), guildStructure()); { String __6 = checkAuth(__); if (!empty(__6)) return __6; } rules.clear(); change(); return "All rules deleted"; } if (match("priority channel on", s)) { String __7 = checkAuth(__); if (!empty(__7)) return __7; priorityChannels.add(channelID); change(); return "OK"; } if (match("priority channel off", s)) { String __8 = checkAuth(__); if (!empty(__8)) return __8; priorityChannels.remove(channelID); change(); return "OK"; } if (match("disable magic quotes", s)) { String __9 = checkAuth(__); if (!empty(__9)) return __9; enableMagicQuotes = false; change(); return "OK"; } if (matchX("add synonym ...", s, m) || matchX("add synonyms ...", s, m)) { List tok = unquoteAll(wordTokC(m.rest())); printStruct("tok", tok); if (l(tok) <= 1) return "Give me at least 2 synonyms, dude"; for (int i = 1; i < l(tok); i++) synonyms.addPair(first(tok), tok.get(i)); return "OK: " + synonyms.clusterWith(first(tok)).synonyms; } if (match("delete synonym cluster *", s, m)) { StringClustersWithIDs.Cluster c = synonyms.clusterWith(m.unq(0)); if (c == null) return "Cluster not found"; synonyms.remove(c); return "Synonym cluster deleted: " + c.synonyms; } if (match("delete synonym * from cluster *", s, m)) { StringClustersWithIDs.Cluster c = synonyms.clusterWith(m.unq(0)); if (c == null) return "Cluster not found"; if (!c.synonyms.remove(m.unq(0))) return format("Synonym * not found in " + c.synonyms); change(); if (l(c.synonyms) <= 1) synonyms.remove(c); return "OK"; } if (match("list synonyms", s)) return or2(lines(map(synonyms.clusters, c -> join(" = ", c.synonyms))), "No synonyms defined"); if (match("list synonyms for *", s, m)) { Collection l = synonyms.searchForCluster(m.unq(0)); return or2(lines(map(l, c -> join(" = ", c.synonyms))), format("No synonyms found for *", m.unq(0))); } if (match("print log", s)) { String __10 = checkAuth(__); if (!empty(__10)) return __10; return str(_actualPrintLog()); } if (match("lottery print log", s)) { String __11 = checkAuth(__); if (!empty(__11)) return __11; String mod = dm_findModule("#1025913/LotteryBot"); if (mod == null) return "Not loaded"; return mod + "\n" + str(dm_call(mod, "_actualPrintLog")); } if (match("lottery enabled", s)) { String __12 = checkAuth(__); if (!empty(__12)) return __12; return str(dm_get(dm_findModule("#1025913/LotteryBot"), "enabled")); } if (match("lottery last error", s)) { String __13 = checkAuth(__); if (!empty(__13)) return __13; return str(dm_get(dm_findModule("#1025913/LotteryBot"), "_error")); } if (match("lottery reload", s)) { String __14 = checkAuth(__); if (!empty(__14)) return __14; dm_reloadModule(dm_findModule("#1025913/LotteryBot")); return "OK (maybe)"; } if (eqic(s, "help")) return ltrim("\r\nI execute simple English rules.\r\n\r\nStuff to say.\r\n@me `on \"hello bot\" say \"who are you\"`\r\n@me `on keyword \"time\" say \"it is always time for a tea\"`\r\n@me `on \"what is X\" google X`\r\n@me `on \"show me X\" image-google X`\r\n@me `on bot keyword \"game\" and keyword \"sure\" say \"let's play tic tac toe\"`\r\n@me `on topic \"weather\" and \"nice\", say \"so the sun is shining?\"`\r\n@me `when @user comes online, say \"hello friend\"`\r\n@me `rules` / `rules as file` - list rules\r\n@me `delete rule abcdefghijkl` - delete rule with ID\r\n\r\n@me `add synonyms thx \"thank you\" thanks` - add synonyms\r\n@me `delete synonym cluster thx` - delete all synonyms of thx\r\n@me `delete synonym thx from cluster thanks` - delete a single synonym\r\n@me `list synonyms` / `list synonyms for \"thank you\"`\r\n\r\n@me `topic` - show current topic for channel (see: conversation keyword)\r\n@me `forget the topic` / `forget ` - forget current topic\r\n\r\n@me `priority channel on` - respond to every msg\r\n@me `priority channel off` - respond to msgs with my name only\r\n@me `masters` / `add master ` / `delete master `\r\n@me `help` / `support` / `source code`\r\n@me `download` - download my brain for this guild\r\n\r\nTo fill me with rules, just upload the file you got from `rules as file` to the channel.\r\n\r\n[Bot made by https://BotCompany.de]\r\n ").replace("@me", atSelf()); // find rule to execute LinkedHashSet outs = new LinkedHashSet(); LinkedHashSet outs2 = new LinkedHashSet(); // higher priority (two matches) for (Rule r : rules) { try { // IMPORTANT: patterns are duplicated above if (matchX2("on conversation keyword * and *, say *|on topic * and *, say *|on topic * and keyword *, say *", r.text, m)) { String in1 = m.unq(0), in2 = m.unq(1), out = m.unq(2); if (findWithSynonyms(in1, s)) if (put_trueIfChanged(topicByChannel, channelID, in1)) change(); if (synonyms.eqicOrInSameCluster(topicByChannel.get(channelID), in1) && findWithSynonyms(in2, s)) outs2.add(rewrite(out, __)); } if (match("on * say *", r.text, m)) { String in = m.unq(0), out = m.unq(1); if (matchWithSynonyms(in, s)) outs.add(rewrite(out, __)); } if (match("on * or * say *", r.text, m)) { String in1 = m.unq(0), in2 = m.unq(1), out = m.unq(2); if (matchWithSynonyms(in1, s) || matchWithSynonyms(in2, s)) outs.add(rewrite(out, __)); } if (match_vbar("on keyword * and * say *|on keyword * and keyword * say *", r.text, m)) { String in1 = m.unq(0), in2 = m.unq(1), out = m.unq(2); if (findWithSynonyms(in1, s) && findWithSynonyms(in2, s)) outs2.add(rewrite(out, __)); } if (match("on keyword * or * say *", r.text, m)) { String in1 = m.unq(0), in2 = m.unq(1), out = m.unq(2); if (findWithSynonyms(in1, s) || findWithSynonyms(in2, s)) outs2.add(rewrite(out, __)); } if (match("on bot keyword * and keyword *, say *", r.text, m)) { ISaid lastSaid = lastSaidInChannel.get(channelID); if (lastSaid != null) { String in1 = m.unq(0), in2 = m.unq(1), out = m.unq(2); if (findWithSynonyms(in1, lastSaid.text) && findWithSynonyms(in2, s)) outs2.add(rewrite(out, __)); } } if (match("on keyword * say *", r.text, m)) { String in = m.unq(0), out = m.unq(1); if (findWithSynonyms(in, s)) outs.add(rewrite(out, __)); } if (match("on *, image-google X", r.text, m)) if (flexMatchIC(replaceWord(m.unq(0), "X", "*"), s, m)) { boolean nsfw = discord_isNSFWChannel_gen(optPar("channel",__)); print("nsfw", nsfw); BufferedImage img = nsfw ? quickVisualize_nsfw(m.unq(0)) : quickVisualize(m.unq(0)); if (img == null) return "No image found, sorry!"; postImage(paramsToMap(__), uploadToImageServer(img, m.unq(0))); // null; } if (match("on *, google X", r.text, m)) if (flexMatchIC(replaceWord(m.unq(0), "X", "*"), s, m)) { boolean nsfw = discord_isNSFWChannel_gen(optPar("channel",__)); print("nsfw", nsfw); return discord_google(m.unq(0), "results" , 1, "safeSearch" , !nsfw); } } catch (Throwable __e) { _handleException(__e); }} if (match("topic", s) || match("conversation keyword", s)) { String topic = topicByChannel.get(channelID); return nempty(topic) ? "Current topic in this channel is: " + topic : "No topic set in this channel"; } if (match("forget topic", s) || match("forget the topic", s)) return forgetTopic(channelID); if (matchStartX("forget ...", s, m)) if (synonyms.eqicOrInSameCluster(m.unq(0), topicByChannel.get(channelID))) return forgetTopic(channelID); if (match("download", s)) { Guild guild = (Guild) (optPar("guild",__)); MessageChannel channel = (MessageChannel) (optPar("channel",__)); return serveGuildBackup(channel, guild, structure_nullingInstancesOfClass(_getClass(module()), ByServer.this)); } if (match("stats", s)) return "I have " + nRules(rules) + " and know " + n2(synonyms.totalCount(), "synonym"); if (match("masters", s)) return renderMasters(); { String __15 = random(outs2); if (!empty(__15)) return __15; } { String __16 = random(outs); if (!empty(__16)) return __16; } if (enableMagicQuotes) { String __17 = answer_magicQuoteInput(s, "useTranspiled" , true); if (!empty(__17)) return __17; } return null; } finally { unlock(__0); } } String rewrite(String answer, Object... __) { if (containsIC(answer, "")) { String name = (String) (optPar("name",__)); if (empty(name)) name = discord_optParUserName(__); if (nempty(name)) answer = replaceIC(answer, "", name); } return answer; } void onOnlineStatusChange(UserUpdateOnlineStatusEvent e) { User user = e.getMember().getUser(); print("User status change: " + user + " " + e.getOldValue() + " -> " + e.getNewValue()); // only react to user coming online if (e.getOldValue() != OnlineStatus.OFFLINE) return; long id = user.getIdLong(); LinkedHashSet outs = new LinkedHashSet(); Matches m = new Matches(); for (Rule r : rules) { try { // IMPORTANT: patterns are duplicated above if (match("when <*> comes online, say *", r.text, m)) { long _id = parseLongOpt(m.unq(0)); String out = m.unq(1); if (id == _id) outs.add(rewrite(out, "name" , user.getName())); } } catch (Throwable __e) { _handleException(__e); }} postInChannel(preferredChannelID, random(outs)); } boolean findWithSynonyms(String pat, String s) { for (String pat2 : splitAtComma(pat)) if (!findWithSynonyms2(pat2, s)) return false; return true; } boolean findWithSynonyms2(String pat2, String s) { for (String pat3 : synonyms.extend(pat2)) if (find3(pat3, s)) return true; return false; } boolean matchWithSynonyms(String pat, String s) { for (String pat2 : synonyms.extend(pat)) if (match(pat2, s)) return true; return false; } String forgetTopic(long channelID) { topicByChannel.remove(channelID); return "OK, let's talk about something else"; } } long totalRuleCount() { return intSumAsLong(map(syncCloneValues(dataByServer), bs -> l(bs.rules))); } String renderMasters() { return empty(authorizedUsers) ? "I have no masters." : "My masters are: " + ai_renderAndList(map("discordAt",authorizedUsers)); } List splitIntoLines(String s) { return tlft_honoringTokens(s); } } static boolean _moduleClass_NLRulesBot = true; static String discordAt(long userID) { return userID == 0 ? "unknown person" : "<@" + userID + ">"; } static volatile StringBuffer local_log = new StringBuffer(); // not redirected static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot // in bytes - will cut to half that static volatile int print_log_max = 1024*1024; static volatile int local_log_max = 100*1024; static boolean print_silent = false; // total mute if set static Object print_byThread_lock = new Object(); static volatile ThreadLocal print_byThread; // special handling by thread - prefers F1 static volatile Object print_allThreads; static volatile Object print_preprocess; static void print() { print(""); } static A print(String s, A o) { print((endsWithLetterOrDigit(s) ? s + ": " : s) + o); return o; } // slightly overblown signature to return original object... static A print(A o) { ping_okInCleanUp(); if (print_silent) return o; String s = String.valueOf(o) + "\n"; print_noNewLine(s); return o; } static void print_noNewLine(String s) { Object f = getThreadLocal(print_byThread_dontCreate()); if (f == null) f = print_allThreads; if (f != null) // We do need the general callF machinery here as print_byThread is sometimes shared between modules if (isFalse( f instanceof F1 ? ((F1) f).get(s) : callF(f, s))) return; print_raw(s); } static void print_raw(String s) { 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); } static void print_autoRotate() { } static GlobalID aGlobalIDObj() { return asGlobalID(randomID(16)); } static GlobalID aGlobalIDObj(Random random) { return asGlobalID(randomID(random, 16)); } static String appendNewLineIfNempty(String s) { return empty(s) ? "" : s + "\n"; } static void change() { //mainConcepts.allChanged(); // safe version for now cause function is sometimes included unnecessarily (e.g. by EGDiff) callOpt(getOptMC("mainConcepts"), "allChanged"); } static RuntimeException rethrow(Throwable t) { if (t instanceof Error) _handleError((Error) t); throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } static RuntimeException rethrow(String msg, Throwable t) { throw new RuntimeException(msg, t); } static boolean empty(Collection c) { return c == null || c.isEmpty(); } static boolean empty(Iterable c) { return c == null || !c.iterator().hasNext(); } static boolean empty(CharSequence s) { return s == null || s.length() == 0; } static boolean empty(Map map) { return map == null || map.isEmpty(); } static boolean empty(Object[] o) { return o == null || o.length == 0; } static boolean empty(Object o) { if (o instanceof Collection) return empty((Collection) o); if (o instanceof String) return empty((String) o); if (o instanceof Map) return empty((Map) o); if (o instanceof Object[]) return empty((Object[]) o); if (o instanceof byte[]) return empty((byte[]) o); if (o == null) return true; throw fail("unknown type for 'empty': " + getType(o)); } static boolean empty(Iterator i) { return i == null || !i.hasNext(); } static boolean empty(double[] a) { return a == null || a.length == 0; } static boolean empty(float[] a) { return a == null || a.length == 0; } static boolean empty(int[] a) { return a == null || a.length == 0; } static boolean empty(long[] a) { return a == null || a.length == 0; } static boolean empty(byte[] a) { return a == null || a.length == 0; } static boolean empty(short[] a) { return a == null || a.length == 0; } static boolean empty(MultiMap mm) { return mm == null || mm.isEmpty(); } static boolean empty(File f) { return getFileSize(f) == 0; } static boolean empty(IntRange r) { return r == null || r.empty(); } static String fullTrim(String s) { return fromLines(toLinesFullTrim(s)); } static void lock(Lock lock) { try { ping(); if (lock == null) return; try { lock.lockInterruptibly(); } catch (InterruptedException e) { print("Locking interrupted! I probably deadlocked, oops."); printStackTrace(e); rethrow(e); } ping(); } catch (Exception __e) { throw rethrow(__e); } } static void lock(Lock lock, String msg) { print("Locking: " + msg); lock(lock); } static void lock(Lock lock, String msg, long timeout) { print("Locking: " + msg); lockOrFail(lock, timeout); } static ReentrantLock lock() { return fairLock(); } static String factStore_cmds(SimpleFactStore factStore, String s, boolean allowChanges) { if (allowChanges) { if (match("clear facts", s)) { factStore.clear(); return "OK"; } } if (match("list facts", s)) { return ai_bracketUsersToDiscordAt(lines(factStore.facts())); } return null; } static String philosophyBotWithFactStore_discordAnswer(String theory, SimpleFactStore factStore, String s, Object... __) { return philosophyBotWithFactStore_discordAnswer(new PhilosophyBot1(theory), factStore, s, __); } static String philosophyBotWithFactStore_discordAnswer(PhilosophyBot1 bot, SimpleFactStore factStore, String s, Object... __) { long userID = (long) (optPar("userID",__)); boolean fromBot = boolPar("fromBot",__); print(userID + " (" + (fromBot ? "bot" : "human") + "): " + s); String user = "(user " + userID + ")"; if (factStore != null) { factStore.onChange(new Runnable() { public void run() { try { change(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "change();"; }}); factStore.verbose = true; philosophyBot1_factStore(bot, factStore); } bot.standardImports(); bot.autoOpenTheories(); bot.addFact(user + " is a " + (fromBot ? "bot" : "human")); bot.addFact(user + " says (" + bot.sanitizeInput(s) + ")"); bot.run(); return first(bot.matchFacts("$x", "say $x")); } static String ai_weightChangeBot_theory() { return "\r\n import math\r\n \r\n theory validity {\r\n // a human weighs between 80 and 400 pounds\r\n $x is a human\r\n & $x weighs ($y pounds)\r\n => $y >= 80 & $y <= 400\r\n \r\n contradiction => say (That can't be right)\r\n }\r\n \r\n theory (weight change) {\r\n $x weighs ($y pounds)\r\n & last time $x weighed ($z pounds)\r\n => proc {\r\n if ($y < $z):\r\n say (That is great!)\r\n else if ($y > $z):\r\n say (Aw, too bad, tomorrow is another day.)\r\n else:\r\n say (Tomorrow will be better)\r\n }\r\n }\r\n \r\n theory (remember last weight) {\r\n $x weighs ($y pounds)\r\n => proc {\r\n unless contradiction:\r\n delete all (last time $x weighed ($z pounds))\r\n store (last time $x weighed ($y pounds))\r\n }\r\n }\r\n \r\n theory (interpret input) {\r\n $x says (i weigh $y pounds)\r\n => $x weighs ($y pounds)\r\n \r\n $x says (my weight is $y pounds)\r\n => $x weighs ($y pounds)\r\n }\r\n "; } static long longPar(String name, Object... params) { return toLong(optPar(name, params)); } static boolean contains(Collection c, Object o) { return c != null && c.contains(o); } static boolean contains(Object[] x, Object o) { if (x != null) for (Object a : x) if (eq(a, o)) return true; return false; } static boolean contains(String s, char c) { return s != null && s.indexOf(c) >= 0; } static boolean contains(String s, String b) { return s != null && s.indexOf(b) >= 0; } static boolean contains(BitSet bs, int i) { return bs != null && bs.get(i); } static boolean contains(Producer p, A a) { if (p != null && a != null) while (true) { A x = p.next(); if (x == null) break; if (eq(x, a)) return true; } return false; } static A optPar(ThreadLocal tl, A defaultValue) { A a = tl.get(); if (a != null) { tl.set(null); return a; } return defaultValue; } static A optPar(ThreadLocal tl) { return optPar(tl, null); } static Object optPar(Object[] params, String name) { return optParam(params, name); } static Object optPar(String name, Object[] params) { return optParam(params, name); } static Object optPar(String name, Map params) { return optParam(name, params); } static A optPar(Object[] params, String name, A defaultValue) { return optParam(params, name, defaultValue); } static A optPar(String name, Object[] params, A defaultValue) { return optParam(params, name, defaultValue); } static Object first(Object list) { return first((Iterable) list); } static A first(List list) { return empty(list) ? null : list.get(0); } static A first(A[] bla) { return bla == null || bla.length == 0 ? null : bla[0]; } static A first(IterableIterator i) { return first((Iterator) i); } static A first(Iterator i) { return i == null || !i.hasNext() ? null : i.next(); } static A first(Iterable i) { if (i == null) return null; Iterator it = i.iterator(); return it.hasNext() ? it.next() : null; } static Character first(String s) { return empty(s) ? null : s.charAt(0); } static Character first(CharSequence s) { return empty(s) ? null : s.charAt(0); } static A first(Pair p) { return p == null ? null : p.a; } static A first(T3 t) { return t == null ? null : t.a; } static Byte first(byte[] l) { return empty(l) ? null : l[0]; } static File prepareCacheProgramFile(String name) { return mkdirsForFile(getCacheProgramFile(name)); } static File prepareCacheProgramFile(String progID, String name) { return mkdirsForFile(getCacheProgramFile(progID, name)); } static boolean deleteFile(File file) { return file != null && file.delete(); } static List tlft(String s) { return toLinesFullTrim(s); } static List tlft(File f) { return toLinesFullTrim(f); } static String loadTextFile(String fileName) { return loadTextFile(fileName, null); } static String loadTextFile(File f, String defaultContents) { return loadTextFile(f, defaultContents, "UTF-8"); } static String loadTextFile(File f, String defaultContents, String encoding) { try { checkFileNotTooBigToRead(f); if (f == null || !f.exists()) return defaultContents; FileInputStream fileInputStream = new FileInputStream(f); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding); return loadTextFile(inputStreamReader); } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFile(File fileName) { return loadTextFile(fileName, null); } static String loadTextFile(String fileName, String defaultContents) { return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents); } 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); } static boolean swic(String a, String b) { return startsWithIgnoreCase(a, b); } static boolean swic(String a, String b, Matches m) { if (!swic(a, b)) return false; m.m = new String[] {substring(a, l(b))}; return true; } static List regexpICFullMatch_groups(String pattern, String text) { Matcher matcher = regexpIC(pattern, text); return matcher.matches() ? regexpGetGroups(matcher) : null; } static boolean nempty(Collection c) { return !empty(c); } static boolean nempty(CharSequence s) { return !empty(s); } static boolean nempty(Object[] o) { return !empty(o); } static boolean nempty(byte[] o) { return !empty(o); } static boolean nempty(int[] o) { return !empty(o); } static boolean nempty(Map m) { return !empty(m); } static boolean nempty(Iterator i) { return i != null && i.hasNext(); } static boolean nempty(Object o) { return !empty(o); } static boolean nempty(IntRange r) { return !empty(r); } static T3 t3(A a, B b, C c) { return new T3(a, b, c); } static A second(List l) { return get(l, 1); } 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; } static A second(A[] bla) { return bla == null || bla.length <= 1 ? null : bla[1]; } static B second(Pair p) { return p == null ? null : p.b; } static B second(T3 t) { return t == null ? null : t.b; } static A second(Producer p) { if (p == null) return null; if (p.next() == null) return null; return p.next(); } static char second(String s) { return charAt(s, 1); } static B second(Either e) { return e == null ? null : e.bOpt(); } static String lines_rtrim(Collection lines) { return rtrim_fromLines(lines); } static String nRules(int n) { return n2(n, "rule"); } static String nRules(Collection l) { return n2(l, "rule"); } static int l(Object[] a) { return a == null ? 0 : a.length; } static int l(boolean[] a) { return a == null ? 0 : a.length; } static int l(byte[] a) { return a == null ? 0 : a.length; } static int l(short[] a) { return a == null ? 0 : a.length; } static int l(long[] a) { return a == null ? 0 : a.length; } static int l(int[] a) { return a == null ? 0 : a.length; } static int l(float[] a) { return a == null ? 0 : a.length; } static int l(double[] a) { return a == null ? 0 : a.length; } static int l(char[] a) { return a == null ? 0 : a.length; } static int l(Collection c) { return c == null ? 0 : c.size(); } static int l(Iterator i) { return iteratorCount_int_close(i); } // consumes the iterator && closes it if possible static int l(Map m) { return m == null ? 0 : m.size(); } static int l(CharSequence s) { return s == null ? 0 : s.length(); } static long l(File f) { return f == null ? 0 : f.length(); } static int l(Object o) { return o == null ? 0 : o instanceof String ? l((String) o) : o instanceof Map ? l((Map) o) : o instanceof Collection ? l((Collection) o) : o instanceof Object[] ? l((Object[]) o) : o instanceof boolean[] ? l((boolean[]) o) : o instanceof byte[] ? l((byte[]) o) : o instanceof char[] ? l((char[]) o) : o instanceof short[] ? l((short[]) o) : o instanceof int[] ? l((int[]) o) : o instanceof float[] ? l((float[]) o) : o instanceof double[] ? l((double[]) o) : o instanceof long[] ? l((long[]) o) : (Integer) call(o, "size"); } static int l(IntRange r) { return r == null ? 0 : r.length(); } static long l(LongRange r) { return r == null ? 0 : r.length(); } // does not store null values static Map indexByField(Iterable c, String field) { HashMap map = new HashMap(); for (Object a : c) { Object val = getOpt(a, field); if (val != null) map.put(val, a); } return map; } static Map indexByField(String field, Iterable c) { return indexByField(c, field); } static String trim(String s) { return s == null ? null : s.trim(); } static String trim(StringBuilder buf) { return buf.toString().trim(); } static String trim(StringBuffer buf) { return buf.toString().trim(); } static boolean neq(Object a, Object b) { return !eq(a, b); } static boolean match(String pat, String s) { return match3(pat, s); } static boolean match(String pat, String s, Matches matches) { return match3(pat, s, matches); } static boolean match(String pat, List toks, Matches matches) { return match3(pat, toks, matches); } static A firstWhereIC(Collection c, Object... data) { return findWhereIC(c, data); } static byte[] toUtf8(String s) { try { return s.getBytes("UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } static String lines(Iterable lines) { return fromLines(lines); } static String lines(Object[] lines) { return fromLines(asList(lines)); } static List lines(String s) { return toLines(s); } static List map(Iterable l, Object f) { return map(f, l); } static List map(Object f, Iterable l) { List x = emptyList(l); if (l != null) for (Object o : l) x.add(callF(f, o)); return x; } static List map(Iterable l, F1 f) { return map(f, l); } static List map(F1 f, Iterable l) { List x = emptyList(l); if (l != null) for (A o : l) x.add(callF(f, o)); return x; } static List map(IF1 f, Iterable l) { return map(l, f); } 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; } static List map(IF1 f, A[] l) { return map(l, f); } 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; } static List map(Object f, Object[] l) { return map(f, asList(l)); } static List map(Object[] l, Object f) { return map(f, l); } static List map(Object f, Map map) { return map(map, f); } // map: func(key, value) -> list element static List map(Map map, Object f) { List x = new ArrayList(); if (map != null) for (Object _e : map.entrySet()) { Map.Entry e = (Map.Entry) _e; x.add(callF(f, e.getKey(), e.getValue())); } return x; } static List map(Map map, IF2 f) { return map(map, (Object) f); } static A firstWhere(Collection c, Object... data) { return findWhere(c, data); } static String nRule(int n) { return nRules(n); } static String nRule(Collection l) { return nRules(l); } static void appendToTextFile(File file, String s) { appendToFile(file, s); } static void appendToTextFile(String file, String s) { appendToTextFile(programFile(file), s); } static File programFile(String name) { return prepareProgramFile(name); } static File programFile(String progID, String name) { return prepareProgramFile(progID, name); } static boolean matchX(String pat, String s) { return matchX(pat, s, null); } static boolean matchX(String pat, String s, Matches m) { if (endsWith(pat, "...")) { pat = dropSuffixTrim("...", pat); if (startsWith(pat, "...")) return find3(dropPrefixTrim("...", pat), s, m); else return matchStart(pat, s, m); } if (startsWith(pat, "...")) return matchEndX(pat, s, m); return match(pat, s, m); } static List unquoteAll(List l) { List t = cloneList(l); for (int i = 0; i < l(t); i++) if (isQuoted(t.get(i))) t.set(i, unquote(t.get(i))); return t; } static Map> wordTokC_cache = synchronizedMRUCache(defaultTokenizerCacheSize()); static List wordTokC(String s) { List tok = wordTokC_cache.get(s); if (tok == null) wordTokC_cache.put(s, tok = codeTokens(wordTok(s))); return tok; } static A printStruct(String prefix, A a) { printStructure(prefix, a); return a; } static A printStruct(A a) { printStructure(a); return a; } static String format(String pat, Object... args) { return format3(pat, args); } static String or2(String a, String b) { return nempty(a) ? a : b; } static String or2(String a, String b, String c) { return or2(or2(a, b), c); } 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)); } static String join(Iterable strings) { return join("", strings); } static String join(Iterable strings, String glue) { return join(glue, strings); } public static String join(String[] strings) { return join("", strings); } static String join(String glue, Pair p) { return p == null ? "" : str(p.a) + glue + str(p.b); } static String str(Object o) { return o == null ? "null" : o.toString(); } static String str(char[] c) { return new String(c); } // dynamic only for now static String dm_findModule(String moduleLibID) { return (String) callCreator("findModuleByLibID", moduleLibID); } static Object dm_call(Object moduleOrID, String method, Object... args) { Object mod = dm_getModule(moduleOrID); if (mod == null) return null; AutoCloseable __1 = dm_enter(mod); try { return call_withVarargs(mod, method, args); } finally { _close(__1); }} static Object dm_get(Object moduleOrID, String field) { return get(dm_getModule(moduleOrID), field); } static Object dm_get(String field, long moduleID) { return dm_get(moduleID, field); } static void dm_reloadModule(Object module) { dm_reloadModuleInBackground(module); } static void dm_reloadModule() { dm_reloadModuleInBackground(); } static boolean eqic(String a, String b) { if ((a == null) != (b == null)) return false; if (a == null) return true; return a.equalsIgnoreCase(b); } 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); } static String ltrim(String s) { if (s == null) return null; int i = 0; while (i < s.length() && " \t\r\n".indexOf(s.charAt(i)) >= 0) ++i; return i > 0 ? substring(s, i) : s; } static boolean matchX2(String pat, String s) { return matchX_vbar(pat, s); } static boolean matchX2(String pat, String s, Matches matches) { return matchX_vbar(pat, s, matches); } static boolean put_trueIfChanged(Map map, A key, B value) { return mapPut_trueIfChanged(map, key, value); } static boolean match_vbar(String pat, String s) { return match_vbar(pat, s, null); } static boolean match_vbar(String pat, String s, Matches matches) { for (String pat2 : tok_splitAtVerticalBar(pat)) if (match3(pat2, s, matches)) return true; return false; } static boolean flexMatchIC(String pat, String s) { return flexMatchIC2(pat, s); } static boolean flexMatchIC(String pat, String s, Matches m) { return flexMatchIC2(pat, s, m); } static boolean flexMatchIC(String pat, List tokfull, Matches m) { return flexMatchIC2(pat, tokfull, m, true); } static boolean flexMatchIC(String pat, String s, Matches m, boolean joinBrackets) { return flexMatchIC2(pat, s, m, joinBrackets); } static String replaceWord(String s, String pattern, String replacement) { return replacePhrase(s, pattern, replacement); } static boolean discord_isNSFWChannel_gen(Object channel) { return isTrue(callOpt(channel, "isNSFW")); } static String quickVisualize_nsfw_progID = "#1007145"; static Lock quickVisualize_nsfw_lock = lock(); static boolean quickVisualize_nsfw_hasCached(String query) { return quickVisualize_nsfw_imageFile(query).length() != 0; } static BufferedImage quickVisualize_nsfw_fromCache(String query) { File f = quickVisualize_nsfw_imageFile(query); if (f.length() != 0) { try { return loadPNG(f); } catch (Throwable __e) { _handleException(__e); }} return null; } static String quickVisualize_nsfw_preprocess(String query) { return toUpper(shorten(trim(query), 200)); } static BufferedImage quickVisualize_nsfw(String query) { query = quickVisualize_nsfw_preprocess(query); if (empty(query)) return null; BufferedImage img = quickVisualize_nsfw_fromCache(query); if (img != null) return img; File f = quickVisualize_nsfw_imageFile(query); /*L urls = googleImageSearch_multi(query); saveTextFile(quickVisualize_nsfw_urlsFile(query), joinLines(urls)); if (empty(urls)) null; img = loadBufferedImage(first(urls));*/ Lock __0 = quickVisualize_nsfw_lock; lock(__0); try { AutoCloseable __2 = tempSetTL(googleImageSearch_new_nsfw, true); try { img = googleImageSearch_new(query); if (img == null) return null; savePNG(f, img); return img; } finally { _close(__2); }} finally { unlock(__0); } } static String quickVisualize_nsfw_imagePath(String query) { query = quickVisualize_nsfw_preprocess(query); return fsI(quickVisualize_nsfw_progID) + "/nsfw/" + urlencode(query) + ".png"; } static File quickVisualize_nsfw_imageFile(String query) { query = quickVisualize_nsfw_preprocess(query); return prepareProgramFile(quickVisualize_nsfw_progID, "nsfw/" + urlencode(query) + ".png"); } static File quickVisualize_nsfw_urlsFile(String query) { query = quickVisualize_nsfw_preprocess(query); return prepareProgramFile(quickVisualize_nsfw_progID, "urls-" + urlencode(query) + ".txt"); } static String quickVisualize_progID = "#1007145"; static Lock quickVisualize_lock = lock(); static boolean quickVisualize_hasCached(String query) { return quickVisualize_imageFile(query).length() != 0; } static BufferedImage quickVisualize_fromCache(String query) { File f = quickVisualize_imageFile(query); if (f.length() != 0) { try { return loadPNG(f); } catch (Throwable __e) { _handleException(__e); }} return null; } static String quickVisualize_preprocess(String query) { return toUpper(shorten(trim(query), 200)); } static BufferedImage quickVisualize(String query) { query = quickVisualize_preprocess(query); if (empty(query)) return null; BufferedImage img = quickVisualize_fromCache(query); if (img != null) return img; File f = quickVisualize_imageFile(query); /*L urls = googleImageSearch_multi(query); saveTextFile(quickVisualize_urlsFile(query), joinLines(urls)); if (empty(urls)) null; img = loadBufferedImage(first(urls));*/ Lock __0 = quickVisualize_lock; lock(__0); try { img = googleImageSearch_new(query); if (img == null) return null; savePNG(f, img); return img; } finally { unlock(__0); } } static String quickVisualize_imagePath(String query) { query = quickVisualize_preprocess(query); return fsI(quickVisualize_progID) + "/" + urlencode(query) + ".png"; } static File quickVisualize_imageFile(String query) { query = quickVisualize_preprocess(query); return prepareProgramFile(quickVisualize_progID, urlencode(query) + ".png"); } static File quickVisualize_urlsFile(String query) { query = quickVisualize_preprocess(query); return prepareProgramFile(quickVisualize_progID, "urls-" + urlencode(query) + ".txt"); } 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; } static String uploadToImageServer(BufferedImage img, String name) { return uploadToImageServerIfNotThere(img, name); } static String uploadToImageServer(String name, BufferedImage img) { return uploadToImageServerIfNotThere(img, name); } static String uploadToImageServer(File f) { return uploadFileToImageServer(f); } static String discord_google(String query, Object... __) { int results = optPar("results",__, 3); boolean safeSearch = boolPar("safeSearch",__); boolean withDescription = boolPar("withDescription",__); String noResultsMsg = (String) (optPar("noResultsMsg",__)); if (noResultsMsg == null) noResultsMsg = "GBot is currently broken, fixing ASAP (2020/2/21)"; //"Sorry - no results found. SafeSearch is " + (safeSearch ? "on" : "off") + "."; List> l = safeSearch ? quickGoogle2_safeSearch(query) : quickGoogle2(query); return or2(lines(map(takeFirst(results, l), linkTextDesc -> unicode_smallBlackSquare() + " **" + linkTextDesc.b + "**\n" + (!withDescription ? "" : linkTextDesc.c + "\n") + "<" + linkTextDesc.a + ">")), noResultsMsg); } static volatile PersistableThrowable _handleException_lastException; static List _handleException_onException = synchroList(ll("printStackTrace2")); static void _handleException(Throwable e) { _handleException_lastException = persistableThrowable(e); Throwable e2 = innerException(e); if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException) return; for (Object f : cloneList(_handleException_onException)) try { callF(f, e); } catch (Throwable e3) { printStackTrace2(e3); // not using pcall here - it could lead to endless loops } } static boolean matchStartX(String pat, String s, Matches matches) { return matchStart(dropSuffix("...", pat), s, matches); } static String structure_nullingInstancesOfClass(Class c, Object o) { if (c == null) return structure(o); structure_Data data = new structure_Data(); structure_ClassInfo info = new structure_ClassInfo(); info.special = info.nullInstances = true; data.infoByClass.put(c, info); return structure(o, data); } static Class _getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; // could optimize this } } static Class _getClass(Object o) { return o == null ? null : o instanceof Class ? (Class) o : o.getClass(); } static Class _getClass(Object realm, String name) { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; // could optimize this } } static String n2(long l) { return formatWithThousands(l); } static String n2(Collection l) { return n2(l(l)); } static String n2(Map map) { return n2(l(map)); } static String n2(double l, String singular) { return n2(l, singular, singular + "s"); } static String n2(double l, String singular, String plural) { if (fraction(l) == 0) return n2((long) l, singular, plural); else return l + " " + plural; } static String n2(long l, String singular, String plural) { return n_fancy2(l, singular, plural); } static String n2(long l, String singular) { return n_fancy2(l, singular, singular + "s"); } static String n2(Collection l, String singular) { return n2(l(l), singular); } static String n2(Collection l, String singular, String plural) { return n_fancy2(l, singular, plural); } static String n2(Map m, String singular, String plural) { return n_fancy2(m, singular, plural); } static String n2(Map m, String singular) { return n2(l(m), singular); } static String n2(Object[] a, String singular) { return n2(l(a), singular); } static String n2(Object[] a, String singular, String plural) { return n_fancy2(a, singular, plural); } static Random random_random = new Random(); static int random(int n) { return random(random_random, n); } static int random(int n, Random r) { return random(r, n); } static int random(Random r, int n) { return n <= 0 ? 0 : r.nextInt(n); } static double random(double max) { return random()*max; } static double random() { return random_random.nextInt(100001)/100000.0; } static double random(double min, double max) { return min+random()*(max-min); } // min <= value < max static int random(int min, int max) { return min+random(max-min); } static int random(int min, int max, Random r) { return random(r, min, max); } static int random(Random r, int min, int max) { return min+random(r, max-min); } static A random(List l) { return oneOf(l); } static A random(Collection c) { if (c instanceof List) return random((List) c); int i = random(l(c)); return collectionGet(c, i); } static int random(IntRange r) { return random(r.start, r.end); } static String answer_magicQuoteInput(String input, Object... __) { List fixedInputs = magicQuoteInputForThisProgram(input, __); if (nempty(fixedInputs)) return "Did you mean this? >> " + first(fixedInputs) + (l(fixedInputs) < 2 ? "" : "\nOr this? >> " + second(fixedInputs)); return null; } static void unlock(Lock lock, String msg) { if (lock == null) return; print("Unlocking: " + msg); lock.unlock(); } static void unlock(Lock lock) { if (lock == null) return; lock.unlock(); } static boolean containsIC(Collection l, String s) { return containsIgnoreCase(l, s); } static boolean containsIC(String[] l, String s) { return containsIgnoreCase(l, s); } static boolean containsIC(String s, char c) { return containsIgnoreCase(s, c); } static boolean containsIC(String a, String b) { return containsIgnoreCase(a, b); } static boolean containsIC(Producer p, String a) { if (p != null && a != null) while (true) { String x = p.next(); if (x == null) break; if (eqic(x, a)) return true; } return false; } static String discord_optParUserName(Object... __) { Object event = optPar("event",__); Object user = rcall("getAuthor",event); return rcall_string("getName",user); } static List replaceIC(List l, String a, String b) { List l2 = new ArrayList(); for (int i = 0; i < l(l); i++) { String s = l.get(i); l2.add(eqic(s, a) ? b : s); } return l2; } static String replaceIC(String s, String a, String b) { return s.replaceAll("(?i)" + patternQuote(a), quoteReplacement(b)); } static long parseLongOpt(String s) { return isInteger(s) ? parseLong(s) : 0; } static List splitAtComma(String s) { return empty(s) ? emptyList() : asList(s.split(",")); } static boolean find3(String pat, String s) { return find3(pat, s, null); } static boolean find3(String pat, String s, Matches matches) { return find3(pat, parse3_cachedInput(s), matches); } static boolean find3(String pat, List toks, Matches matches) { List tokpat = parse3_cachedPattern(pat); String[] m = find2(tokpat, toks); //print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m)); if (m == null) return false; if (matches != null) matches.m = m; return true; } static long intSumAsLong(Iterable l) { long sum = 0; for (Integer i : unnull(l)) if (i != null) sum += i; return sum; } static List syncCloneValues(Map map) { if (map == null) return new ArrayList(); synchronized(map) { return cloneList(values(map)); } } static String ai_renderAndList(List l) { return textOut_and(l); } static String ai_renderAndList(List l, String emptyText) { return textOut_and(l, emptyText); } static List tlft_honoringTokens(String s) { List indices = new ArrayList(); List tok = javaTok(s); List out = new ArrayList(); int start = 0; for (int i = 2; i+1 < l(tok); i += 2) { { if (!(containsNewLine(tok.get(i)))) continue; } addIfNempty(out, trimJoinSubList(tok, start, i)); start = i+1; } if (start < l(tok)) addIfNempty(out, trimJoinSubList(tok, start)); return out; } static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) { return print_byThread().get() == null ? tempInterceptPrint(f) : null; } static Throwable printStackTrace2(Throwable e) { // we go to system.out now - system.err is nonsense print(getStackTrace2(e)); return e; } static void printStackTrace2() { printStackTrace2(new Throwable()); } static void printStackTrace2(String msg) { printStackTrace2(new Throwable(msg)); } static boolean endsWithLetterOrDigit(String s) { return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1)); } static void ping_okInCleanUp() { if (ping_pauseAll || ping_anyActions) ping_impl(true); } // this syntax should be removed... static Object getThreadLocal(Object o, String name) { ThreadLocal t = (ThreadLocal) (getOpt(o, name)); return t != null ? t.get() : null; } static A getThreadLocal(ThreadLocal tl) { return tl == null ? null : tl.get(); } static A getThreadLocal(ThreadLocal tl, A defaultValue) { return or(getThreadLocal(tl), defaultValue); } static ThreadLocal print_byThread_dontCreate() { return print_byThread; } static boolean isFalse(Object o) { return eq(false, o); } static Map> callF_cache = newDangerousWeakHashMap(); static A callF(F0 f) { return f == null ? null : f.get(); } static B callF(F1 f, A a) { return f == null ? null : f.get(a); } static A callF(IF0 f) { return f == null ? null : f.get(); } static B callF(IF1 f, A a) { return f == null ? null : f.get(a); } static C callF(F2 f, A a, B b) { return f == null ? null : f.get(a, b); } static C callF(IF2 f, A a, B b) { return f == null ? null : f.get(a, b); } static void callF(VF1 f, A a) { if (f != null) f.get(a); } static Object callF(Object f, Object... args) { try { if (f instanceof String) return callMCWithVarArgs((String) f, args); // possible SLOWDOWN over callMC if (f instanceof Runnable) { ((Runnable) f).run(); return null; } if (f == null) return null; Class c = f.getClass(); ArrayList methods; synchronized(callF_cache) { methods = callF_cache.get(c); if (methods == null) methods = callF_makeCache(c); } int n = l(methods); if (n == 0) { throw fail("No get method in " + getClassName(c)); } if (n == 1) return invokeMethod(methods.get(0), f, args); for (int i = 0; i < n; i++) { Method m = methods.get(i); if (call_checkArgs(m, args, false)) return invokeMethod(m, f, args); } throw fail("No matching get method in " + getClassName(c)); } catch (Exception __e) { throw rethrow(__e); } } // used internally static ArrayList callF_makeCache(Class c) { ArrayList l = new ArrayList(); Class _c = c; do { for (Method m : _c.getDeclaredMethods()) if (m.getName().equals("get")) { makeAccessible(m); l.add(m); } if (!l.isEmpty()) break; _c = _c.getSuperclass(); } while (_c != null); callF_cache.put(c, l); return l; } static String fixNewLines(String s) { int i = indexOf(s, '\r'); if (i < 0) return s; int l = s.length(); StringBuilder out = new StringBuilder(l); out.append(s, 0, i); for (; i < l; i++) { char c = s.charAt(i); if (c != '\r') out.append(c); else { out.append('\n'); if (i+1 < l && s.charAt(i+1) == '\n') ++i; } } return out.toString(); } static void print_append(Appendable buf, String s, int max) { try { synchronized(buf) { buf.append(s); if (buf instanceof StringBuffer) rotateStringBuffer(((StringBuffer) buf), max); else if (buf instanceof StringBuilder) rotateStringBuilder(((StringBuilder) buf), max); } } catch (Exception __e) { throw rethrow(__e); } } static GlobalID asGlobalID(String id) { return id == null ? null : new GlobalID(id); } static int randomID_defaultLength = 12; static String randomID(int length) { return makeRandomID(length); } static String randomID(Random r, int length) { return makeRandomID(r, length); } static String randomID() { return randomID(randomID_defaultLength); } static String randomID(Random r) { return randomID(r, randomID_defaultLength); } static Object callOpt(Object o) { return callF(o); } static A callOpt(Object o, String method, Object... args) { return (A) callOpt_withVarargs(o, method, args); } static Object getOptMC(String field) { return getOpt(mc(), field); } static void _handleError(Error e) { call(javax(), "_handleError", e); } static RuntimeException fail() { throw new RuntimeException("fail"); } static RuntimeException fail(Throwable e) { throw asRuntimeException(e); } static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); } static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); } static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); } static String getType(Object o) { return getClassName(o); } static long getFileSize(String path) { return path == null ? 0 : new File(path).length(); } static long getFileSize(File f) { return f == null ? 0 : f.length(); } // usually L 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(); } static String fromLines(String... lines) { return fromLines(asList(lines)); } static List toLinesFullTrim(String s) { List l = new ArrayList(); for (String line : toLines(s)) if (nempty(line = trim(line))) l.add(line); return l; } static List toLinesFullTrim(File f) { List l = new ArrayList(); for (String line : linesFromFile(f)) if (nempty(line = trim(line))) l.add(line); return l; } //sbool ping_actions_shareable = true; static volatile boolean ping_pauseAll = false; static int ping_sleep = 100; // poll pauseAll flag every 100 static volatile boolean ping_anyActions = false; static Map ping_actions = newWeakHashMap(); static ThreadLocal ping_isCleanUpThread = new ThreadLocal(); // always returns true static boolean ping() { if (ping_pauseAll || ping_anyActions) ping_impl(true /* XXX */); //ifndef LeanMode ping_impl(); endifndef return true; } // returns true when it slept static boolean ping_impl(boolean okInCleanUp) { try { if (ping_pauseAll && !isAWTThread()) { do Thread.sleep(ping_sleep); while (ping_pauseAll); return true; } if (ping_anyActions) { // don't allow sharing ping_actions if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get())) failIfUnlicensed(); Object action = null; synchronized(ping_actions) { if (!ping_actions.isEmpty()) { action = ping_actions.get(currentThread()); if (action instanceof Runnable) ping_actions.remove(currentThread()); if (ping_actions.isEmpty()) ping_anyActions = false; } } if (action instanceof Runnable) ((Runnable) action).run(); else if (eq(action, "cancelled")) throw fail("Thread cancelled."); } return false; } catch (Exception __e) { throw rethrow(__e); } } static A printStackTrace(A e) { // we go to system.out now - system.err is nonsense print(getStackTrace(e)); return e; } static void printStackTrace() { printStackTrace(new Throwable()); } static void printStackTrace(String msg) { printStackTrace(new Throwable(msg)); } static void printStackTrace(String msg, Throwable e) { printStackTrace(new Throwable(msg, e)); } static void lockOrFail(Lock lock, long timeout) { try { ping(); if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) { String s = "Couldn't acquire lock after " + timeout + " ms."; if (lock instanceof ReentrantLock) { ReentrantLock l = (ReentrantLock) lock; s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner"); } throw fail(s); } ping(); } catch (Exception __e) { throw rethrow(__e); } } static ReentrantLock fairLock() { return new ReentrantLock(true); } static String ai_bracketUsersToDiscordAt(String s) { return regexpReplaceIC(s, "\\(user (\\d+)\\)", matcher -> "<@" + matcher.group(1) + ">"); } static boolean boolPar(ThreadLocal tl) { return boolOptParam(tl); } // defaults to false static boolean boolPar(Object[] __, String name) { return boolOptParam(__, name); } static boolean boolPar(String name, Object[] __) { return boolOptParam(__, name); } static boolean boolPar(String name, Map __) { return boolOptParam(name, __); } static boolean boolPar(String name, Object[] params, boolean defaultValue) { return optParam(params, name, defaultValue); } static void philosophyBot1_factStore(PhilosophyBot1 bot, IFactStore factStore, Object... __) { if (factStore == null) return; bot.addFacts(factStore.facts()); boolean debug = boolPar("debug",__); bot.addNativePredicate("delete all $x", (map) -> { String pat = map.get("$x"); factStore.deleteAll(s -> { Map map2 = bot.zipIt(pat, s); if (map2 == null) return false; if (debug) print("Delete match: " + map2); return true; }); return true; }); bot.addNativePredicate("store $x", (map) -> { String x = map.get("$x"); if (debug) print("factStore: store " + x); factStore.store(x); return true; }); } static long toLong(Object o) { if (o instanceof Number) return ((Number) o).longValue(); if (o instanceof String) return parseLong((String) o); return 0; } static boolean eq(Object a, Object b) { return a == b || a != null && b != null && a.equals(b); } static A optParam(ThreadLocal tl, A defaultValue) { return optPar(tl, defaultValue); } static A optParam(ThreadLocal tl) { return optPar(tl); } static Object optParam(String name, Map params) { return mapGet(params, name); } // now also takes a map as single array entry 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; } static Object optParam(Object[] opt, String name) { return optParam(opt, name, null); } static Object optParam(String name, Object[] params) { return optParam(params, name); } public static File mkdirsForFile(File file) { File dir = file.getParentFile(); if (dir != null) { // is null if file is in current dir dir.mkdirs(); if (!dir.isDirectory()) if (dir.isFile()) throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!"); else throw fail("Unknown IO exception during mkdirs of " + f2s(file)); } return file; } public static String mkdirsForFile(String path) { mkdirsForFile(new File(path)); return path; } static File getCacheProgramFile(String progID, String fileName) { if (new File(fileName).isAbsolute()) return new File(fileName); return new File(getCacheProgramDir(progID), fileName); } static File getCacheProgramFile(String fileName) { return getCacheProgramFile(getProgramID(), fileName); } static ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal(); static void checkFileNotTooBigToRead(File f) { callF(checkFileNotTooBigToRead_tl.get(), f); } static File newFile(File base, String... names) { for (String name : names) base = new File(base, name); return base; } static File newFile(String name) { return name == null ? null : new File(name); } static File newFile(String base, String... names) { return newFile(newFile(base), names); } static boolean startsWithIgnoreCase(String a, String b) { return regionMatchesIC(a, 0, b, 0, b.length()); } static String substring(String s, int x) { return substring(s, x, strL(s)); } static String substring(String s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; int n = s.length(); if (y < x) y = x; if (y > n) y = n; if (x >= y) return ""; return s.substring(x, y); } static String substring(String s, IntRange r) { return r == null ? null : substring(s, r.start, r.end); } // convenience method for quickly dropping a prefix static String substring(String s, CharSequence l) { return substring(s, l(l)); } static Matcher regexpIC(Pattern pat, String s) { return pat.matcher(unnull(s)); } static Matcher regexpIC(String pat, String s) { return compileRegexpIC(pat).matcher(unnull(s)); } static Pattern regexpIC(String pat) { return compileRegexpIC(pat); } static List regexpGetGroups(Matcher matcher) { int n = matcher.groupCount(); List l = new ArrayList(); for (int i = 1; i <= n; i++) l.add(matcher.group(i)); return l; } // performs find() static List regexpGetGroups(String pat, String s) { Matcher m = regexpMatcher(pat, s); if (m.find()) return regexpGetGroups(m); return null; } // get purpose 1: access a list/array/map (safer version of x.get(y)) static A get(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } // seems to conflict with other signatures /*static B get(Map map, A key) { ret map != null ? map.get(key) : null; }*/ static A get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } // default to false static boolean get(boolean[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : false; } // get purpose 2: access a field by reflection or a map static Object get(Object o, String field) { try { if (o == null) return null; if (o instanceof Class) return get((Class) o, field); if (o instanceof Map) return ((Map) o).get(field); Field f = getOpt_findField(o.getClass(), field); if (f != null) { makeAccessible(f); return f.get(o); } if (o instanceof DynamicObject) return ((DynamicObject) o).fieldValues.get(field); } catch (Exception e) { throw asRuntimeException(e); } throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName()); } static Object get_raw(String field, Object o) { return get_raw(o, field); } static Object get_raw(Object o, String field) { try { if (o == null) return null; Field f = get_findField(o.getClass(), field); makeAccessible(f); return f.get(o); } catch (Exception __e) { throw rethrow(__e); } } static Object get(Class c, String field) { try { Field f = get_findStaticField(c, field); makeAccessible(f); return f.get(null); } catch (Exception e) { throw new RuntimeException(e); } } static Field get_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } static Field get_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } static Object get(String field, Object o) { return get(o, field); } static Iterator iterator(Iterable c) { return c == null ? emptyIterator() : c.iterator(); } static char charAt(String s, int i) { return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0'; } 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(); } static int iteratorCount_int_close(Iterator i) { try { int n = 0; if (i != null) while (i.hasNext()) { i.next(); ++n; } if (i instanceof AutoCloseable) ((AutoCloseable) i).close(); return n; } catch (Exception __e) { throw rethrow(__e); } } static Object call(Object o) { return callF(o); } // varargs assignment fixer for a single string array argument static Object call(Object o, String method, String[] arg) { return call(o, method, new Object[] {arg}); } static Object call(Object o, String method, Object... args) { //ret call_cached(o, method, args); return call_withVarargs(o, method, args); } static Object getOpt(Object o, String field) { return getOpt_cached(o, field); } static Object getOpt(String field, Object o) { return getOpt_cached(o, field); } static Object getOpt_raw(Object o, String field) { try { Field f = getOpt_findField(o.getClass(), field); if (f == null) return null; makeAccessible(f); return f.get(o); } catch (Exception __e) { throw rethrow(__e); } } // access of static fields is not yet optimized static Object getOpt(Class c, String field) { try { if (c == null) return null; Field f = getOpt_findStaticField(c, field); if (f == null) return null; makeAccessible(f); return f.get(null); } catch (Exception __e) { throw rethrow(__e); } } static Field getOpt_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static boolean match3(String pat, String s) { return match3(pat, s, null); } static boolean match3(String pat, String s, Matches matches) { if (pat == null || s == null) return false; return match3(pat, parse3_cachedInput(s), matches); } static boolean match3(String pat, List toks, Matches matches) { List tokpat = parse3_cachedPattern(pat); return match3(tokpat, toks, matches); } static boolean match3(List tokpat, List toks, Matches matches) { String[] m = match2(tokpat, toks); //print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m)); if (m == null) return false; if (matches != null) matches.m = m; return true; } static A findWhereIC(Collection c, Object... data) { if (c != null) for (A x : c) if (checkFieldsIC(x, data)) return x; return null; } // unclear semantics as to whether return null on null static ArrayList asList(A[] a) { return a == null ? new ArrayList() : new ArrayList(Arrays.asList(a)); } static ArrayList asList(int[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (int i : a) l.add(i); return l; } static ArrayList asList(float[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (float i : a) l.add(i); return l; } static ArrayList asList(double[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (double i : a) l.add(i); return l; } static ArrayList asList(Iterable s) { if (s instanceof ArrayList) return (ArrayList) s; ArrayList l = new ArrayList(); if (s != null) for (A a : s) l.add(a); return l; } static ArrayList asList(Producer p) { ArrayList l = new ArrayList(); A a; if (p != null) while ((a = p.next()) != null) l.add(a); return l; } static ArrayList asList(Enumeration e) { ArrayList l = new ArrayList(); if (e != null) while (e.hasMoreElements()) l.add(e.nextElement()); return l; } static IterableIterator toLines(File f) { return linesFromFile(f); } 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; } static int toLines_nextLineBreak(String s, int start) { int n = s.length(); for (int i = start; i < n; i++) { char c = s.charAt(i); if (c == '\r' || c == '\n') return i; } return -1; } static ArrayList emptyList() { return new ArrayList(); //ret Collections.emptyList(); } static ArrayList emptyList(int capacity) { return new ArrayList(max(0, capacity)); } // Try to match capacity static ArrayList emptyList(Iterable l) { return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList(); } static ArrayList emptyList(Object[] l) { return emptyList(l(l)); } // get correct type at once static ArrayList emptyList(Class c) { return new ArrayList(); } static A findWhere(Collection c, Object... data) { if (c != null) for (A x : c) if (checkFields(x, data)) return x; return null; } static Lock appendToFile_lock = lock(); static boolean appendToFile_keepOpen = false; static HashMap appendToFile_writers = new HashMap(); static void appendToFile(String path, String s) { try { Lock __0 = appendToFile_lock; lock(__0); try { // Let's just generally synchronize this to be safe. mkdirsForFile(new File(path)); path = getCanonicalPath(path); Writer writer = appendToFile_writers.get(path); if (writer == null) { //print("[Logging to " + path + "]"); writer = new BufferedWriter(new OutputStreamWriter( newFileOutputStream(path, true), "UTF-8")); if (appendToFile_keepOpen) appendToFile_writers.put(path, writer); } writer.write(s); if (!appendToFile_keepOpen) writer.close(); } finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } } static void appendToFile(File path, String s) { if (path != null) appendToFile(path.getPath(), s); } static void cleanMeUp_appendToFile() { AutoCloseable __3 = tempCleaningUp(); try { Lock __1 = appendToFile_lock; lock(__1); try { closeAllWriters(values(appendToFile_writers)); appendToFile_writers.clear(); } finally { unlock(__1); } } finally { _close(__3); }} static File prepareProgramFile(String name) { return mkdirsForFile(getProgramFile(name)); } static File prepareProgramFile(String progID, String name) { return mkdirsForFile(getProgramFile(progID, name)); } static boolean endsWith(String a, String b) { return a != null && a.endsWith(b); } static boolean endsWith(String a, char c) { return nempty(a) && lastChar(a) == c; } static boolean endsWith(String a, String b, Matches m) { if (!endsWith(a, b)) return false; m.m = new String[] {dropLast(l(b), a)}; return true; } static String dropSuffixTrim(String suffix, String s) { return dropSuffixAndTrim(suffix, s); } static boolean dropSuffixTrim(String suffix, String s, Matches m) { if (!endsWith(s, suffix)) return false; m.m = new String[] { dropLast(l(suffix), s) }; return true; } static boolean startsWith(String a, String b) { return a != null && a.startsWith(unnull(b)); } static boolean startsWith(String a, char c) { return nemptyString(a) && a.charAt(0) == c; } static boolean startsWith(String a, String b, Matches m) { if (!startsWith(a, b)) return false; m.m = new String[] {substring(a, strL(b))}; return true; } 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; } static String dropPrefixTrim(String prefix, String s) { return trim(dropPrefix(prefix, s)); } static boolean matchStart(String pat, String s) { return matchStart(pat, s, null); } // matches are as you expect, plus an extra item for the rest string static boolean matchStart(String pat, String s, Matches matches) { if (s == null) return false; return matchStart(pat, parse3_cachedInput(s), matches); } static boolean matchStart(String pat, List toks, Matches matches) { if (toks == null) return false; List tokpat = parse3_cachedPattern(pat); if (toks.size() < tokpat.size()) return false; String[] m = match2(tokpat, toks.subList(0, tokpat.size())); //print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m)); if (m == null) return false; if (matches != null) { matches.m = new String[m.length+1]; arraycopy(m, matches.m); matches.m[m.length] = joinSubList(toks, tokpat.size(), toks.size()); // for Matches.rest() } return true; } static boolean matchEndX(String pat, String s, Matches matches) { return matchEnd(dropPrefix("...", pat), s, matches); } static ArrayList cloneList(Iterable l) { return l instanceof Collection ? cloneList((Collection) l) : asList(l); } static ArrayList cloneList(Collection l) { if (l == null) return new ArrayList(); synchronized(collectionMutex(l)) { return new ArrayList(l); } } // supports the usual quotings (", variable length double brackets) except ' quoting static boolean isQuoted(String s) { if (isNormalQuoted(s)) return true; // use the exact version return isMultilineQuoted(s); } 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); // Octal escape? 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; // Hex Unicode: u???? 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; // added by Stefan } i++; } sb.append(ch); } return sb.toString(); } } return s; // not quoted - return original } static Map synchronizedMRUCache(int maxSize) { return synchroMap(new MRUCache(maxSize)); } static int defaultTokenizerCacheSize() { return 1000; } static List codeTokens(List tok) { return codeTokensOnly(tok); } static List wordTok(String s) { return javaTokNPunctuationWithBrackets_cached(s); } static A printStructure(String prefix, A o) { if (endsWithLetter(prefix)) prefix += ": "; print(prefix + structureForUser(o)); return o; } static A printStructure(A o) { print(structureForUser(o)); return o; } static String format3(String pat, Object... args) { if (args.length == 0) return pat; List tok = javaTokPlusPeriod(pat); int argidx = 0; for (int i = 1; i < tok.size(); i += 2) if (tok.get(i).equals("*")) tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null")); return join(tok); } static String format3_formatArg(Object arg) { if (arg == null) return "null"; if (arg instanceof String) { String s = (String) arg; return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s); } if (arg instanceof Integer || arg instanceof Long) return String.valueOf(arg); return quote(structure(arg)); } static Object callCreator(String functionName, Object... args) { return call(creator(), functionName, args); } 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); } static AutoCloseable dm_enter(Object mod) { return (AutoCloseable) callOpt(dm_getModule(mod), "enter"); } 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); // try varargs 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); // try varargs 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"); } } catch (Exception __e) { throw rethrow(__e); } } static void _close(AutoCloseable c) { if (c != null) try { c.close(); } catch (Throwable e) { // Some classes stupidly throw an exception on double-closing if (c instanceof javax.imageio.stream.ImageOutputStream) return; else throw rethrow(e); } } static void dm_reloadModuleInBackground(Object module) { dm_callOS("reloadModuleInBackground", dm_getStem(module)); } static void dm_reloadModuleInBackground() { dm_reloadModuleInBackground(dm_current_mandatory_generic()); } static String asString(Object o) { return o == null ? null : o.toString(); } static boolean matchX_vbar(String pat, String s) { return matchX_vbar(pat, s, null); } static boolean matchX_vbar(String pat, String s, Matches matches) { for (String pat2 : tok_splitAtVerticalBar(pat)) if (matchX(pat2, s, matches)) return true; return false; } static boolean mapPut_trueIfChanged(Map map, A key, B value) { if (map != null && key != null && value != null) if (eq(map.get(key), value)) return false; else { map.put(key, value); return true; } return false; } static List tok_splitAtVerticalBar(String s) { if (!contains(s, '|')) return ll(s); return splitAtTokens(javaTokPlusBrackets2(s), tok_splitAtVerticalBar_list); } static List tok_splitAtVerticalBar_list = ll("|"); static boolean flexMatchIC2_debug = false; static boolean flexMatchIC2(String pat, String s) { return flexMatchIC2(pat, s, null); } static boolean flexMatchIC2(String pat, String s, Matches m) { return flexMatchIC2(javaTok(pat), javaTok_cached(unnull(s)), m); } static boolean flexMatchIC2(String pat, String s, Matches m, boolean joinBrackets) { return flexMatchIC2(javaTok(pat), javaTok_cached(unnull(s)), m, joinBrackets); } static boolean flexMatchIC2(String pat, List tokfull, Matches m, boolean joinBrackets) { return flexMatchIC2(javaTok(pat), tokfull, m, joinBrackets); } static boolean flexMatchIC2(List tokpat, List tokfull, Matches m) { return flexMatchIC2(tokpat, tokfull, m, true); } static boolean flexMatchIC2(List tokpat, List tokfull, Matches m, boolean joinBrackets) { tokpat = codeTokens(joinBrackets ? joinBrackets(tokpat) : tokpat); for (int i = 0; i < l(tokpat); i++) if (eq(tokpat.get(i), "*")) tokpat.add(i++, "!*"); // insert single-token wildcard in front to avoid empty matches if (joinBrackets) tokfull = joinBrackets(tokfull); List tok = codeTokens(tokfull); BitSet bla = new BitSet(); BitSet bla2 = new BitSet(); if (!flexMatchIC2_impl(tokpat, 0, tok, 0, bla, bla2)) return false; if (m != null) { List l = new ArrayList(); for (int i = 1; i < l(tokfull); i += 2) { if (bla.get(i/2)) { int j = i; while (j < l(tokfull) && bla.get(j/2)) j += 2; l.add(join(subList(tokfull, i, j-1))); i = j-2; } else if (bla2.get(i/2)) l.add(tokfull.get(i)); } m.m = toStringArray(l); } return true; } static boolean flexMatchIC2_impl(List pat, int ipat, List tok, int itok, BitSet bla, BitSet bla2) { if (flexMatchIC2_debug) print("flexMatchIC2 pat=" + structure(subList(pat, ipat)) + " tok=" + structure(subList(tok, itok)) + " " + structure(bla)); if (ipat >= l(pat)) return itok >= l(tok); String t = pat.get(ipat); if (eq(t, "*")) { // the flex wildcard (0 or more tokens) if (flexMatchIC2_debug) print("Trying zero tokens"); if (flexMatchIC2_impl(pat, ipat+1, tok, itok, bla, bla2)) { if (flexMatchIC2_debug) print("Success!"); return true; } bla.set(itok); if (itok < l(tok)) { if (flexMatchIC2_debug) print("Trying one or more tokens"); if (flexMatchIC2_impl(pat, ipat, tok, itok+1, bla, bla2)) { if (flexMatchIC2_debug) print("Success!"); return true; // success, leave mark } } if (flexMatchIC2_debug) print("Failed * matching"); bla.clear(itok); // fail, undo marking return false; } if (itok >= l(tok)) { if (flexMatchIC2_debug) print("too much pattern"); return false; } if (eq(t, "!*")) { // the single-token wildcard bla.set(itok); if (flexMatchIC2_impl(pat, ipat+1, tok, itok+1, bla, bla2)) return true; // success, leave mark bla.clear(itok); // fail, undo marking return false; } String realt = tok.get(itok); if (t.startsWith("(") && t.endsWith(")")) { // quick pre-check if (flexMatchIC2_debug) print("flexMatchIC2 precheck " + t + " " + realt); if (!containsIgnoreCase(t, realt)) return false; // real check List list = splitAt(dropFirstAndLast(t), "|"); if (flexMatchIC2_debug) print("flexMatchIC2 real check " + struct(list)); if (!containsIgnoreCase(list, realt)) return false; bla2.set(itok); } else if (neqic(realt, t)) { if (flexMatchIC2_debug) print("mismatch"); return false; } // it is a token match. consume and proceed if (flexMatchIC2_impl(pat, ipat+1, tok, itok+1, bla, bla2)) return true; else { bla2.clear(itok); return false; } } static String replacePhrase(String s, String pattern, String replacement) { return cic(s, pattern) ? regexpReplaceIC_direct(s, "\\b" + regexpQuote(pattern) + "\\b", replacement) : s; } static boolean isTrue(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); if (o == null) return false; if (o instanceof ThreadLocal) // TODO: remove this return isTrue(((ThreadLocal) o).get()); throw fail(getClassName(o)); } static BufferedImage loadPNG(File file) { return loadBufferedImage(file); } static String toUpper(String s) { return s == null ? null : s.toUpperCase(); } static List toUpper(Collection s) { return allToUpper(s); } static int shorten_default = 100; static String shorten(CharSequence s) { return shorten(s, shorten_default); } static String shorten(CharSequence s, int max) { return shorten(s, max, "..."); } static String shorten(CharSequence s, int max, String shortener) { if (s == null) return ""; if (max < 0) return str(s); return s.length() <= max ? str(s) : subCharSequence(s, 0, min(s.length(), max-l(shortener))) + shortener; } static String shorten(int max, CharSequence s) { return shorten(s, max); } static AutoCloseable tempSetTL(ThreadLocal tl, A a) { return tempSetThreadLocal(tl, a); } // jsoup static String googleImageSearch_new_userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1"; static int googleImageSearch_new_timeout = 10*1000; static ThreadLocal googleImageSearch_new_nsfw = new ThreadLocal(); static BufferedImage googleImageSearch_new(String q) { String html = googleImageSearch_new_loadPage_cached(q); String group = regexpFirstGroup("image/jpeg;base64,([a-zA-Z0-9/+]*)={0,2}", html); return group == null ? null : imageFromBytes(base64decode(dropLast(l(group) & 3, group))); } static String googleImageSearch_new_loadPage_cached(String q) { File f = googleImageSearch_htmlCacheFile(q); if (fileSize(f) > 0) return loadTextFile(f); String html = str(googleImageSearch_new_loadPage(q)); saveTextFile(f, html); return html; } static Document googleImageSearch_new_loadPage(String q) { try { String googleUrl = "https://www.google.com/search?tbm=isch" + (!isTrue(googleImageSearch_new_nsfw.get()) ? "&safe=active" : "") + "&q=" + urlencode(q); print("Googling " + quote(q)); return Jsoup.connect(googleUrl).userAgent(googleImageSearch_new_userAgent).timeout(googleImageSearch_new_timeout).get(); } catch (Exception __e) { throw rethrow(__e); } } static void savePNG(BufferedImage img, File file) { try { File tempFile = new File(file.getPath() + "_temp"); CriticalAction ca = beginCriticalAction("Save " + f2s(file)); try { ImageIO.write(img, "png", mkdirsFor(tempFile)); file.delete(); tempFile.renameTo(file); } finally { ca.done(); } } catch (Exception __e) { throw rethrow(__e); } } // gotta love convenience & program-smartness static void savePNG(File file, BufferedImage img) { savePNG(img, file); } static void savePNG(File file, RGBImage img) { savePNG(file, img.getBufferedImage()); } static String fsI(String id) { return formatSnippetID(id); } static String fsI(long id) { return formatSnippetID(id); } static String urlencode(String x) { try { return URLEncoder.encode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } static void mapPut(Map map, A key, B value) { if (map != null && key != null && value != null) map.put(key, value); } static void mapPut(Map map, Pair p) { if (map != null && p != null) map.put(p.a, p.b); } // there are random upload errors... static int uploadToImageServerIfNotThere_tries = 3; static String uploadToImageServerIfNotThere(BufferedImage img, String name) { return uploadToImageServerIfNotThere(null, img, name); } static String uploadToImageServerIfNotThere(File f, BufferedImage img, String name) { String md5 = md5OfRGBImage(new RGBImage(img)); Throwable lastException = null; for (int tries = 0; tries < uploadToImageServerIfNotThere_tries; tries++) try { long id = imageServerCheckMD5(md5); if (id == 0) return uploadToImageServer_new(f, img, name); else return snippetImgLink(fsI(id)); } catch (Throwable e) { lastException = printException(e); } throw fail(lastException); } static String uploadToImageServerIfNotThere(File f) { return uploadToImageServerIfNotThere(f, loadImage2(f), fileName(f)); } static String uploadFileToImageServer(File f) { return uploadToImageServerIfNotThere(f, loadImage2(f), f.getName()); } static List> quickGoogle2_safeSearch(String query) { return quickGoogle2_safeSearch(query, null); } static List> quickGoogle2_safeSearch(String query, String language, Object... __) { return quickGoogle2(query, language, paramsPlus(__, "safeSearch" , true)); } static List> quickGoogle2(String query) { return quickGoogle2(query, null); } static List> quickGoogle2(String query, String language, Object... __) { boolean safeSearch = boolPar("safeSearch",__); boolean noCache = boolPar("noCache",__); boolean debug = boolPar("debug",__); if (safeSearch) noCache = true; language = or2(language, "lang_en"); query = trim(query); List> out = noCache ? null : lookupPossiblyIgnoringCase(parseGoogleLog(), query); if (out != null) { print("cache hit"); return out; } out = new ArrayList(); String userAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0"; loadPageWithUserAgent_verbose = true; String html = loadPageWithUserAgent("https://www.google.com/search?q=" + urlencode(query) + "&lr=" + language + "&hl=en" + (safeSearch ? "&safe=active" : ""), userAgent); String url = first(loadPage_responseHeaders.get().get("Location")); if (url != null) html = loadPageWithUserAgent(url, userAgent); saveTextFile(javaxCachesDir("last-google-result-page.html"), html); List htmlTok = htmlTok(html); List> h3s = findContainerTagDeep(htmlTok, "h3"); for (List tok : h3s) { int idx = magicIndexOfSubList(htmlTok, tok); String linkTag = get(htmlTok, idx-1); if (!tagIs(linkTag, "a")) { if (debug) print("linkTag", linkTag); continue; } String link = tagGet(linkTag, "href"); { if (!(isAbsoluteURL(link))) continue; } String text = htmldecode(join(dropTags(contentsOfContainerTag(tok)))); // TODO List sub = subList(htmlTok, idx+l(tok)-1); List> spans = findContainerTagWithParams(sub, "span", "class" , "st"); if (debug) pnl("l(sub)=" + l(sub) + ", spans: " + l(spans)); if (debug) pnl("spans", spans); String desc = trim(htmldecode(dropTags(join(first(spans))))); if (debug) printStruct("desc", desc); //S desc = ""; out.add(triple(link, text, desc)); } if (empty(out)) { saveTextFile(javaxCachesDir("buggy-google.html"), html); return out; } if (!noCache) logStructure(googleLog(), litorderedmap("query", query, "language", language, "date" , localDateWithSeconds(), "results" , out)); return out; } static List takeFirst(List l, int n) { return l(l) <= n ? l : newSubListOrSame(l, 0, n); } static List takeFirst(int n, List l) { return takeFirst(l, n); } static String takeFirst(int n, String s) { return substring(s, 0, n); } static String takeFirst(String s, int n) { return substring(s, 0, n); } static CharSequence takeFirst(int n, CharSequence s) { return subCharSequence(s, 0, n); } static List takeFirst(int n, Iterable i) { if (i == null) return null; List l = new ArrayList(); Iterator it = i.iterator(); for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) { if (it.hasNext()) l.add(it.next()); else break; } return l; } static int[] takeFirst(int n, int[] a) { return takeFirstOfIntArray(n, a); } static String unicode_smallBlackSquare() { return "\u25AA"; } static List synchroList() { return Collections.synchronizedList(new ArrayList()); } static List synchroList(List l) { return Collections.synchronizedList(l); } static List ll(A... a) { ArrayList l = new ArrayList(a.length); if (a != null) for (A x : a) l.add(x); return l; } static PersistableThrowable persistableThrowable(Throwable e) { return e == null ? null : new PersistableThrowable(e); } static Throwable innerException(Throwable e) { return getInnerException(e); } static String dropSuffix(String suffix, String s) { return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s; } static boolean structure_showTiming, structure_checkTokenCount; static String structure(Object o) { return structure(o, new structure_Data()); } static String structure(Object o, structure_Data d) { StringWriter sw = new StringWriter(); d.out = new PrintWriter(sw); structure_go(o, d); String s = str(sw); if (structure_checkTokenCount) { print("token count=" + d.n); assertEquals("token count", l(javaTokC(s)), d.n); } return s; } static void structure_go(Object o, structure_Data d) { structure_1(o, d); while (nempty(d.stack)) popLast(d.stack).run(); } static void structureToPrintWriter(Object o, PrintWriter out) { structure_Data d = new structure_Data(); d.out = out; structure_go(o, d); } // leave to false, unless unstructure() breaks static boolean structure_allowShortening = false; // info on how to serialize objects of a certain class static class structure_ClassInfo { List fields; Method customSerializer; boolean special, nullInstances; } static class structure_Data { PrintWriter out; int stringSizeLimit; int shareStringsLongerThan = 20; boolean noStringSharing = false; IdentityHashMap seen = new IdentityHashMap(); //new BitSet refd; HashMap strings = new HashMap(); HashSet concepts = new HashSet(); HashMap infoByClass = new HashMap(); HashMap persistenceInfo = new HashMap(); int n; // token count List stack = new ArrayList(); // append single token structure_Data append(String token) { out.print(token); ++n; return this; } structure_Data append(int i) { out.print(i); ++n; return this; } // append multiple tokens structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; } // extend last token structure_Data app(String token) { out.print(token); return this; } structure_Data app(int i) { out.print(i); return this; } } static void structure_1(final Object o, final structure_Data d) { try { if (o == null) { d.append("null"); return; } Class c = o.getClass(); boolean concept = false; structure_ClassInfo info = d.infoByClass.get(c); if (info == null) { d.infoByClass.put(c, info = new structure_ClassInfo()); if ((info.customSerializer = findMethodNamed(c, "_serialize")) != null) info.special = true; } List lFields = info.fields; if (lFields == null) { // these are never back-referenced (for readability) if (o instanceof Number) { PrintWriter out = d.out; if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; } if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; } if (o instanceof Short) { short s = ((Short) o).shortValue(); d.append("sh "); out.print(s); d.n += s < 0 ? 2 : 1; return; } if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; } if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; } if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; } } if (o instanceof Boolean) { d.append(((Boolean) o).booleanValue() ? "t" : "f"); return; } if (o instanceof Character) { d.append(quoteCharacter((Character) o)); return; } if (o instanceof File) { d.append("File ").append(quote(((File) o).getPath())); return; } // referencable objects follow Integer ref = d.seen.get(o); if (o instanceof String && ref == null) ref = d.strings.get((String) o); if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; } if (!(o instanceof String)) d.seen.put(o, d.n); // record token number else { String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o; if (!d.noStringSharing) { if (d.shareStringsLongerThan == Integer.MAX_VALUE) d.seen.put(o, d.n); if (l(s) >= d.shareStringsLongerThan) d.strings.put(s, d.n); } quoteToPrintWriter(s, d.out); d.n++; return; } if (o instanceof Set) { /*O set2 = unwrapSynchronizedSet(o); if (set2 != o) { d.append("sync"); o = set2; } TODO */ if (((Set) o) instanceof TreeSet) { d.append(isCISet_gen(((Set) o)) ? "ciset" : "treeset"); structure_1(new ArrayList(((Set) o)), d); return; } // assume it's a HashSet or LinkedHashSet d.append(((Set) o) instanceof LinkedHashSet ? "lhs" : "hashset"); structure_1(new ArrayList(((Set) o)), d); return; } String name = c.getName(); if (o instanceof Collection && !startsWith(name, "main$") /* && neq(name, "main$Concept$RefL") */) { // it's a list if (name.equals("java.util.Collections$SynchronizedList") || name.equals("java.util.Collections$SynchronizedRandomAccessList")) { d.append("sync "); { structure_1(unwrapSynchronizedList(((List) o)), d); return; } } else if (name.equals("java.util.LinkedList")) d.append("ll"); d.append("["); final int l = d.n; final Iterator it = ((Collection) o).iterator(); d.stack.add(new Runnable() { public void run() { try { if (!it.hasNext()) d.append("]"); else { d.stack.add(this); if (d.n != l) d.append(", "); structure_1(it.next(), d); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.sta..."; }}); return; } if (o instanceof Map && !startsWith(name, "main$")) { if (o instanceof LinkedHashMap) d.append("lhm"); else if (o instanceof HashMap) d.append("hm"); else if (o instanceof TreeMap) d.append(isCIMap_gen(((TreeMap) o)) ? "cimap" : "tm"); else if (name.equals("java.util.Collections$SynchronizedMap") || name.equals("java.util.Collections$SynchronizedSortedMap") || name.equals("java.util.Collections$SynchronizedNavigableMap")) { d.append("sync "); { structure_1(unwrapSynchronizedMap(((Map) o)), d); return; } } d.append("{"); final int l = d.n; final Iterator it = ((Map) o).entrySet().iterator(); d.stack.add(new Runnable() { boolean v = false; Map.Entry e; public void run() { if (v) { d.append("="); v = false; d.stack.add(this); structure_1(e.getValue(), d); } else { if (!it.hasNext()) d.append("}"); else { e = (Map.Entry) it.next(); v = true; d.stack.add(this); if (d.n != l) d.append(", "); structure_1(e.getKey(), d); } } } }); return; } if (c.isArray()) { if (o instanceof byte[]) { d.append("ba ").append(quote(bytesToHex((byte[]) o))); return; } final int n = Array.getLength(o); if (o instanceof boolean[]) { String hex = boolArrayToHex((boolean[]) o); int i = l(hex); while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2; d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return; } String atype = "array"/*, sep = ", "*/; // sep is not used yet if (o instanceof int[]) { //ret "intarray " + quote(intArrayToHex((int[]) o)); atype = "intarray"; //sep = " "; } else if (o instanceof double[]) { atype = "dblarray"; //sep = " "; } d.append(atype).append("{"); d.stack.add(new Runnable() { int i; public void run() { if (i >= n) d.append("}"); else { d.stack.add(this); if (i > 0) d.append(", "); structure_1(Array.get(o, i++), d); } } }); return; } if (o instanceof Class) { d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return; } if (o instanceof Throwable) { d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return; } if (o instanceof BitSet) { BitSet bs = (BitSet) o; d.append("bitset{", 2); int l = d.n; for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { if (d.n != l) d.append(", "); d.append(i); } d.append("}"); return; } // Need more cases? This should cover all library classes... if (name.startsWith("java.") || name.startsWith("javax.")) { d.append("j ").append(quote(str(o))); return; // Hm. this is not unstructure-able } /*if (name.equals("main$Lisp")) { fail("lisp not supported right now"); }*/ if (info.special) { if (info.customSerializer != null) { // custom serialization (_serialize method) Object o2 = invokeMethod(info.customSerializer, o); d.append("cu "); String shortName = dropPrefix("main$", name); d.append(shortName); d.out.append(' '); structure_1(o2, d); return; } else if (info.nullInstances) { d.append("null"); return; } else throw fail("unknown special type"); } String dynName = shortDynamicClassName(o); if (concept && !d.concepts.contains(dynName)) { d.concepts.add(dynName); d.append("c "); } // serialize an object with fields. // first, collect all fields and values in fv. TreeSet fields = new TreeSet(new Comparator() { public int compare(Field a, Field b) { return stdcompare(a.getName(), b.getName()); } }); Class cc = c; while (cc != Object.class) { for (Field field : getDeclaredFields_cached(cc)) { String fieldName = field.getName(); if (fieldName.equals("_persistenceInfo")) d.persistenceInfo.put(c, field); if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0) continue; fields.add(field); // put special cases here...? } cc = cc.getSuperclass(); } // TODO: S fieldOrder = getOpt(c, "_fieldOrder"); lFields = asList(fields); // Render this$1 first because unstructure needs it for constructor call. int n = l(lFields); for (int i = 0; i < n; i++) { Field f = lFields.get(i); if (f.getName().equals("this$1")) { lFields.remove(i); lFields.add(0, f); break; } } info.fields = lFields; } // << if (lFields == null) else { // ref handling for lFields != null Integer ref = d.seen.get(o); if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; } d.seen.put(o, d.n); // record token number } Field persistenceInfoField = (Field) (d.persistenceInfo.get(c)); Map persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o); LinkedHashMap fv = new LinkedHashMap(); for (Field f : lFields) { Object value; try { value = f.get(o); } catch (Exception e) { value = "?"; } if (value != null && (persistenceInfo == null || !Boolean.FALSE.equals(persistenceInfo.get(f.getName())))) fv.put(f.getName(), value); } String name = c.getName(); String shortName = dropPrefix("main$", name); if (startsWithDigit(shortName)) shortName = name; // for anonymous classes // Now we have fields & values. Process fieldValues if it's a DynamicObject. // omit field "className" if equal to class's name if (concept && eq(fv.get("className"), shortName)) fv.remove("className"); if (o instanceof DynamicObject) { putAll(fv, (Map) fv.get("fieldValues")); fv.remove("fieldValues"); shortName = shortDynamicClassName(o); fv.remove("className"); } String singleField = fv.size() == 1 ? first(fv.keySet()) : null; d.append(shortName); d.n += countDots(shortName)*2; // correct token count final int l = d.n; final Iterator it = fv.entrySet().iterator(); d.stack.add(new Runnable() { public void run() { try { if (!it.hasNext()) { if (d.n != l) d.append(")"); } else { Map.Entry e = (Map.Entry) it.next(); d.append(d.n == l ? "(" : ", "); d.append((String) e.getKey()).append("="); d.stack.add(this); structure_1(e.getValue(), d); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else..."; }}); } catch (Exception __e) { throw rethrow(__e); } } static Class getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } static Class getClass(Object o) { return o instanceof Class ? (Class) o : o.getClass(); } static Class getClass(Object realm, String name) { try { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } catch (Exception __e) { throw rethrow(__e); } } static String classNameToVM(String name) { return name.replace(".", "$"); } static String formatWithThousands(long l) { return formatWithThousandsSeparator(l); } static double fraction(double d) { return d % 1; } static String n_fancy2(long l, String singular, String plural) { return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural); } static String n_fancy2(Collection l, String singular, String plural) { return n_fancy2(l(l), singular, plural); } static String n_fancy2(Map m, String singular, String plural) { return n_fancy2(l(m), singular, plural); } static String n_fancy2(Object[] a, String singular, String plural) { return n_fancy2(l(a), singular, plural); } static A oneOf(List l) { return empty(l) ? null : l.get(new Random().nextInt(l.size())); } static char oneOf(String s) { return empty(s) ? '?' : s.charAt(random(l(s))); } static String oneOf(String... l) { return oneOf(asList(l)); } static A collectionGet(Collection c, int idx) { if (c == null || idx < 0 || idx >= l(c)) return null; if (c instanceof List) return listGet((List) c, idx); Iterator it = c.iterator(); for (int i = 0; i < idx; i++) if (it.hasNext()) it.next(); else return null; return it.hasNext() ? it.next() : null; } static List magicQuoteInputForThisProgram_matchers; static List magicQuoteInputForThisProgram(String input, Object... __) { Collection inputs = magicQuotes(input); // all quoted variants if (magicQuoteInputForThisProgram_matchers == null) magicQuoteInputForThisProgram_matchers = matchingPatternsInJavaXSource_withFunctions( boolPar("useTranspiled",__) ? getServerTranspiledWithoutLibs(programID()) : programID()); return filter(inputs, i -> matchedByAnyFunctionNameAndPattern(magicQuoteInputForThisProgram_matchers, i)); // filter quoted inputs that match } static boolean containsIgnoreCase(Collection l, String s) { if (l != null) for (String x : l) if (eqic(x, s)) return true; return false; } static boolean containsIgnoreCase(String[] l, String s) { if (l != null) for (String x : l) if (eqic(x, s)) return true; return false; } static boolean containsIgnoreCase(String s, char c) { return indexOfIgnoreCase(s, String.valueOf(c)) >= 0; } static boolean containsIgnoreCase(String a, String b) { return indexOfIgnoreCase(a, b) >= 0; } static Object rcall(String method, Object o, Object... args) { return call_withVarargs(o, method, args); } static String rcall_string(String method, Object o, Object... args) { return (String) rcall(method, o, args); } static String getName() { return getProgramName(); } static String patternQuote(String s) { return s.length() == 0 ? "" : Pattern.quote(s); } static String quoteReplacement(String s) { return Matcher.quoteReplacement(s); } 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; } static long parseLong(String s) { if (empty(s)) return 0; return Long.parseLong(dropSuffix("L", s)); } static long parseLong(Object s) { return Long.parseLong((String) s); } static Map> parse3_cachedInput_cache = synchronizedMRUCache(1000); static List parse3_cachedInput(String s) { List tok = parse3_cachedInput_cache.get(s); if (tok == null) parse3_cachedInput_cache.put(s, tok = parse3(s)); return tok; } static Map> parse3_cachedPattern_cache = synchronizedMRUCache(1000); static synchronized List parse3_cachedPattern(String s) { List tok = parse3_cachedPattern_cache.get(s); if (tok == null) parse3_cachedPattern_cache.put(s, tok = parse3(s)); return tok; } // We dropped the "***" support here (use match3 for that) static String[] find2(List pat, List tok) { for (int idx = 0; idx < tok.size(); idx += 2) { // TODO: subtract pat size from end index String[] result = find2(pat, tok, idx); if (result != null) return result; } return null; } static String[] find2(List pat, List tok, int idx) { if (idx+pat.size() > tok.size()) return null; List result = new ArrayList(); for (int i = 1; i < pat.size(); i += 2) { String p = pat.get(i), t = tok.get(idx+i); if (eq(p, "*")) result.add(t); else if (!p.equalsIgnoreCase(t)) return null; } return toStringArray(result); } static String unnull(String s) { return s == null ? "" : s; } static Collection unnull(Collection l) { return l == null ? emptyList() : l; } static List unnull(List l) { return l == null ? emptyList() : l; } static int[] unnull(int[] l) { return l == null ? emptyIntArray() : l; } static char[] unnull(char[] l) { return l == null ? emptyCharArray() : l; } static Map unnull(Map l) { return l == null ? emptyMap() : l; } static Iterable unnull(Iterable i) { return i == null ? emptyList() : i; } static A[] unnull(A[] a) { return a == null ? (A[]) emptyObjectArray() : a; } static BitSet unnull(BitSet b) { return b == null ? new BitSet() : b; } static Pt unnull(Pt p) { return p == null ? new Pt() : p; } //ifclass Symbol static Pair unnull(Pair p) { return p != null ? p : new Pair(null, null); } static Collection values(Map map) { return map == null ? emptyList() : map.values(); } // convenience shortcut for values_gen static Collection values(Object map) { return values((Map) map); } static Collection values(MultiMap mm) { return mm == null ? emptyList() : concatLists(values(mm.data)); } static String textOut_and(Collection l) { return textOut_and(l, "nothing"); } static String textOut_and(Collection l, String emptyText) { if (empty(l)) return emptyText; List separators = rep(", ", l(l)-2); separators.add(" and "); return join_flex(separators, l); } // TODO: extended multi-line strings static int javaTok_n, javaTok_elements; static boolean javaTok_opt = false; 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; // scan for whitespace 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); // scan for non-whitespace // Special JavaX syntax: 'identifier 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 == '\'') { // allow multi-line strings, but not for ' ++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) == '\'')); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } 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; } static List javaTok(List tok) { return javaTokWithExisting(join(tok), tok); } static boolean containsNewLine(String s) { return contains(s, '\n'); // screw \r, nobody needs it } static void addIfNempty(Collection l, String s) { if (nempty(s)) l.add(s); } static void addIfNempty(Collection l, Map m) { if (nempty(m)) l.add(m); } static void addIfNempty(Collection l, Collection c) { if (nempty(c)) l.add(c); } static String trimJoinSubList(List l, int i, int j) { return trim(join(subList(l, i, j))); } static String trimJoinSubList(List l, int i) { return trim(join(subList(l, i))); } static ThreadLocal print_byThread() { synchronized(print_byThread_lock) { if (print_byThread == null) print_byThread = new ThreadLocal(); } return print_byThread; } // f can return false to suppress regular printing // call print_raw within f to actually print something static AutoCloseable tempInterceptPrint(F1 f) { return tempSetThreadLocal(print_byThread(), f); } static String getStackTrace2(Throwable e) { return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n"); } static A or(A a, A b) { return a != null ? a : b; } static Map newDangerousWeakHashMap() { return _registerDangerousWeakMap(synchroMap(new WeakHashMap())); } // initFunction: voidfunc(Map) - is called initially, and after clearing the map static Map newDangerousWeakHashMap(Object initFunction) { return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction); } static Object callMCWithVarArgs(String method, Object... args) { return call_withVarargs(mc(), method, args); } static String getClassName(Object o) { return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName(); } static Object invokeMethod(Method m, Object o, Object... args) { try { try { return m.invoke(o, args); } catch (InvocationTargetException e) { throw rethrow(getExceptionCause(e)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args))); } } catch (Exception __e) { throw rethrow(__e); } } static boolean call_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != args.length) { if (debug) print("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) { Object arg = args[i]; if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) { if (debug) print("Bad parameter " + i + ": " + arg + " vs " + types[i]); return false; } } return true; } static Field makeAccessible(Field f) { try { f.setAccessible(true); } catch (Throwable e) { // Note: The error reporting only works with Java VM option --illegal-access=deny vmBus_send("makeAccessible_error",e, f); } return f; } static Method makeAccessible(Method m) { try { m.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error",e, m); } return m; } static Constructor makeAccessible(Constructor c) { try { c.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error",e, c); } return c; } static int indexOf(List l, A a, int startIndex) { if (l == null) return -1; int n = l(l); for (int i = startIndex; i < n; i++) if (eq(l.get(i), a)) return i; return -1; } static int indexOf(List l, int startIndex, A a) { return indexOf(l, a, startIndex); } static int indexOf(List l, A a) { if (l == null) return -1; return l.indexOf(a); } static int indexOf(String a, String b) { return a == null || b == null ? -1 : a.indexOf(b); } static int indexOf(String a, String b, int i) { return a == null || b == null ? -1 : a.indexOf(b, i); } static int indexOf(String a, char b) { return a == null ? -1 : a.indexOf(b); } static int indexOf(String a, int i, char b) { return indexOf(a, b, i); } static int indexOf(String a, char b, int i) { return a == null ? -1 : a.indexOf(b, i); } static int indexOf(String a, int i, String b) { return a == null || b == null ? -1 : a.indexOf(b, i); } static int indexOf(A[] x, A a) { int n = l(x); for (int i = 0; i < n; i++) if (eq(x[i], a)) return i; return -1; } 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); } } 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); } } static String makeRandomID(int length) { return makeRandomID(length, defaultRandomGenerator()); } 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); } static String makeRandomID(Random r, int length) { return makeRandomID(length, r); } static Object callOpt_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.findMethod(method, args); if (me == null) { // TODO: varargs return null; } if ((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(method, args); if (me != null) return invokeMethod(me, o, args); // try varargs 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); } return null; } } catch (Exception __e) { throw rethrow(__e); } } static Class mc() { return main.class; } static Class javax() { return getJavaX(); } static RuntimeException asRuntimeException(Throwable t) { if (t instanceof Error) _handleError((Error) t); return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } static CloseableIterableIterator linesFromFile(File f) { try { if (!f.exists()) return emptyCloseableIterableIterator(); if (ewic(f.getName(), ".gz")) return linesFromReader(utf8bufferedReader(newGZIPInputStream(f))); return linesFromReader(utf8bufferedReader(f)); } catch (Exception __e) { throw rethrow(__e); } } static CloseableIterableIterator linesFromFile(String path) { return linesFromFile(newFile(path)); } static Map newWeakHashMap() { return _registerWeakMap(synchroMap(new WeakHashMap())); } // TODO: test if android complains about this static boolean isAWTThread() { if (isAndroid()) return false; if (isHeadless()) return false; return isAWTThread_awt(); } static boolean isAWTThread_awt() { return SwingUtilities.isEventDispatchThread(); } static void failIfUnlicensed() { assertTrue("license off", licensed()); } static Thread currentThread() { return Thread.currentThread(); } static String getStackTrace(Throwable throwable) { lastException(throwable); return getStackTrace_noRecord(throwable); } static String getStackTrace_noRecord(Throwable throwable) { StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); return hideCredentials(writer.toString()); } static String getStackTrace() { return getStackTrace_noRecord(new Throwable()); } // f : Matcher -> S static String regexpReplaceIC(String s, String pat, Object f) { return regexReplaceIC(s, pat, f); } static String regexpReplaceIC(String s, String pat, IF1 f) { return regexReplaceIC(s, pat, f); } static boolean boolOptParam(ThreadLocal tl) { return isTrue(optPar(tl)); } // defaults to false static boolean boolOptParam(Object[] __, String name) { return isTrue(optParam(__, name)); } static boolean boolOptParam(String name, Object[] __) { return boolOptParam(__, name); } static boolean boolOptParam(String name, Map __) { return isTrue(optPar(name, __)); } static B mapGet(Map map, A a) { return map == null || a == null ? null : map.get(a); } static B mapGet(A a, Map map) { return map == null || a == null ? null : map.get(a); } static boolean even(int i) { return (i & 1) == 0; } static boolean even(long i) { return (i & 1) == 0; } static String f2s(File f) { return f == null ? null : f.getAbsolutePath(); } static String f2s(String s) { return f2s(newFile(s)); } static String f2s(java.nio.file.Path p) { return p == null ? null : f2s(p.toFile()); } static File getCacheProgramDir() { return getCacheProgramDir(getProgramID()); } static File getCacheProgramDir(String snippetID) { return new File(userHome(), "JavaX-Caches/" + formatSnippetIDOpt(snippetID)); } static String programID; static String getProgramID() { return nempty(programID) ? formatSnippetIDOpt(programID) : "?"; } // TODO: ask JavaX instead static String getProgramID(Class c) { String id = (String) getOpt(c, "programID"); if (nempty(id)) return formatSnippetID(id); return "?"; } static String getProgramID(Object o) { return getProgramID(getMainClass(o)); } static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) { return a != null && a.regionMatches(true, offsetA, b, offsetB, len); } static int strL(String s) { return s == null ? 0 : s.length(); } static Map compileRegexpIC_cache = syncMRUCache(10); static java.util.regex.Pattern compileRegexpIC(String pat) { java.util.regex.Pattern p = compileRegexpIC_cache.get(pat); if (p == null) { try { compileRegexpIC_cache.put(pat, p = java.util.regex.Pattern.compile(pat, Pattern.CASE_INSENSITIVE)); } catch (PatternSyntaxException e) { throw rethrow(wrapPatternSyntaxException(e)); } } return p; } static Matcher regexpMatcher(String pat, String s) { return compileRegexp(pat).matcher(unnull(s)); } static Field getOpt_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static Iterator emptyIterator() { return Collections.emptyIterator(); } //static final Map> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init); static class getOpt_Map extends WeakHashMap { getOpt_Map() { if (getOpt_special == null) getOpt_special = new HashMap(); clear(); } public void clear() { super.clear(); //print("getOpt clear"); put(Class.class, getOpt_special); put(String.class, getOpt_special); } } static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map())); //static final Map> getOpt_cache = _registerWeakMap(synchroMap(new getOpt_Map)); static HashMap getOpt_special; // just a marker /*static void getOpt_special_init(Map map) { map.put(Class.class, getOpt_special); map.put(S.class, getOpt_special); }*/ static Object getOpt_cached(Object o, String field) { try { if (o == null) return null; Class c = o.getClass(); HashMap map; synchronized(getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } if (map == getOpt_special) { if (o instanceof Class) return getOpt((Class) o, field); /*if (o instanceof S) ret getOpt(getBot((S) o), field);*/ if (o instanceof Map) return ((Map) o).get(field); } Field f = map.get(field); if (f != null) return f.get(o); if (o instanceof DynamicObject) return mapGet2(((DynamicObject) o).fieldValues, field); return null; } catch (Exception __e) { throw rethrow(__e); } } // used internally - we are in synchronized block static HashMap getOpt_makeCache(Class c) { HashMap map; if (isSubtypeOf(c, Map.class)) map = getOpt_special; else { map = new HashMap(); if (!reflection_classesNotToScan().contains(c.getName())) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) { makeAccessible(f); String name = f.getName(); if (!map.containsKey(name)) map.put(name, f); } _c = _c.getSuperclass(); } while (_c != null); } } if (getOpt_cache != null) getOpt_cache.put(c, map); return map; } // match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens) static String[] match2(List pat, List tok) { // standard case (no ...) int i = pat.indexOf("..."); if (i < 0) return match2_match(pat, tok); pat = new ArrayList(pat); // We're modifying it, so copy first pat.set(i, "*"); while (pat.size() < tok.size()) { pat.add(i, "*"); pat.add(i+1, ""); // doesn't matter } return match2_match(pat, tok); } static String[] match2_match(List pat, List tok) { List result = new ArrayList(); if (pat.size() != tok.size()) { return null; } for (int i = 1; i < pat.size(); i += 2) { String p = pat.get(i), t = tok.get(i); if (eq(p, "*")) result.add(t); else if (!equalsIgnoreCase(unquote(p), unquote(t))) // bold change - match quoted and unquoted now. TODO: should remove return null; } return result.toArray(new String[result.size()]); } static boolean checkFieldsIC(Object x, Object... data) { for (int i = 0; i < l(data); i += 2) if (!eqicOrEq(getOpt(x, (String) data[i]), data[i+1])) return false; return true; } static int max(int a, int b) { return Math.max(a, b); } static int max(int a, int b, int c) { return max(max(a, b), c); } static long max(int a, long b) { return Math.max((long) a, b); } static long max(long a, long b) { return Math.max(a, b); } static double max(int a, double b) { return Math.max((double) a, b); } static float max(float a, float b) { return Math.max(a, b); } static double max(double a, double b) { return Math.max(a, b); } static int max(Collection c) { int x = Integer.MIN_VALUE; for (int i : c) x = max(x, i); return x; } static double max(double[] c) { if (c.length == 0) return Double.MIN_VALUE; double x = c[0]; for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]); return x; } static float max(float[] c) { if (c.length == 0) return Float.MAX_VALUE; float x = c[0]; for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]); return x; } static byte max(byte[] c) { byte x = -128; for (byte d : c) if (d > x) x = d; return x; } static short max(short[] c) { short x = -0x8000; for (short d : c) if (d > x) x = d; return x; } static int max(int[] c) { int x = Integer.MIN_VALUE; for (int d : c) if (d > x) x = d; return x; } static boolean checkFields(Object x, Object... data) { for (int i = 0; i < l(data); i += 2) if (neq(getOpt(x, (String) data[i]), data[i+1])) return false; return true; } static String getCanonicalPath(File f) { try { return f == null ? null : f.getCanonicalPath(); } catch (Exception __e) { throw rethrow(__e); } } static String getCanonicalPath(String path) { return getCanonicalPath(newFile(path)); } static FileOutputStream newFileOutputStream(File path) throws IOException { return newFileOutputStream(path.getPath()); } static FileOutputStream newFileOutputStream(String path) throws IOException { return newFileOutputStream(path, false); } static FileOutputStream newFileOutputStream(File path, boolean append) throws IOException { return newFileOutputStream(path.getPath(), append); } static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException { mkdirsForFile(path); FileOutputStream f = new FileOutputStream(path, append); _registerIO(f, path, true); return f; } static AutoCloseable tempCleaningUp() { return tempSetTL(ping_isCleanUpThread, true); } static void closeAllWriters(Collection l) { for (Writer w : unnull(l)) { try { w.close(); } catch (Throwable __e) { _handleException(__e); }} } static File getProgramFile(String progID, String fileName) { if (new File(fileName).isAbsolute()) return new File(fileName); return new File(getProgramDir(progID), fileName); } static File getProgramFile(String fileName) { return getProgramFile(getProgramID(), fileName); } static char lastChar(String s) { return empty(s) ? '\0' : s.charAt(l(s)-1); } static A[] dropLast(A[] a) { return dropLast(a, 1); } static A[] dropLast(A[] a, int n) { if (a == null) return null; n = Math.min(n, a.length); A[] b = arrayOfSameType(a, a.length-n); System.arraycopy(a, 0, b, 0, b.length); return b; } static List dropLast(List l) { return subList(l, 0, l(l)-1); } static List dropLast(int n, List l) { return subList(l, 0, l(l)-n); } static List dropLast(Iterable l) { return dropLast(asList(l)); } static String dropLast(String s) { return substring(s, 0, l(s)-1); } static String dropLast(String s, int n) { return substring(s, 0, l(s)-n); } static String dropLast(int n, String s) { return dropLast(s, n); } static String dropSuffixAndTrim(String suffix, String s) { return trim(dropSuffix(suffix, s)); } static boolean nemptyString(String s) { return s != null && s.length() > 0; } static int listL(Collection l) { return l == null ? 0 : l.size(); } static String dropPrefix(String prefix, String s) { return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s; } static void arraycopy(Object[] a, Object[] b) { if (a != null && b != null) arraycopy(a, 0, b, 0, Math.min(a.length, b.length)); } static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) { if (n != 0) System.arraycopy(src, srcPos, dest, destPos, n); } static String joinSubList(List l, int i, int j) { return join(subList(l, i, j)); } static String joinSubList(List l, int i) { return join(subList(l, i)); } static String joinSubList(List l, IntRange r) { return r == null ? null : joinSubList(l, r.start, r.end); } static boolean matchEnd(String pat, String s) { return matchEnd(pat, s, null); } // matches are as you expect, plus an extra item for the rest string static boolean matchEnd(String pat, String s, Matches matches) { if (s == null) return false; List tokpat = parse3(pat), toks = parse3(s); if (toks.size() < tokpat.size()) return false; String[] m = match2(tokpat, takeLast(l(tokpat), toks)); if (m == null) return false; if (matches != null) { matches.m = new String[m.length+1]; arraycopy(m, matches.m); matches.m[m.length] = join(dropLast(l(tokpat), toks)); // for Matches.rest() } return true; } static Object collectionMutex(List l) { return l; } 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; } 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; } 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) == '['; } static Map synchroMap() { return synchroHashMap(); } static Map synchroMap(Map map) { return Collections.synchronizedMap(map); } static List codeTokensOnly(List tok) { int n = tok.size(); List l = emptyList(n/2); for (int i = 1; i < n; i += 2) l.add(tok.get(i)); return l; } static Map> javaTokNPunctuationWithBrackets_cached_cache = synchronizedMRUCache(defaultTokenizerCacheSize()); static List javaTokNPunctuationWithBrackets_cached(String s) { List tok = javaTokNPunctuationWithBrackets_cached_cache.get(s); if (tok == null) javaTokNPunctuationWithBrackets_cached_cache.put(s, tok = javaTokNPunctuationWithBrackets(s)); return tok; } static boolean endsWithLetter(String s) { return nempty(s) && isLetter(last(s)); } static String structureForUser(Object o) { return beautifyStructure(struct_noStringSharing(o)); } // This is made for NL parsing. // It's javaTok extended with "..." token, "$n" and "#n" and // special quotes (which are converted to normal ones). static List javaTokPlusPeriod(String s) { List tok = new ArrayList(); if (s == null) return tok; int l = s.length(); int i = 0; while (i < l) { int j = i; char c; String cc; // scan for whitespace while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j+2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/")); j = Math.min(j+2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); cc = s.substring(i, Math.min(i+2, l)); // scan for non-whitespace if (c == (char) 0x201C || c == (char) 0x201D) c = '"'; // normalize quotes if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { char _c = s.charAt(j); if (_c == (char) 0x201C || _c == (char) 0x201D) _c = '"'; // normalize quotes if (_c == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j+1 < l) j += 2; else ++j; } if (j-1 >= i+1) { tok.add(opener + s.substring(i+1, j-1) + opener); i = j; continue; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for things like "this one's" else if (Character.isDigit(c)) do ++j; while (j < l && Character.isDigit(s.charAt(j))); else if (cc.equals("[[")) { do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]")); j = Math.min(j+2, l); } else if (cc.equals("[=") && i+2 < l && s.charAt(i+2) == '[') { do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]")); j = Math.min(j+3, l); } else if (s.substring(j, Math.min(j+3, l)).equals("...")) j += 3; else if (c == '$' || c == '#') do ++j; while (j < l && Character.isDigit(s.charAt(j))); else ++j; tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static boolean isIdentifier(String s) { return isJavaIdentifier(s); } static boolean isNonNegativeInteger(String s) { int n = l(s); if (n == 0) return false; int i = 0; while (i < n) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } static String quote(Object o) { if (o == null) return "null"; return quote(str(o)); } static String quote(String s) { if (s == null) return "null"; StringBuilder out = new StringBuilder((int) (l(s)*1.5+2)); quote_impl(s, out); return out.toString(); } static void quote_impl(String s, StringBuilder out) { out.append('"'); int l = s.length(); for (int i = 0; i < l; i++) { char c = s.charAt(i); if (c == '\\' || c == '"') out.append('\\').append(c); else if (c == '\r') out.append("\\r"); else if (c == '\n') out.append("\\n"); else if (c == '\t') out.append("\\t"); else if (c == '\0') out.append("\\0"); else out.append(c); } out.append('"'); } static WeakReference creator_class; static Object creator() { return creator_class == null ? null : creator_class.get(); } static boolean isString(Object o) { return o instanceof String; } static Object dm_getService(String serviceName) { return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName))); } static boolean isStringOrIntOrLong(Object o) { return o instanceof String || o instanceof Integer || o instanceof Long; } static Object dm_callOS(String functionName, Object... args) { return call(dm_os(), functionName, args); } static Object dm_resolveModule(Object moduleOrStem) { return dm_callOS("resolveModule", moduleOrStem); } static final Map callOpt_cache = newDangerousWeakHashMap(); static Object callOpt_cached(Object o, String methodName, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); // TODO: (super-rare) case where method exists static and non-static // with different args Method me = cache.findMethod(methodName, args); if (me == null || (me.getModifiers() & Modifier.STATIC) == 0) return null; return invokeMethod(me, null, args); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me == null) return null; return invokeMethod(me, o, args); } } catch (Exception __e) { throw rethrow(__e); } } static _MethodCache callOpt_getCache(Class c) { synchronized(callOpt_cache) { _MethodCache cache = callOpt_cache.get(c); if (cache == null) callOpt_cache.put(c, cache = new _MethodCache(c)); return cache; } } static boolean isStaticMethod(Method m) { return methodIsStatic(m); } 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; } static String joinWithComma(Collection c) { return join(", ", c); } static String joinWithComma(String... c) { return join(", ", c); } static String joinWithComma(Pair p) { return p == null ? "" : joinWithComma(str(p.a), str(p.b)); } static List classNames(Collection l) { return getClassNames(l); } static List classNames(Object[] l) { return getClassNames(Arrays.asList(l)); } static Object dm_getStem(Object moduleOrID) { if (isString(moduleOrID) && isIdentifier(((String) moduleOrID))) moduleOrID = dm_getService(((String) moduleOrID)); if (isStringOrIntOrLong(moduleOrID)) return dm_getStemByID(moduleOrID); return or(getOpt(dm_getModule(moduleOrID), "_host"), moduleOrID); } static Object dm_current_mandatory_generic() { return assertNotNull("No module set", dm_current_generic()); } static List splitAtTokens(String s, List tokens) { return splitAtTokens(javaTok(s), tokens); } static List splitAtTokens(List tok, List tokens) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { int j = indexOfSubList(tok, tokens, i); if (i >= l(tok)) break; if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j+l(tokens); } return l; } static List splitAtTokens(List tok, String... tokens) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { int j = indexOfSubList(tok, tokens, i); if (i >= l(tok)) break; if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j+l(tokens); } return l; } static List javaTokPlusBrackets2(String s) { return tok_combineRoundCurlySquareBrackets_keep(javaTok(s)); } static Map> javaTok_cached_cache = synchronizedMRUCache(100); static List javaTok_cached(String s) { List tok = javaTok_cached_cache.get(s); if (tok == null) javaTok_cached_cache.put(s, tok = javaTok(s)); return tok; } static List joinBrackets(List tok) { List t = new ArrayList(); Map map = getBracketMap(tok); for (int i = 0; i < l(tok); i++) { Integer dest = map.get(i); if (dest != null) { t.add(join(subList(tok, i, dest+1))); i = dest; } else t.add(tok.get(i)); } return t; } static List subList(List l, int startIndex) { return subList(l, startIndex, l(l)); } static List subList(int startIndex, int endIndex, List l) { return subList(l, startIndex, endIndex); } 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); } static List subList(List l, IntRange r) { return subList(l, r.start, r.end); } static String[] toStringArray(Collection c) { String[] a = new String[l(c)]; Iterator it = c.iterator(); for (int i = 0; i < l(a); i++) a[i] = it.next(); return a; } static String[] toStringArray(Object o) { if (o instanceof String[]) return (String[]) o; else if (o instanceof Collection) return toStringArray((Collection) o); else throw fail("Not a collection or array: " + getClassName(o)); } // TODO: returns empty first, but not empty last static List splitAt(String s, String splitter) { if (empty(splitter)) return null; // avoid endless loop List parts = new ArrayList(); int i = 0; if (s != null) while (i < l(s)) { int j = indexOf(s, splitter, i); if (j < 0) j = l(s); parts.add(substring(s, i, j)); i = j+l(splitter); } return parts; } static List dropFirstAndLast(int n, List l) { return cloneSubList(l, n, l(l)-n); } static List dropFirstAndLast(int m, int n, List l) { return cloneSubList(l, m, l(l)-n); } static List dropFirstAndLast(List l) { return dropFirstAndLast(1, l); } static String dropFirstAndLast(String s) { return substring(s, 1, l(s)-1); } static String struct(Object o) { return structure(o); } static String struct(Object o, structure_Data data) { return structure(o, data); } static boolean neqic(String a, String b) { return !eqic(a, b); } static boolean neqic(char a, char b) { return !eqic(a, b); } static boolean cic(Collection l, String s) { return containsIgnoreCase(l, s); } static boolean cic(String[] l, String s) { return containsIgnoreCase(l, s); } static boolean cic(String s, char c) { return containsIgnoreCase(s, c); } static boolean cic(String a, String b) { return containsIgnoreCase(a, b); } static String regexpReplaceIC_direct(String s, String pat, String replacement) { Matcher m = regexpIC(pat, s); StringBuffer buf = new StringBuffer(); while (m.find()) m.appendReplacement(buf, replacement); m.appendTail(buf); return str(buf); } static String regexpQuote(String s) { return s.length() == 0 ? "" : Pattern.quote(s); } static boolean loadBufferedImage_useImageCache = true; 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(); // fall back to loading from sourceforge } } 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")); //Log.info("Cached image."); } //Log.info("Loaded image."); return image; } catch (Exception __e) { throw rethrow(__e); } } static BufferedImage loadBufferedImage(File file) { try { return file.isFile() ? ImageIO.read(file) : null; } catch (Exception __e) { throw rethrow(__e); } } static List allToUpper(Collection l) { List x = new ArrayList(l(l)); if (l != null) for (String s : l) x.add(upper(s)); return x; } static CharSequence subCharSequence(CharSequence s, int x) { return subCharSequence(s, x, s == null ? 0 : s.length()); } static CharSequence subCharSequence(CharSequence s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; if (x >= s.length()) return ""; if (y < x) y = x; if (y > s.length()) y = s.length(); return s.subSequence(x, y); } static int min(int a, int b) { return Math.min(a, b); } static long min(long a, long b) { return Math.min(a, b); } static float min(float a, float b) { return Math.min(a, b); } static float min(float a, float b, float c) { return min(min(a, b), c); } static double min(double a, double b) { return Math.min(a, b); } static double min(double[] c) { double x = Double.MAX_VALUE; for (double d : c) x = Math.min(x, d); return x; } static float min(float[] c) { float x = Float.MAX_VALUE; for (float d : c) x = Math.min(x, d); return x; } static byte min(byte[] c) { byte x = 127; for (byte d : c) if (d < x) x = d; return x; } static short min(short[] c) { short x = 0x7FFF; for (short d : c) if (d < x) x = d; return x; } static int min(int[] c) { int x = Integer.MAX_VALUE; for (int d : c) if (d < x) x = d; return x; } static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) { if (tl == null) return null; final A prev = setThreadLocal(tl, a); return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }}; } static String regexpFirstGroup(String pat, String s) { Matcher m = regexpMatcher(pat, s); if (m.find()) return m.group(1); else return null; } static BufferedImage imageFromBytes(byte[] b) { try { return b == null ? null : ImageIO.read(new ByteArrayInputStream(b)); } catch (Exception __e) { throw rethrow(__e); } } static byte[] base64decode(String s) { byte[] alphaToInt = base64decode_base64toint; int sLen = s.length(); int numGroups = sLen/4; if (4*numGroups != sLen) throw new IllegalArgumentException( "String length must be a multiple of four."); int missingBytesInLastGroup = 0; int numFullGroups = numGroups; if (sLen != 0) { if (s.charAt(sLen-1) == '=') { missingBytesInLastGroup++; numFullGroups--; } if (s.charAt(sLen-2) == '=') missingBytesInLastGroup++; } byte[] result = new byte[3*numGroups - missingBytesInLastGroup]; // Translate all full groups from base64 to byte array elements int inCursor = 0, outCursor = 0; for (int i=0; i> 4)); result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2)); result[outCursor++] = (byte) ((ch2 << 6) | ch3); } // Translate partial group, if present if (missingBytesInLastGroup != 0) { int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4)); if (missingBytesInLastGroup == 1) { int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2)); } } // assert inCursor == s.length()-missingBytesInLastGroup; // assert outCursor == result.length; return result; } static int base64decode_base64toint(char c, byte[] alphaToInt) { int result = alphaToInt[c]; if (result < 0) throw new IllegalArgumentException("Illegal character " + c); return result; } static final byte base64decode_base64toint[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 }; static File googleImageSearch_htmlCacheFile(String q) { return javaxCachesDir("Google Image Search/" + uniqueFileNameUsingMD5_80_v2(upper(q)) + ".html"); } static long fileSize(String path) { return getFileSize(path); } static long fileSize(File f) { return getFileSize(f); } /** writes safely (to temp file, then rename) */ 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(); } } static File saveTextFile(File fileName, String contents) { try { saveTextFile(fileName.getPath(), contents); return fileName; } catch (Exception __e) { throw rethrow(__e); } } static List beginCriticalAction_inFlight = synchroList(); static class CriticalAction { String description; CriticalAction() {} CriticalAction(String description) { this.description = description;} void done() { beginCriticalAction_inFlight.remove(this); } } static CriticalAction beginCriticalAction(String description) { ping(); CriticalAction c = new CriticalAction(description); beginCriticalAction_inFlight.add(c); return c; } 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 mkdirsFor(File file) { return mkdirsForFile(file); } static String formatSnippetID(String id) { return "#" + parseSnippetID(id); } static String formatSnippetID(long id) { return "#" + id; } static String md5OfRGBImage(RGBImage img) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(intToBytes(img.getWidth())); int[] pixels = img.getPixels(); for (int i = 0; i < l(pixels); i++) m.update(intToBytes(pixels[i])); return bytesToHex(m.digest()); } catch (Exception __e) { throw rethrow(__e); } } static long imageServerCheckMD5(String md5) { assertTrue(isMD5(md5)); String s = loadPage(imageServerURL() + "checkmd5/" + md5); return parseLongOpt(s); } static String uploadToImageServer_new(BufferedImage img, String name) { return uploadToImageServer_new(null, img, name); } static String uploadToImageServer_new(File f, BufferedImage img, String name) { byte[] imgData = f == null ? toPNG(img) : loadBinaryFile(f); return uploadToImageServer_rawBytes(imgData, name); } static String snippetImgLink(String snippetID) { return snippetImageURL(snippetID); } static A printException(A e) { printStackTrace(e); return e; } static BufferedImage loadImage2(String snippetIDOrURL) { return loadBufferedImage(snippetIDOrURL); } static BufferedImage loadImage2(File file) { return loadBufferedImage(file); } static String fileName(File f) { return f == null ? null : f.getName(); } 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); } static List lookupPossiblyIgnoringCase(MultiMap map, String key) { return lookupPossiblyIgnoreCase(map, key); } static A lookupPossiblyIgnoringCase(Map map, String key) { return lookupPossiblyIgnoreCase(map, key); } static Map>> parseGoogleLog() { Map>> out = new HashMap(); for (Map map : scanMapLog(googleLog())) out.put((String) map.get("query"), (List) map.get("results")); return out; } static boolean loadPageWithUserAgent_verbose = false; static String loadPageWithUserAgent(String url, String userAgent) { try { URL tURL = new URL(url); URLConnection conn = tURL.openConnection(); conn.setRequestProperty("User-Agent", userAgent); loadPage_anonymous = true; if (loadPageWithUserAgent_verbose) print("Loading as " + userAgent + ": " + hideCredentials(url)); return loadPage(conn, tURL); } catch (Exception __e) { throw rethrow(__e); } } static File javaxCachesDir_dir; // can be set to work on different base dir static File javaxCachesDir() { return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches"); } static File javaxCachesDir(String sub) { return newFile(javaxCachesDir(), sub); } static List htmlTok(String s) { return htmlcoarsetok(s); } // tok must come from htmlTok // returns all container tags found (including content) as CNC // honors nested tags correctly static List> findContainerTagDeep(List tok, String tag) { List> l = new ArrayList(); for (int i = 1; i < l(tok); i += 2) if (isOpeningTag(tok.get(i), tag)) { int j, level = 1; for (j = i+2; j < tok.size(); j += 2) if (isOpeningTag(tok.get(j), tag)) ++level; else if (isTag(tok.get(j), "/" + tag)) { --level; if (level == 0) { l.add(tok.subList(i-1, j+2)); // actual CNC break; } } } return l; } static List> findContainerTagDeep(String html, String tag) { return findContainerTagDeep(htmlTok(html), tag); } // Finds out the index of a sublist in the original list // Works with nested (grand-parent) sublists. // Does not work with lists not made with subList() (returns -1) static int magicIndexOfSubList(List list, List sublist) { if (sublist == list) return 0; Integer o2 = (Integer) (get(sublist, "offset")); if (o2 == null) return -1; Integer o1 = (Integer) (getOpt(list, "offset")); return o2-(o1 != null ? o1 : 0); } static boolean tagIs(String token, String tag) { return token.regionMatches(true, 0, "<" + tag + " ", 0, tag.length()+2) || token.regionMatches(true, 0, "<" + tag + ">", 0, tag.length()+2); } static String tagGet(String tag, String param) { return mapGet(htmlgetparams(tag), param); } static boolean isAbsoluteURL(String s) { return contains(s, "://"); } static String htmldecode(final String input) { if (input == null) return null; final int MIN_ESCAPE = 2; final int MAX_ESCAPE = 6; StringWriter writer = null; int len = input.length(); int i = 1; int st = 0; while (true) { // look for '&' while (i < len && input.charAt(i-1) != '&') i++; if (i >= len) break; // found '&', look for ';' int j = i; while (j < len && j < i + MAX_ESCAPE + 1 && input.charAt(j) != ';') j++; if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) { i++; continue; } // found escape if (input.charAt(i) == '#') { // numeric escape int k = i + 1; int radix = 10; final char firstChar = input.charAt(k); if (firstChar == 'x' || firstChar == 'X') { k++; radix = 16; } try { int entityValue = Integer.parseInt(input.substring(k, j), radix); if (writer == null) writer = new StringWriter(input.length()); writer.append(input.substring(st, i - 1)); if (entityValue > 0xFFFF) { final char[] chrs = Character.toChars(entityValue); writer.write(chrs[0]); writer.write(chrs[1]); } else { writer.write(entityValue); } } catch (NumberFormatException ex) { i++; continue; } } else { // named escape CharSequence value = htmldecode_lookupMap.get(input.substring(i, j)); if (value == null) { i++; continue; } if (writer == null) writer = new StringWriter(input.length()); writer.append(input.substring(st, i - 1)); writer.append(value); } // skip escape st = j + 1; i = st; } if (writer != null) { writer.append(input.substring(st, len)); return writer.toString(); } return input; } private static final String[][] htmldecode_ESCAPES = { {"\"", "quot"}, // " - double-quote {"&", "amp"}, // & - ampersand {"<", "lt"}, // < - less-than {">", "gt"}, // > - greater-than // Mapping to escape ISO-8859-1 characters to their named HTML 3.x equivalents. {"\u00A0", "nbsp"}, // non-breaking space {"\u00A1", "iexcl"}, // inverted exclamation mark {"\u00A2", "cent"}, // cent sign {"\u00A3", "pound"}, // pound sign {"\u00A4", "curren"}, // currency sign {"\u00A5", "yen"}, // yen sign = yuan sign {"\u00A6", "brvbar"}, // broken bar = broken vertical bar {"\u00A7", "sect"}, // section sign {"\u00A8", "uml"}, // diaeresis = spacing diaeresis {"\u00A9", "copy"}, // copyright sign {"\u00AA", "ordf"}, // feminine ordinal indicator {"\u00AB", "laquo"}, // left-pointing double angle quotation mark = left pointing guillemet {"\u00AC", "not"}, // not sign {"\u00AD", "shy"}, // soft hyphen = discretionary hyphen {"\u00AE", "reg"}, // registered trademark sign {"\u00AF", "macr"}, // macron = spacing macron = overline = APL overbar {"\u00B0", "deg"}, // degree sign {"\u00B1", "plusmn"}, // plus-minus sign = plus-or-minus sign {"\u00B2", "sup2"}, // superscript two = superscript digit two = squared {"\u00B3", "sup3"}, // superscript three = superscript digit three = cubed {"\u00B4", "acute"}, // acute accent = spacing acute {"\u00B5", "micro"}, // micro sign {"\u00B6", "para"}, // pilcrow sign = paragraph sign {"\u00B7", "middot"}, // middle dot = Georgian comma = Greek middle dot {"\u00B8", "cedil"}, // cedilla = spacing cedilla {"\u00B9", "sup1"}, // superscript one = superscript digit one {"\u00BA", "ordm"}, // masculine ordinal indicator {"\u00BB", "raquo"}, // right-pointing double angle quotation mark = right pointing guillemet {"\u00BC", "frac14"}, // vulgar fraction one quarter = fraction one quarter {"\u00BD", "frac12"}, // vulgar fraction one half = fraction one half {"\u00BE", "frac34"}, // vulgar fraction three quarters = fraction three quarters {"\u00BF", "iquest"}, // inverted question mark = turned question mark {"\u00C0", "Agrave"}, // ? - uppercase A, grave accent {"\u00C1", "Aacute"}, // ? - uppercase A, acute accent {"\u00C2", "Acirc"}, // ? - uppercase A, circumflex accent {"\u00C3", "Atilde"}, // ? - uppercase A, tilde {"\u00C4", "Auml"}, // ? - uppercase A, umlaut {"\u00C5", "Aring"}, // ? - uppercase A, ring {"\u00C6", "AElig"}, // ? - uppercase AE {"\u00C7", "Ccedil"}, // ? - uppercase C, cedilla {"\u00C8", "Egrave"}, // ? - uppercase E, grave accent {"\u00C9", "Eacute"}, // ? - uppercase E, acute accent {"\u00CA", "Ecirc"}, // ? - uppercase E, circumflex accent {"\u00CB", "Euml"}, // ? - uppercase E, umlaut {"\u00CC", "Igrave"}, // ? - uppercase I, grave accent {"\u00CD", "Iacute"}, // ? - uppercase I, acute accent {"\u00CE", "Icirc"}, // ? - uppercase I, circumflex accent {"\u00CF", "Iuml"}, // ? - uppercase I, umlaut {"\u00D0", "ETH"}, // ? - uppercase Eth, Icelandic {"\u00D1", "Ntilde"}, // ? - uppercase N, tilde {"\u00D2", "Ograve"}, // ? - uppercase O, grave accent {"\u00D3", "Oacute"}, // ? - uppercase O, acute accent {"\u00D4", "Ocirc"}, // ? - uppercase O, circumflex accent {"\u00D5", "Otilde"}, // ? - uppercase O, tilde {"\u00D6", "Ouml"}, // ? - uppercase O, umlaut {"\u00D7", "times"}, // multiplication sign {"\u00D8", "Oslash"}, // ? - uppercase O, slash {"\u00D9", "Ugrave"}, // ? - uppercase U, grave accent {"\u00DA", "Uacute"}, // ? - uppercase U, acute accent {"\u00DB", "Ucirc"}, // ? - uppercase U, circumflex accent {"\u00DC", "Uuml"}, // ? - uppercase U, umlaut {"\u00DD", "Yacute"}, // ? - uppercase Y, acute accent {"\u00DE", "THORN"}, // ? - uppercase THORN, Icelandic {"\u00DF", "szlig"}, // ? - lowercase sharps, German {"\u00E0", "agrave"}, // ? - lowercase a, grave accent {"\u00E1", "aacute"}, // ? - lowercase a, acute accent {"\u00E2", "acirc"}, // ? - lowercase a, circumflex accent {"\u00E3", "atilde"}, // ? - lowercase a, tilde {"\u00E4", "auml"}, // ? - lowercase a, umlaut {"\u00E5", "aring"}, // ? - lowercase a, ring {"\u00E6", "aelig"}, // ? - lowercase ae {"\u00E7", "ccedil"}, // ? - lowercase c, cedilla {"\u00E8", "egrave"}, // ? - lowercase e, grave accent {"\u00E9", "eacute"}, // ? - lowercase e, acute accent {"\u00EA", "ecirc"}, // ? - lowercase e, circumflex accent {"\u00EB", "euml"}, // ? - lowercase e, umlaut {"\u00EC", "igrave"}, // ? - lowercase i, grave accent {"\u00ED", "iacute"}, // ? - lowercase i, acute accent {"\u00EE", "icirc"}, // ? - lowercase i, circumflex accent {"\u00EF", "iuml"}, // ? - lowercase i, umlaut {"\u00F0", "eth"}, // ? - lowercase eth, Icelandic {"\u00F1", "ntilde"}, // ? - lowercase n, tilde {"\u00F2", "ograve"}, // ? - lowercase o, grave accent {"\u00F3", "oacute"}, // ? - lowercase o, acute accent {"\u00F4", "ocirc"}, // ? - lowercase o, circumflex accent {"\u00F5", "otilde"}, // ? - lowercase o, tilde {"\u00F6", "ouml"}, // ? - lowercase o, umlaut {"\u00F7", "divide"}, // division sign {"\u00F8", "oslash"}, // ? - lowercase o, slash {"\u00F9", "ugrave"}, // ? - lowercase u, grave accent {"\u00FA", "uacute"}, // ? - lowercase u, acute accent {"\u00FB", "ucirc"}, // ? - lowercase u, circumflex accent {"\u00FC", "uuml"}, // ? - lowercase u, umlaut {"\u00FD", "yacute"}, // ? - lowercase y, acute accent {"\u00FE", "thorn"}, // ? - lowercase thorn, Icelandic {"\u00FF", "yuml"}, // ? - lowercase y, umlaut {"\u2013", "ndash"}, {"\u2018", "lsquo"}, {"\u2019", "rsquo"}, {"\u201D", "rdquo"}, {"\u201C", "ldquo"}, {"\u2014", "mdash"}, {"'", "apos"}, // the controversial (but who cares!) ' // stackoverflow.com/questions/2083754/why-shouldnt-apos-be-used-to-escape-single-quotes }; private static final HashMap htmldecode_lookupMap; static { htmldecode_lookupMap = new HashMap(); for (final CharSequence[] seq : htmldecode_ESCAPES) htmldecode_lookupMap.put(seq[1].toString(), seq[0]); } static String dropTags(String html) { return dropAllTags(html); } static List dropTags(List tok) { return dropAllTags(tok); } // drop opening and closing tag, return new CNC static List contentsOfContainerTag(List tok) { return tok == null ? null : subList(tok, 2, l(tok)-2); } static List contentsOfContainerTag(List tok, String tagName) { return contentsOfContainerTag(first(findContainerTag(tok, tagName))); } // tok must come from htmlTok // returns all container tags found (including content) as CNC // honors nested tags correctly static List> findContainerTagWithParams(List tok, String tag, Object... params) { List> l = new ArrayList(); for (List t : findContainerTag(tok, tag)) if (htmlCheckParams(second(t), params)) l.add(t); return l; } static List> findContainerTagWithParams(String html, String tag, Object... params) { return findContainerTagWithParams(htmlTok(html), tag, params); } static A pnl(String prefix, A l) { printNumberedLines(prefix, l); return l; } static A pnl(A l) { printNumberedLines(l); return l; } static A pnl(A map) { printNumberedLines(map); return map; } static A pnl(String prefix, A map) { printNumberedLines(prefix, map); return map; } static A[] pnl(A[] a) { printNumberedLines(a); return a; } static String pnl(String s) { printNumberedLines(lines(s)); return s; } static T3 triple(A a, B b, C c) { return new T3(a, b, c); } static void logStructure(File logFile, Object o) { logQuoted(logFile, structure(o)); } // quick version - log to file in program directory static void logStructure(String fileName, Object o) { logStructure(getProgramFile(fileName), o); } static void logStructure(String progID, String fileName, Object o) { logStructure(getProgramFile(progID, fileName), o); } static File googleLog() { return javaxDataDir("google-log.txt"); } static LinkedHashMap litorderedmap(Object... x) { LinkedHashMap map = new LinkedHashMap(); litmap_impl(map, x); return map; } static String localDateWithSeconds(long time) { SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss"); return format.format(time); } static String localDateWithSeconds() { return localDateWithSeconds(now()); } static List newSubListOrSame(List l, int startIndex) { return newSubListOrSame(l, startIndex, l(l)); } static List newSubListOrSame(List l, int startIndex, int endIndex) { if (l == null) return null; int n = l(l); startIndex = max(0, startIndex); endIndex = min(n, endIndex); if (startIndex >= endIndex) return ll(); if (startIndex == 0 && endIndex == n) return l; return cloneList(l.subList(startIndex, endIndex)); } static List newSubListOrSame(List l, IntRange r) { return newSubListOrSame(l, r.start, r.end); } static int[] takeFirstOfIntArray(int[] b, int n) { return subIntArray(b, 0, n); } static int[] takeFirstOfIntArray(int n, int[] b) { return takeFirstOfIntArray(b, n); } static Throwable getInnerException(Throwable e) { if (e == null) return null; while (e.getCause() != null) e = e.getCause(); return e; } static Throwable getInnerException(Runnable r) { return getInnerException(getException(r)); } static A assertEquals(Object x, A y) { return assertEquals(null, x, y); } static A assertEquals(String msg, Object x, A y) { if (assertVerbose()) return assertEqualsVerbose(msg, x, y); if (!(x == null ? y == null : x.equals(y))) throw fail((msg != null ? msg + ": " : "") + y + " != " + x); return y; } static List javaTokC(String s) { if (s == null) return null; int l = s.length(); ArrayList tok = new ArrayList(); int i = 0; while (i < l) { int j = i; char c, d; // scan for whitespace while (j < l) { c = s.charAt(j); d = j+1 >= l ? '\0' : s.charAt(j+1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/")); j = Math.min(j+2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } i = j; if (i >= l) break; c = s.charAt(i); d = i+1 >= l ? '\0' : s.charAt(i+1); // scan for non-whitespace if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors ++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)); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } 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)); i = j; } return tok; } static A popLast(List l) { return liftLast(l); } static List popLast(int n, List l) { return liftLast(n, l); } // This is a bit rough... finds static and non-static methods. static Method findMethodNamed(Object obj, String method) { if (obj == null) return null; if (obj instanceof Class) return findMethodNamed((Class) obj, method); return findMethodNamed(obj.getClass(), method); } static Method findMethodNamed(Class c, String method) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) { makeAccessible(m); return m; } c = c.getSuperclass(); } return null; } static void quoteToPrintWriter(String s, PrintWriter out) { if (s == null) { out.print("null"); return; } out.print('"'); int l = s.length(); for (int i = 0; i < l; i++) { char c = s.charAt(i); if (c == '\\' || c == '"') { out.print('\\'); out.print(c); } else if (c == '\r') out.print("\\r"); else if (c == '\n') out.print("\\n"); else if (c == '\0') out.print("\\0"); else out.print(c); } out.print('"'); } static String quoteCharacter(char c) { if (c == '\'') return "'\\''"; if (c == '\\') return "'\\\\'"; if (c == '\r') return "'\\r'"; if (c == '\n') return "'\\n'"; if (c == '\t') return "'\\t'"; return "'" + c + "'"; } static boolean isCISet_gen(Iterable l) { return l instanceof TreeSet && className(((TreeSet) l).comparator()).contains("CIComp"); } static List unwrapSynchronizedList(List l) { if (eqOneOf(className(l), "java.util.Collections$SynchronizedList", "java.util.Collections$SynchronizedRandomAccessList")) return (List) get_raw(l, "list"); return l; } static boolean isCIMap_gen(Map map) { return map instanceof TreeMap && className(((TreeMap) map).comparator()).contains("CIComp"); } static Map unwrapSynchronizedMap(Map map) { if (eqOneOf(className(map), "java.util.Collections$SynchronizedMap", "java.util.Collections$SynchronizedSortedMap", "java.util.Collections$SynchronizedNavigableMap")) return (Map) get_raw(map, "m"); return map; } public static String bytesToHex(byte[] bytes) { return bytesToHex(bytes, 0, bytes.length); } public static String bytesToHex(byte[] bytes, int ofs, int len) { StringBuilder stringBuilder = new StringBuilder(len*2); for (int i = 0; i < len; i++) { String s = "0" + Integer.toHexString(bytes[ofs+i]); stringBuilder.append(s.substring(s.length()-2, s.length())); } return stringBuilder.toString(); } static String boolArrayToHex(boolean[] a) { return bytesToHex(boolArrayToBytes(a)); } static String shortDynamicClassName(Object o) { if (o instanceof DynamicObject && ((DynamicObject) o).className != null) return ((DynamicObject) o).className; return shortClassName(o); } static int stdcompare(Number a, Number b) { return cmp(a, b); } static int stdcompare(String a, String b) { return cmp(a, b); } static int stdcompare(long a, long b) { return a < b ? -1 : a > b ? 1 : 0; } static int stdcompare(Object a, Object b) { return cmp(a, b); } static Map getDeclaredFields_cache = newDangerousWeakHashMap(); static Field[] getDeclaredFields_cached(Class c) { Field[] fields; synchronized(getDeclaredFields_cache) { fields = getDeclaredFields_cache.get(c); if (fields == null) { getDeclaredFields_cache.put(c, fields = c.getDeclaredFields()); for (Field f : fields) makeAccessible(f); } } return fields; } static boolean startsWithDigit(String s) { return nempty(s) && isDigit(s.charAt(0)); } static Map putAll(Map a, Map b) { if (a != null && b != null) a.putAll(b); return a; } static int countDots(String s) { int n = l(s), count = 0; for (int i = 0; i < n; i++) if (s.charAt(i) == '.') ++count; return count; } static String formatWithThousandsSeparator(long l) { return NumberFormat.getInstance(new Locale("en_US")).format(l); } static A listGet(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } // effort doubles for each extra token static int magicQuotes_maxTokens = 10; static Set magicQuotes(String input) { LinkedHashSet out = new LinkedHashSet(); List tok = javaTok(input); if (l(tok) <= magicQuotes_maxTokens) magicQuotes_impl(new ArrayList(), asLinkedList(tok), false, out); return out; } // Q: do remainingTokens start with an N or C token? static void magicQuotes_impl(List tokens, List remainingTokens, boolean inQuote, Set out) { ping(); if (l(remainingTokens) < 2) out.add(inQuote ? join(tokens) + "\"" + join(remainingTokens) : join(tokens) + join(remainingTokens)); else { // case 1: don't insert a quote tokens.addAll(popFirst(2, remainingTokens)); magicQuotes_impl(tokens, remainingTokens, inQuote, out); remainingTokens.addAll(0, popLast(2, tokens)); // case 2: insert quote List t = cloneTakeFirst(2, remainingTokens); if (inQuote) addAll(tokens, "\"" + first(t), second(t)); else addAll(tokens, first(t), "\"" + second(t)); removeFirst(2, remainingTokens); magicQuotes_impl(tokens, remainingTokens, !inQuote, out); removeLast(2, tokens); remainingTokens.addAll(0, t); } } static List matchingPatternsInJavaXSource_withFunctions(String src) { List patterns = mL("JavaX patterns matching patterns"); final List tok = javaTok(loadSnippetOrKeep(src)); LinkedHashSet out = new LinkedHashSet(); for (String pat : patterns) for (String found : jextractAll(pat, tok)) out.add(new FunctionNameAndPattern(firstToken(found), firstQuotedToken(found))); return asList(out); } static String getServerTranspiledWithoutLibs(String snippetID) { return dropFirstLine(getServerTranspiled2(snippetID)); } static String programID() { return getProgramID(); } static String programID(Object o) { return getProgramID(o); } static List filter(Iterable c, Object pred) { if (pred instanceof F1) return filter(c, (F1) pred); List x = new ArrayList(); if (c != null) for (Object o : c) if (isTrue(callF(pred, o))) x.add(o); return x; } static List filter(Object pred, Iterable c) { return filter(c, pred); } static List filter(Iterable c, F1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o)) x.add(o); return x; } static List filter(F1 pred, Iterable c) { return filter(c, pred); } //ifclass IF1 static List filter(Iterable c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o)) x.add(o); return x; } static List filter(B[] c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o)) x.add(o); return x; } static List filter(IF1 pred, Iterable c) { return filter(c, pred); } //endif static boolean matchedByAnyFunctionNameAndPattern(Collection patterns, String input) { for (FunctionNameAndPattern f : unnull(patterns)) if (matchUsingFunctionNameAndPattern(f, input)) return true; return false; } // works on lists and strings and null static int indexOfIgnoreCase(List a, String b) { return indexOfIgnoreCase(a, b, 0); } static int indexOfIgnoreCase(List a, String b, int i) { int n = a == null ? 0 : a.size(); for (; i < n; i++) if (eqic(a.get(i), b)) return i; return -1; } static int indexOfIgnoreCase(String a, String b) { return indexOfIgnoreCase_manual(a, b); /*Matcher m = Pattern.compile(b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(a); if (m.find()) return m.start(); else ret -1;*/ } static int indexOfIgnoreCase(String a, String b, int i) { return indexOfIgnoreCase_manual(a, b, i); } static String getProgramName_cache; static String getProgramName() { Lock __0 = downloadLock(); lock(__0); try { if (getProgramName_cache == null) getProgramName_cache = getSnippetTitleOpt(programID()); return getProgramName_cache; } finally { unlock(__0); } } static void _onLoad_getProgramName() { { startThread(new Runnable() { public void run() { try { getProgramName(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getProgramName();"; }}); } } static List parse3(String s) { return dropPunctuation(javaTokPlusPeriod(s)); } static int[] emptyIntArray_a = new int[0]; static int[] emptyIntArray() { return emptyIntArray_a; } static char[] emptyCharArray = new char[0]; static char[] emptyCharArray() { return emptyCharArray; } static Map emptyMap() { return new HashMap(); } static Object[] emptyObjectArray_a = new Object[0]; static Object[] emptyObjectArray() { return emptyObjectArray_a; } static List concatLists(Iterable... lists) { List l = new ArrayList(); if (lists != null) for (Iterable list : lists) addAll(l, list); return l; } static List concatLists(Collection> lists) { List l = new ArrayList(); if (lists != null) for (Iterable list : lists) addAll(l, list); return l; } static String rep(int n, char c) { return repeat(c, n); } static String rep(char c, int n) { return repeat(c, n); } static List rep(A a, int n) { return repeat(a, n); } static List rep(int n, A a) { return repeat(n, a); } static String join_flex(List glues, Iterable strings) { if (strings == null) return ""; StringBuilder buf = new StringBuilder(); Iterator i = strings.iterator(); Iterator iGlues = glues.iterator(); if (i.hasNext()) { buf.append(i.next()); while (i.hasNext()) buf.append(iGlues.next()).append(i.next()); } return buf.toString(); } 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); } static String javaTok_substringC(String s, int i, int j) { return s.substring(i, j); } 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; // scan for whitespace 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); // scan for non-whitespace // Special JavaX syntax: 'identifier 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 /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings ++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)); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } else if (c == '[' && d == '[') { do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]")); j = Math.min(j+2, l); } else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') { do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]")); j = Math.min(j+3, l); } else ++j; if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) { return t.length() == j-i && s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave } static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); } 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|cookie)=[^&\\s\"]*", "$1$2="); } static String hideCredentials(Object o) { return hideCredentials(str(o)); } static Throwable unwrapTrivialExceptionWraps(Throwable e) { if (e == null) return e; while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause(); return e; } static String replacePrefix(String prefix, String replacement, String s) { if (!startsWith(s, prefix)) return s; return replacement + substring(s, l(prefix)); } static Throwable innerException2(Throwable e) { if (e == null) return null; while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause(); return e; } static List _registerDangerousWeakMap_preList; static A _registerDangerousWeakMap(A map) { return _registerDangerousWeakMap(map, null); } static A _registerDangerousWeakMap(A map, Object init) { callF(init, map); if (init instanceof String) { final String f = (String) init; init = new VF1() { public void get(Map map) { try { callMC(f, map) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callMC(f, map)"; }}; } if (javax() == null) { // We're in class init if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList(); _registerDangerousWeakMap_preList.add(pair(map, init)); return map; } call(javax(), "_registerDangerousWeakMap", map, init); return map; } static void _onLoad_registerDangerousWeakMap() { assertNotNull(javax()); if (_registerDangerousWeakMap_preList == null) return; for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b); _registerDangerousWeakMap_preList = null; } static Throwable getExceptionCause(Throwable e) { Throwable c = e.getCause(); return c != null ? c : e; } static String joinWithSpace(Iterable c) { return join(" ", c); } static String joinWithSpace(String... c) { return join(" ", c); } static boolean isInstanceX(Class type, Object arg) { if (type == boolean.class) return arg instanceof Boolean; if (type == int.class) return arg instanceof Integer; if (type == long.class) return arg instanceof Long; if (type == float.class) return arg instanceof Float; if (type == short.class) return arg instanceof Short; if (type == char.class) return arg instanceof Character; if (type == byte.class) return arg instanceof Byte; if (type == double.class) return arg instanceof Double; return type.isInstance(arg); } static 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); } static void vmBus_send(String msg) { vmBus_send(msg, (Object) null); } static Random defaultRandomGenerator() { return ThreadLocalRandom.current(); } static Class __javax; static Class getJavaX() { try { return __javax; } catch (Exception __e) { throw rethrow(__e); } } static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; static CloseableIterableIterator emptyCloseableIterableIterator() { return emptyCloseableIterableIterator_instance; } static boolean ewic(String a, String b) { return endsWithIgnoreCase(a, b); } static boolean ewic(String a, String b, Matches m) { return endsWithIgnoreCase(a, b, m); } static 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)); } static BufferedReader utf8bufferedReader(InputStream in) { try { return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in)); } catch (Exception __e) { throw rethrow(__e); } } static BufferedReader utf8bufferedReader(File f) { try { return utf8bufferedReader(newFileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } static GZIPInputStream newGZIPInputStream(File f) { return gzInputStream(f); } static GZIPInputStream newGZIPInputStream(InputStream in) { return gzInputStream(in); } static List _registerWeakMap_preList; static A _registerWeakMap(A map) { if (javax() == null) { // We're in class init if (_registerWeakMap_preList == null) _registerWeakMap_preList = synchroList(); _registerWeakMap_preList.add(map); return map; } try { call(javax(), "_registerWeakMap", map); } catch (Throwable e) { printException(e); print("Upgrade JavaX!!"); } return map; } static void _onLoad_registerWeakMap() { assertNotNull(javax()); if (_registerWeakMap_preList == null) return; for (Object o : _registerWeakMap_preList) _registerWeakMap(o); _registerWeakMap_preList = null; } static int isAndroid_flag; static boolean isAndroid() { if (isAndroid_flag == 0) isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1; return isAndroid_flag > 0; } static Boolean isHeadless_cache; static boolean isHeadless() { if (isHeadless_cache != null) return isHeadless_cache; if (isAndroid()) return isHeadless_cache = true; if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true; // Also check if AWT actually works. // If DISPLAY variable is set but no X server up, this will notice. try { SwingUtilities.isEventDispatchThread(); return isHeadless_cache = false; } catch (Throwable e) { return isHeadless_cache = true; } } static void assertTrue(Object o) { if (!(eq(o, true) /*|| isTrue(pcallF(o))*/)) throw fail(str(o)); } static boolean assertTrue(String msg, boolean b) { if (!b) throw fail(msg); return b; } static boolean assertTrue(boolean b) { if (!b) throw fail("oops"); return b; } static volatile boolean licensed_yes = true; static boolean licensed() { if (!licensed_yes) return false; ping_okInCleanUp(); return true; } static void licensed_off() { licensed_yes = false; } // PersistableThrowable doesn't hold GC-disturbing class references in backtrace static volatile PersistableThrowable lastException_lastException; static PersistableThrowable lastException() { return lastException_lastException; } static void lastException(Throwable e) { lastException_lastException = persistableThrowable(e); } // f : Matcher -> S static String regexReplaceIC(String s, String pat, Object f) { return regexReplace(regexpMatcherIC(pat, s), f); } static String _userHome; static String userHome() { if (_userHome == null) return actualUserHome(); return _userHome; } static File userHome(String path) { return new File(userDir(), path); } static String formatSnippetIDOpt(String s) { return isSnippetID(s) ? formatSnippetID(s) : s; } static Class getMainClass() { return mc(); } static Class getMainClass(Object o) { try { if (o == null) return null; if (o instanceof Class && eq(((Class) o).getName(), "x30")) return (Class) o; return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main"); } catch (Exception __e) { throw rethrow(__e); } } static Map syncMRUCache(int size) { return synchroMap(new MRUCache(size)); } static RuntimeException wrapPatternSyntaxException(PatternSyntaxException e) { if (e == null) return null; String pat = e.getPattern(); int i = e.getIndex(); return new RuntimeException("Regular expression error between " + multiLineQuoteWithSpaces(substring(pat, 0, i)) + " and " + multiLineQuoteWithSpaces(substring(pat, i)) + " - " + e.getMessage()); } static Map compileRegexp_cache = syncMRUCache(10); 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; } static void clear(Collection c) { if (c != null) c.clear(); } static void clear(Map map) { if (map != null) map.clear(); } static void put(Map map, A a, B b) { if (map != null) map.put(a, b); } static void put(List l, int i, A a) { if (l != null && i >= 0 && i < l(l)) l.set(i, a); } static B mapGet2(Map map, A a) { return map == null ? null : map.get(a); } static B mapGet2(A a, Map map) { return map == null ? null : map.get(a); } static boolean isSubtypeOf(Class a, Class b) { return b.isAssignableFrom(a); // << always hated that method, let's replace it! } static Set reflection_classesNotToScan_value = litset( "jdk.internal.loader.URLClassPath" ); static Set reflection_classesNotToScan() { return reflection_classesNotToScan_value; } static boolean equalsIgnoreCase(String a, String b) { return eqic(a, b); } static boolean equalsIgnoreCase(char a, char b) { return eqic(a, b); } static boolean eqicOrEq(Object a, Object b) { return a instanceof String && b instanceof String ? eqic((String) a, (String) b) : eq(a, b); } static void _registerIO(Object object, String path, boolean opened) { } static File getProgramDir() { return programDir(); } static File getProgramDir(String snippetID) { return programDir(snippetID); } static A[] arrayOfSameType(A[] a, int n) { return newObjectArrayOfSameType(a, n); } static List takeLast(List l, int n) { return newSubList(l, l(l)-n); } static List takeLast(int n, List l) { return takeLast(l, n); } static String takeLast(int n, String s) { return substring(s, l(s)-n); } static String takeLast(String s, int n) { return substring(s, l(s)-n); } static String className(Object o) { return getClassName(o); } static boolean eqOneOf(Object o, Object... l) { for (Object x : l) if (eq(o, x)) return true; return false; } static Map synchroHashMap() { return Collections.synchronizedMap(new HashMap()); } static Map> javaTokNPunctuationWithBrackets_cache = synchronizedMRUCache(1000); static List javaTokNPunctuationWithBrackets(String s) { List tok = javaTokNPunctuationWithBrackets_cache.get(s); if (tok == null) javaTokNPunctuationWithBrackets_cache.put(s, tok = javaTokNPunctuationWithBrackets_uncached(s)); return tok; } static List javaTokNPunctuationWithBrackets_uncached(String s) { return tok_combineRoundOrCurlyBrackets_keep(javaTokNPunctuation_bracketsInC(s)); } static boolean isLetter(char c) { return Character.isLetter(c); } static A last(List l) { return empty(l) ? null : l.get(l.size()-1); } static char last(String s) { return empty(s) ? '#' : s.charAt(l(s)-1); } static int last(int[] a) { return l(a) != 0 ? a[l(a)-1] : 0; } static double last(double[] a) { return l(a) != 0 ? a[l(a)-1] : 0; } static A last(A[] a) { return l(a) != 0 ? a[l(a)-1] : null; } static A last(Iterator it) { A a = null; while (it.hasNext()) { ping(); a = it.next(); } return a; } static A last(Collection l) { if (l == null) return null; if (l instanceof List) return (A) last(((List) l)); if (l instanceof SortedSet) return (A) last(((SortedSet) l)); Iterator it = iterator(l); A a = null; while (it.hasNext()) { ping(); a = it.next(); } return a; } static A last(SortedSet l) { return l == null ? null : l.last(); } static String beautifyStructure(String s) { List tok = javaTokForStructure(s); structure_addTokenMarkers(tok); jreplace(tok, "lhm", ""); return join(tok); } static String struct_noStringSharing(Object o) { structure_Data d = new structure_Data(); d.noStringSharing = true; return structure(o, d); } 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; } static Object vmBus_query(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); { Object __1= pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg); if (__1 != null) return __1; } return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg); } static Object vmBus_query(String msg) { return vmBus_query(msg, (Object) null); } static String assertIdentifier(String s) { return assertIsIdentifier(s); } static String assertIdentifier(String msg, String s) { return assertIsIdentifier(msg, s); } static Object dm_os() { { Object __1= vm_generalMap_get("stefansOS"); if (__1 != null) return __1; } return creator(); } static boolean methodIsStatic(Method m) { return (m.getModifiers() & Modifier.STATIC) != 0; } static boolean argumentCompatibleWithType(Object arg, Class type) { return arg == null ? !type.isPrimitive() : isInstanceX(type, arg); } static A[] arrayOfType(Class type, int n) { return makeArray(type, n); } static A[] arrayOfType(int n, Class type) { return arrayOfType(type, n); } static List getClassNames(Collection l) { List out = new ArrayList(); if (l != null) for (Object o : l) out.add(o == null ? null : getClassName(o)); return out; } static Object dm_getStemByID(Object id) { return dm_callOS("getModuleByID", str(id)); } static A assertNotNull(A a) { assertTrue(a != null); return a; } static A assertNotNull(String msg, A a) { assertTrue(msg, a != null); return a; } // named like this for historic reasons static InheritableThreadLocal dm_currentModule_value = new InheritableThreadLocal(); static Object dm_current_generic() { return getWeakRef(dm_currentModule_value.get()); } // prevent memory leak static void cleanMeUp_dm_current_generic() { dm_currentModule_value = new InheritableThreadLocal(); } static int indexOfSubList(List x, List y) { return indexOfSubList(x, y, 0); } 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; } 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; } static String trimJoin(List s) { return trim(join(s)); } static List tok_combineRoundCurlySquareBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eqOneOf(t, "{", "(", "[")) { int j = findEndOfBracketPart2(tok, i); l.add(joinSubList(tok, i, j)); i = j-1; } else l.add(t); } return l; } // map: index of opening bracket -> index of closing bracket static Map getBracketMap(List tok) { return getBracketMap(tok, getBracketMap_opening, getBracketMap_closing); } static Map getBracketMap(List tok, Collection opening, Collection closing) { return getBracketMap(tok, opening, closing, 0, l(tok)); } static Map getBracketMap(List tok, Collection opening, Collection closing, int from, int to) { TreeMap map = new TreeMap(); List stack = new ArrayList(); for (int i = from|1; i < to; i+= 2) { if (opening.contains(tok.get(i))) stack.add(i); else if (closing.contains(tok.get(i))) { if (!empty(stack)) map.put(liftLast(stack), i); } } return map; } static Set getBracketMap_opening = lithashset("{", "("); static Set getBracketMap_closing = lithashset("}", ")"); static List cloneSubList(List l, int startIndex, int endIndex) { return newSubList(l, startIndex, endIndex); } static List cloneSubList(List l, int startIndex) { return newSubList(l, startIndex); } static boolean isURL(String s) { return startsWithOneOf(s, "http://", "https://", "file:"); } static BufferedImage imageIO_readURL(String url) { try { return ImageIO.read(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } static boolean isAbsolutePath(String s) { return s != null && new File(s).isAbsolute(); } static boolean isAbsolutePath(File f) { return f != null && f.isAbsolute(); } public static boolean isSnippetID(String s) { try { parseSnippetID(s); return true; } catch (RuntimeException e) { return false; } } public static long parseSnippetID(String snippetID) { long id = Long.parseLong(shortenSnippetID(snippetID)); if (id == 0) throw fail("0 is not a snippet ID"); return id; } static IResourceLoader vm_getResourceLoader() { return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader")); } static File imageSnippetsCacheDir() { return javaxCachesDir("Image-Snippets"); } static String snippetImageURL_http(String snippetID) { return snippetImageURL_http(snippetID, "png"); } static String snippetImageURL_http(String snippetID, String contentType) { return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080"); } static String upper(String s) { return s == null ? null : s.toUpperCase(); } static char upper(char c) { return Character.toUpperCase(c); } static A setThreadLocal(ThreadLocal tl, A value) { if (tl == null) return null; A old = tl.get(); tl.set(value); return old; } static String uniqueFileNameUsingMD5_80_v2(String fullName) { return uniqueFileNameUsingMD5_80_v2(fullName, md5(fullName)); } static String uniqueFileNameUsingMD5_80_v2(String fullName, String md5) { return takeFirst(80-33, fileNameEncode(fullName)) + " - " + md5; } static long now_virtualTime; static long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } static File copyFile(File src, File dest) { try { FileInputStream inputStream = new FileInputStream(src.getPath()); FileOutputStream outputStream = newFileOutputStream(dest.getPath()); try { copyStream(inputStream, outputStream); inputStream.close(); } finally { outputStream.close(); } return dest; } catch (Exception __e) { throw rethrow(__e); } } static List collect(Iterable c, String field) { return collectField(c, field); } static List collect(String field, Iterable c) { return collectField(c, field); } /*ifclass Concept static L collect(Class c, S field) { ret collect(list(c), field); } endif TODO: make translator ignore stuff in ifclass until resolved */ static void sleepInCleanUp(long ms) { try { if (ms < 0) return; Thread.sleep(ms); } catch (Exception __e) { throw rethrow(__e); } } static byte[] intToBytes(int i) { return new byte[] { (byte) (i >>> 24), (byte) (i >>> 16), (byte) (i >>> 8), (byte) i}; } static boolean isMD5(String s) { return l(s) == 32 && isLowerHexString(s); } static int loadPage_defaultTimeout = 60000; static ThreadLocal loadPage_charset = new ThreadLocal(); static boolean loadPage_allowGzip = true, loadPage_debug; static boolean loadPage_anonymous = false; // don't send computer ID static int loadPage_verboseness = 100000; static int loadPage_retries = 1; //60; // seconds static ThreadLocal loadPage_silent = new ThreadLocal(); static volatile int loadPage_forcedTimeout; // ms static ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal(); // ms static ThreadLocal>> loadPage_responseHeaders = new ThreadLocal(); static ThreadLocal> loadPage_extraHeaders = new ThreadLocal(); static ThreadLocal loadPage_sizeLimit = new ThreadLocal(); public static String loadPageSilently(String url) { try { return loadPageSilently(new URL(loadPage_preprocess(url))); } catch (Exception __e) { throw rethrow(__e); } } public static String loadPageSilently(URL url) { try { if (!networkAllowanceTest(str(url))) throw fail("Not allowed: " + url); IOException e = null; for (int tries = 0; tries < loadPage_retries; tries++) try { URLConnection con = loadPage_openConnection(url); return loadPage(con, url); } catch (IOException _e) { e = _e; if (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); } } static String loadPage_preprocess(String url) { if (url.startsWith("tb/")) // don't think we use this anymore url = tb_mainServer() + "/" + url; if (url.indexOf("://") < 0) url = "http://" + url; return url; } 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); } } static String loadPage(URL url) { return loadPage(url.toExternalForm()); } static String loadPage(URLConnection con, URL url) throws IOException { return loadPage(con, url, true); } static String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException { Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders); Long limit = optPar(loadPage_sizeLimit); if (addHeaders) try { if (!loadPage_anonymous) setHeaders(con); if (loadPage_allowGzip) con.setRequestProperty("Accept-Encoding", "gzip"); con.setRequestProperty("X-No-Cookies", "1"); for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key)); } catch (Throwable e) {} // fails if within doPost vm_generalSubMap("URLConnection per thread").put(currentThread(), con); loadPage_responseHeaders.set(con.getHeaderFields()); InputStream in = null; try { in = urlConnection_getInputStream(con); //vm_generalSubMap("InputStream per thread").put(currentThread(), in); if (loadPage_debug) print("Put stream in map: " + currentThread()); String contentType = con.getContentType(); if (contentType == null) { //printStruct("Headers: ", con.getHeaderFields()); throw new IOException("Page could not be read: " + hideCredentials(url)); } //print("Content-Type: " + contentType); String charset = loadPage_charset == null ? null : loadPage_charset.get(); if (charset == null) charset = loadPage_guessCharset(contentType); if ("gzip".equals(con.getContentEncoding())) { if (loadPage_debug) print("loadPage: Using gzip."); in = newGZIPInputStream(in); } Reader r; try { r = new InputStreamReader(in, unquote(charset)); } catch (UnsupportedEncodingException e) { print(toHex(utf8(charset))); throw e; } boolean silent = isTrue(loadPage_silent.get()); StringBuilder buf = new StringBuilder(); int n = 0; while (limit == null || n < limit) { ping(); int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; if (!silent && (n % loadPage_verboseness) == 0) print(" " + n + " chars read"); } return buf.toString(); } finally { if (loadPage_debug) print("loadPage done"); //vm_generalSubMap("InputStream per thread").remove(currentThread()); vm_generalSubMap("URLConnection per thread").remove(currentThread()); if (in != null) in.close(); } } 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); /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */ //return or(match, "ISO-8859-1"); return or(match, "UTF-8"); } 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; } static String imageServerURL() { return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/"); } static byte[] toPNG(BufferedImage img) { return convertToPNG(img); } public static byte[] loadBinaryFile(String fileName) { try { if (!new File(fileName).exists()) return null; FileInputStream in = new FileInputStream(fileName); byte buf[] = new byte[1024]; ByteArrayOutputStream out = new ByteArrayOutputStream(); int l; while (true) { l = in.read(buf); if (l <= 0) break; out.write(buf, 0, l); } in.close(); return out.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } } public static byte[] loadBinaryFile(File file) { return loadBinaryFile(file.getPath()); } static String uploadToImageServer_rawBytes(byte[] imgData, String name) { String page = postPage(imageServerURL() + "upload/" + randomID() /* anti-anti-spam */, "data", bytesToHex(imgData), "name", name); print(page); Matcher m = Pattern.compile("/images/([0-9]+)").matcher(page); if (!m.find()) return null; return snippetImgLink(m.group(1)); } static String snippetImageURL(long snippetID) { return snippetImageURL(fsI(snippetID)); } static String snippetImageURL(String snippetID) { return snippetImageURL(snippetID, "png"); } static String snippetImageURL(String snippetID, String contentType) { if (snippetID == null || isURL(snippetID)) return snippetID; long id = parseSnippetID(snippetID); String url; if (isImageServerSnippet(id)) url = imageServerLink(id); else //url = "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=image/" + contentType; url = "https://botcompany.de/img/" + id; return url; } static Map mapPlus(Map m, Object... data) { m = cloneMap(m); litmap_impl(m, data); return m; } static Object[] assertEvenLength(Object[] a) { assertTrue(even(l(a))); return a; } static LinkedHashMap paramsToOrderedMap(Object... params) { return asLinkedHashMap(paramsToMap(params)); } static Object[] mapToParams(Map map) { return mapToObjectArray(map); } static List lookupPossiblyIgnoreCase(MultiMap map, String key) { if (map == null) return null; List value = map.get(key); return !value.isEmpty() ? value : lookupIgnoreCase(map, key); } static A lookupPossiblyIgnoreCase(Map map, String key) { if (map == null) return null; A value = map.get(key); return value != null ? value : lookupIgnoreCase(map, key); } static List scanMapLog(String progID, String fileName) { return scanMapLog(getProgramFile(progID, fileName)); } static List scanMapLog(String fileName) { return scanMapLog(getProgramFile(fileName)); } static List scanMapLog(File file) { List l = new ArrayList(); for (String s : scanLog(file)) { try { l.add(unstructureMap(s)); } catch (Throwable __e) { _handleException(__e); }} return l; } // TODO: process CDATA, scripts static List htmlcoarsetok(String s) { List tok = new ArrayList(); int l = s == null ? 0 : s.length(); int i = 0; while (i < l) { int j = i; char c; // scan for non-tags while (j < l) { if (s.charAt(j) != '<') // regular character ++j; else if (s.substring(j, Math.min(j+4, l)).equals("")); j = Math.min(j+3, l); } else // it's a tag break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); // scan for tags if (c == '<') { ++j; while (j < l && s.charAt(j) != '>') ++j; // TODO: strings? if (j < l) ++j; } tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static boolean isOpeningTag(String token, String tag) { return isTag(token, tag) && !token.endsWith("/>"); } static boolean isOpeningTag(String token) { return token.startsWith("<") && token.endsWith(">") && !token.endsWith("/>") && isLetter(token.charAt(1)); } static boolean isTag(String token, String tag) { return token.regionMatches(true, 0, "<" + tag + " ", 0, tag.length()+2) || token.regionMatches(true, 0, "<" + tag + ">", 0, tag.length()+2); } static Map htmlgetparams(String tag) { return getHtmlTagParameters(tag); } // tok should be the output of htmlcoarsetok static List dropAllTags(List tok) { List list = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && t.startsWith("<")) { list.set(list.size()-1, list.get(list.size()-1) + tok.get(i+1)); ++i; } else list.add(t); } return list; } // alternatively, call this convenient function static String dropAllTags(String html) { return join(dropAllTags(htmlcoarsetok(html))); } // tok must come from htmlTok // returns all container tags found (including content) as CNC // should be OK for both HTML and XML static List> findContainerTag(List tok, String tag) { List> l = new ArrayList(); for (int i = 1; i < l(tok); i += 2) if (isOpeningTag(tok.get(i), tag)) { int j, level = 1; for (j = i+2; j < tok.size(); j += 2) if (isOpeningTag(tok.get(j), tag)) ++level; else if (isTag(tok.get(j), "/" + tag)) { --level; if (level == 0) { l.add(tok.subList(i-1, j+2)); // actual CNC break; } } i = j; } return l; } static List> findContainerTag(String html, String tag) { return findContainerTag(htmlTok(html), tag); } static boolean htmlCheckParams(String tag, Object... params) { return checkFields(htmlgetparams(tag), params); } /*static L printNumberedLines(L l) { printNumberedLines((Collection) l); ret l; } static L printNumberedLines(S prefix, L l) { printNumberedLines(prefix, (Collection) l); ret l; }*/ static void printNumberedLines(Map map) { printNumberedLines(mapToLines(map)); } static void printNumberedLines(String prefix, Map map) { printNumberedLines(prefix, mapToLines(map)); } static A printNumberedLines(A l) { int i = 0; if (l != null) for (Object a : l) print((++i) + ". " + str(a)); return l; } static A printNumberedLines(String prefix, A l) { int i = 0; if (l != null) for (Object a : l) print(prefix + (++i) + ". " + str(a)); return l; } static void printNumberedLines(Object[] l) { printNumberedLines(asList(l)); } static void printNumberedLines(Object o) { printNumberedLines(lines(str(o))); } static void logQuoted(String logFile, String line) { logQuoted(getProgramFile(logFile), line); } static void logQuoted(File logFile, String line) { appendToFile(logFile, quote(line) + "\n"); } static File javaxDataDir_dir; // can be set to work on different base dir static File javaxDataDir() { return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data"); } static File javaxDataDir(String... subs) { return newFile(javaxDataDir(), subs); } static HashMap litmap(Object... x) { HashMap map = new HashMap(); litmap_impl(map, x); return map; } 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]); } static SimpleDateFormat simpleDateFormat_local(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(localTimeZone()); return sdf; } static int[] subIntArray(int[] b, int start) { return subIntArray(b, start, l(b)); } static int[] subIntArray(int[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new int[0]; int[] x = new int[end-start]; System.arraycopy(b, start, x, 0, end-start); return x; } static int[] subIntArray(int[] a, IntRange r) { return r == null ? null : subIntArray(a, r.start, r.end); } static Throwable getException(Runnable r) { try { callF(r); return null; } catch (Throwable e) { return e; } } static ThreadLocal assertVerbose_value = new ThreadLocal(); static void assertVerbose(boolean b) { assertVerbose_value.set(b); } static boolean assertVerbose() { return isTrue(assertVerbose_value.get()); } static A assertEqualsVerbose(Object x, A y) { assertEqualsVerbose((String) null, x, y); return y; } // x = expected, y = actual static A assertEqualsVerbose(String msg, Object x, A y) { if (!eq(x, y)) { throw fail((msg != null ? msg + ": " : "") + "expected: "+ x + ", got: " + y); } else print("OK" + (empty(msg) ? "" : " " + msg) + ": " + /*sfu*/(x)); return y; } static A liftLast(List l) { if (empty(l)) return null; int i = l(l)-1; A a = l.get(i); l.remove(i); return a; } static List liftLast(int n, List l) { int i = l(l)-n; List part = cloneSubList(l, i); removeSubList(l, i); return part; } static byte[] boolArrayToBytes(boolean[] a) { byte[] b = new byte[(l(a)+7)/8]; for (int i = 0; i < l(a); i++) if (a[i]) b[i/8] |= 1 << (i & 7); return b; } 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); } static int cmp(Number a, Number b) { return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue()); } static int cmp(double a, double b) { return a < b ? -1 : a == b ? 0 : 1; } static int cmp(int a, int b) { return a < b ? -1 : a == b ? 0 : 1; } static int cmp(long a, long b) { return a < b ? -1 : a == b ? 0 : 1; } static int cmp(Object a, Object b) { if (a == null) return b == null ? 0 : -1; if (b == null) return 1; return ((Comparable) a).compareTo(b); } static boolean isDigit(char c) { return Character.isDigit(c); } static LinkedList asLinkedList(Iterable s) { if (s instanceof LinkedList) return ((LinkedList) s); LinkedList l = new LinkedList(); if (s != null) for (A a : s) l.add(a); return l; } static A popFirst(List l) { if (empty(l)) return null; A a = first(l); l.remove(0); return a; } static A popFirst(Collection l) { if (empty(l)) return null; A a = first(l); l.remove(a); return a; } static List popFirst(int n, List l) { List part = cloneSubList(l, 0, n); removeSubList(l, 0, n); return part; } static List cloneTakeFirst(List l, int n) { return l(l) <= n ? l : cloneSubList(l, 0, n); } static List cloneTakeFirst(int n, List l) { return cloneTakeFirst(l, n); } static void addAll(Collection c, Iterable b) { if (c != null && b != null) for (A a : b) c.add(a); } static boolean addAll(Collection c, Collection b) { return c != null && b != null && c.addAll(b); } static boolean addAll(Collection c, B... b) { return c != null && c.addAll(Arrays.asList(b)); } static Map addAll(Map a, Map b) { if (a != null) a.putAll(b); return a; } static void removeFirst(List l) { if (nempty(l)) l.remove(0); } static void removeFirst(int n, List l) { removeSubList(l, 0, n); } static void removeLast(List l) { if (!l.isEmpty()) l.remove(l(l)-1); } static void removeLast(List l, int n) { removeSubList(l, l(l)-n); } static void removeLast(int n, List l) { removeLast(l, n); } static List mL(String name) { return mechList_opt(name); } static String loadSnippetOrKeep(String snippetIDOrText) { return isSnippetID(snippetIDOrText) ? loadSnippet(snippetIDOrText) : snippetIDOrText; } static List jextractAll(String pat, String s) { return jextractAll(pat, javaTok(s)); } static List jextractAll(String pat, List tok) { List tokpat = javaTok(pat); jfind_preprocess(tokpat); return map(jfindAll(tok, tokpat), i -> joinSubList(tok, i, i+l(tokpat)-2)); } static String firstToken(String s) { return firstJavaToken(s); } static String firstToken(List tok) { return get(tok, 1); } static String firstQuotedToken(String s) { for (String t : javaTok(s)) if (isQuoted(t)) return unquote(t); return null; } static String dropFirstLine(String text) { if (text == null) return null; int i = text.indexOf('\n'); return i >= 0 ? text.substring(i+1) : ""; } static boolean getServerTranspiled2_allowLocalFallback = true, getServerTranspiled2_localFallbackVerbose = true; // to avoid checking server for transpilations too often when booting OS static Map getServerTranspiled2_tempCache; static String getServerTranspiled2(String id) { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.getTranspiled(id); id = fsIOpt(id); String transpiled = mapGet(getServerTranspiled2_tempCache, id); if (transpiled != null) return transpiled; //if (getServerTranspiled2_tempCache != null) print("CACHE FAIL on " + id); transpiled = loadCachedTranspilation(id); String md5 = null; if (machineIsOffline() || isOfflineMode() || isLocalSnippet(id)) return transpiled; if (transpiled != null) md5 = md5(transpiled); String transpiledSrc; try { transpiledSrc = getServerTranspiled(formatSnippetID(id), md5); } catch (Throwable e) { if (!getServerTranspiled2_allowLocalFallback) rethrow(e); printExceptionShort(e); if (getServerTranspiled2_localFallbackVerbose) print("Fallback to local code"); return transpiled; } if (eq(transpiledSrc, "SAME")) { if (!isTrue(loadPage_silent.get())) print("SAME"); return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiled); } return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiledSrc); } static boolean matchUsingFunctionNameAndPattern(FunctionNameAndPattern fp, String s, Matches m) { if (fp == null) return false; String f = fp.function, pat = fp.pattern; if (eqOneOf(f, "if", "match", "match3")) return match(pat, s, m); if (eq(f, "matchX")) return matchX(pat, s, m); if (eq(f, "matchX2")) return matchX2(pat, s, m); if (eq(f, "matchX_vbar")) return matchX_vbar(pat, s, m); warn("Unknown function: " + fp); return false; } static boolean matchUsingFunctionNameAndPattern(FunctionNameAndPattern fp, String s) { return matchUsingFunctionNameAndPattern(fp, s, null); } static int indexOfIgnoreCase_manual(String a, String b) { return indexOfIgnoreCase_manual(a, b, 0); } static int indexOfIgnoreCase_manual(String a, String b, int i) { int la = strL(a), lb = strL(b); if (la < lb) return -1; int n = la-lb; loop: for (; i <= n; i++) { for (int j = 0; j < lb; j++) { char c1 = a.charAt(i+j), c2 = b.charAt(j); if (!eqic(c1, c2)) continue loop; } return i; } return -1; } static Lock downloadLock_lock = fairLock(); static Lock downloadLock() { return downloadLock_lock; } static String getSnippetTitleOpt(String s) { return isSnippetID(s) ? getSnippetTitle(s) : s; } static Thread startThread(Object runnable) { return startThread(defaultThreadName(), runnable); } static Thread startThread(String name, Object runnable) { runnable = wrapAsActivity(runnable); return startThread(newThread(toRunnable(runnable), name)); } static Thread startThread(Thread t) { _registerThread(t); t.start(); return t; } static List dropPunctuation_keep = ll("*", "<", ">"); static List dropPunctuation(List tok) { tok = new ArrayList(tok); for (int i = 1; i < tok.size(); i += 2) { String t = tok.get(i); if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) { tok.set(i-1, tok.get(i-1) + tok.get(i+1)); tok.remove(i); tok.remove(i); i -= 2; } } return tok; } static String dropPunctuation(String s) { return join(dropPunctuation(nlTok(s))); } static String repeat(char c, int n) { n = Math.max(n, 0); char[] chars = new char[n]; for (int i = 0; i < n; i++) chars[i] = c; return new String(chars); } static List repeat(A a, int n) { n = Math.max(n, 0); List l = new ArrayList(n); for (int i = 0; i < n; i++) l.add(a); return l; } static List repeat(int n, A a) { return repeat(a, n); } static boolean startsWithOneOf(String s, String... l) { for (String x : l) if (startsWith(s, x)) return true; return false; } static boolean startsWithOneOf(String s, Matches m, String... l) { for (String x : l) if (startsWith(s, x, m)) return true; return false; } static boolean isAGIBlueDomain(String domain) { return domainIsUnder(domain, theAGIBlueDomain()); } static String hostNameFromURL(String url) { try { return new URL(url).getHost(); } catch (Exception __e) { throw rethrow(__e); } } static HashMap> callMC_cache = new HashMap(); static String callMC_key; static Method callMC_value; // varargs assignment fixer for a single string array argument static Object callMC(String method, String[] arg) { return callMC(method, new Object[] {arg}); } static Object callMC(String method, Object... args) { try { Method me; if (callMC_cache == null) callMC_cache = new HashMap(); // initializer time workaround synchronized(callMC_cache) { me = method == callMC_key ? callMC_value : null; } if (me != null) try { return invokeMethod(me, null, args); } catch (IllegalArgumentException e) { throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e); } List m; synchronized(callMC_cache) { m = callMC_cache.get(method); } if (m == null) { if (callMC_cache.isEmpty()) { callMC_makeCache(); m = callMC_cache.get(method); } if (m == null) throw fail("Method named " + method + " not found in main"); } int n = m.size(); if (n == 1) { me = m.get(0); synchronized(callMC_cache) { callMC_key = method; callMC_value = me; } try { return invokeMethod(me, null, args); } catch (IllegalArgumentException e) { throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e); } } for (int i = 0; i < n; i++) { me = m.get(i); if (call_checkArgs(me, args, false)) return invokeMethod(me, null, args); } throw fail("No method called " + method + " with arguments (" + joinWithComma(getClasses(args)) + ") found in main"); } catch (Exception __e) { throw rethrow(__e); } } static void callMC_makeCache() { synchronized(callMC_cache) { callMC_cache.clear(); Class _c = (Class) mc(), c = _c; while (c != null) { for (Method m : c.getDeclaredMethods()) if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) { makeAccessible(m); multiMapPut(callMC_cache, m.getName(), m); } c = c.getSuperclass(); } } } static Pair pair(A a, B b) { return new Pair(a, b); } static Pair pair(A a) { return new Pair(a, a); } static Object vmBus_wrapArgs(Object... args) { return empty(args) ? null : l(args) == 1 ? args[0] : args; } static void pcallFAll(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) pcallF(f, args); } static void pcallFAll(Iterator it, Object... args) { while (it.hasNext()) pcallF(it.next(), args); } static Set vm_busListeners_live_cache; static Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache; } static Set vm_busListeners_live_load() { return vm_generalIdentityHashSet("busListeners"); } static Map vm_busListenersByMessage_live_cache; static Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache; } static Map vm_busListenersByMessage_live_load() { return vm_generalHashMap("busListenersByMessage"); } static boolean endsWithIgnoreCase(String a, String b) { int la = l(a), lb = l(b); return la >= lb && regionMatchesIC(a, la-lb, b, 0, lb); } static boolean endsWithIgnoreCase(String a, String b, Matches m) { if (!endsWithIgnoreCase(a, b)) return false; m.m = new String[] { substring(a, 0, l(a)-l(b)) }; return true; } static BufferedReader bufferedReader(Reader r) { return bufferedReader(r, 8192); } static BufferedReader bufferedReader(Reader r, int bufSize) { return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r, bufSize), r); } static CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) { class IFF2 extends CloseableIterableIterator { A a; boolean done = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } void getNext() { if (done || a != null) return; a = f.get(); done = a == null; } public void close() throws Exception { if (closeable != null) closeable.close(); } }; return new IFF2(); } static String readLineFromReaderWithClose(BufferedReader r) { try { String s = r.readLine(); if (s == null) r.close(); return s; } catch (Exception __e) { throw rethrow(__e); } } static AutoCloseable _wrapIOCloseable(final AutoCloseable c) { return c == null ? null : new AutoCloseable() { public String toString() { return "c.close();\r\n _registerIO(c, null, false);"; } public void close() throws Exception { c.close(); _registerIO(c, null, false); }}; } static A _registerIOWrap(A wrapper, Object wrapped) { return wrapper; } static FileInputStream newFileInputStream(File path) throws IOException { return newFileInputStream(path.getPath()); } static FileInputStream newFileInputStream(String path) throws IOException { FileInputStream f = new FileInputStream(path); _registerIO(f, path, true); return f; } static int gzInputStream_defaultBufferSize = 65536; static GZIPInputStream gzInputStream(File f) { try { return gzInputStream(new FileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } static GZIPInputStream gzInputStream(File f, int bufferSize) { try { return gzInputStream(new FileInputStream(f), bufferSize); } catch (Exception __e) { throw rethrow(__e); } } static GZIPInputStream gzInputStream(InputStream in) { return gzInputStream(in, gzInputStream_defaultBufferSize); } static GZIPInputStream gzInputStream(InputStream in, int bufferSize) { try { return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in); } catch (Exception __e) { throw rethrow(__e); } } // f : Matcher -> S static String regexReplace(String s, String pat, Object f) { Matcher m = Pattern.compile(pat).matcher(s); return regexReplace(m, f); } static String regexReplace(Matcher m, Object f) { StringBuffer buf = new StringBuffer(); while (m.find()) m.appendReplacement(buf, m.quoteReplacement(str(callF(f, m)))); m.appendTail(buf); return str(buf); } static Matcher regexpMatcherIC(String pat, String s) { return compileRegexpIC(pat).matcher(unnull(s)); } static String actualUserHome_value; static String actualUserHome() { if (actualUserHome_value == null) { if (isAndroid()) actualUserHome_value = "/storage/emulated/0/"; else actualUserHome_value = System.getProperty("user.home"); } return actualUserHome_value; } static File actualUserHome(String sub) { return newFile(new File(actualUserHome()), sub); } static File userDir() { return new File(userHome()); } static File userDir(String path) { return new File(userHome(), path); } static String multiLineQuoteWithSpaces(String s) { return multiLineQuote(" " + s + " "); } static HashSet litset(A... items) { return lithashset(items); } static File programDir_mine; // set this to relocate program's data static File programDir() { return programDir(getProgramID()); } 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; } static File programDir(String snippetID, String subPath) { return new File(programDir(snippetID), subPath); } static A[] newObjectArrayOfSameType(A[] a, int n) { return (A[]) Array.newInstance(a.getClass().getComponentType(), n); } static List newSubList(List l, int startIndex, int endIndex) { return cloneList(subList(l, startIndex, endIndex)); } static List newSubList(List l, int startIndex) { return cloneList(subList(l, startIndex)); } static List tok_combineRoundOrCurlyBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eqOneOf(t, "{", "(")) { int j = findEndOfBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j-1; } else l.add(t); } return l; } static List javaTokNPunctuation_bracketsInC(String s) { List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { int j = i; String t; char c; while (j < l(tok) && l(t = tok.get(j)) == 1 && !Character.isLetterOrDigit(c = t.charAt(0)) && "{}()".indexOf(c) < 0) j += 2; if (j > i) // j points to next C token after mergeable stuff replaceSubList(tok, i-1, j, ll(joinSubList(tok, i-1, j))); } return tok; } static List javaTokForStructure(String s) { return javaTok_noMLS(s); } static String structure_addTokenMarkers(String s) { return join(structure_addTokenMarkers(javaTokForStructure(s))); } static List structure_addTokenMarkers(List tok) { // find references TreeSet refs = new TreeSet(); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (t.startsWith("t") && isInteger(t.substring(1))) refs.add(parseInt(t.substring(1))); } if (empty(refs)) return tok; // add markers for (int i : refs) { int idx = i*2+1; if (idx >= l(tok)) continue; // broken structure String t = ""; if (endsWithLetterOrDigit(tok.get(idx-1))) t = " "; tok.set(idx, t + "m" + i + " " + tok.get(idx)); } return tok; } static String jreplace(String s, String in, String out) { return jreplace(s, in, out, null); } static String jreplace(String s, String in, String out, Object condition) { List tok = javaTok(s); return jreplace(tok, in, out, condition) ? join(tok) : s; } // leaves tok properly tokenized // returns true iff anything was replaced static boolean jreplace(List tok, String in, String out) { return jreplace(tok, in, out, false, true, null); } static boolean jreplace(List tok, String in, String out, Object condition) { return jreplace(tok, in, out, false, true, condition); } static boolean jreplace(List tok, String in, String out, IF2, Integer, Boolean> condition) { return jreplace(tok, in, out, (Object) condition); } static boolean jreplace(List tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) { String[] toks = javaTokForJFind_array(in); int lTokin = toks.length*2+1; boolean anyChange = false; int i = -1; for (int n = 0; n < 10000; n++) { // TODO: don't need this check anymore i = findCodeTokens(tok, i+1, ignoreCase, toks, condition); if (i < 0) return anyChange; List subList = tok.subList(i-1, i+lTokin-1); // N to N String expansion = jreplaceExpandRefs(out, subList); int end = i+lTokin-2; clearAllTokens(tok, i, end); // C to C tok.set(i, expansion); if (reTok) // would this ever be false?? reTok(tok, i, end); i = end; anyChange = true; } throw fail("woot? 10000! " + quote(in) + " => " + quote(out)); } static boolean jreplace_debug = false; static Object pcallFAll_returnFirstNotNull(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) { Object __1= pcallF(f, args); if (__1 != null) return __1; } return null; } static Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) { while (it.hasNext()) { Object __2= pcallF(it.next(), args); if (__2 != null) return __2; } return null; } static String assertIsIdentifier(String s) { if (!isIdentifier(s)) throw fail("Not an identifier: " + quote(s)); return s; } static String assertIsIdentifier(String msg, String s) { if (!isIdentifier(s)) throw fail(msg + " - Not an identifier: " + quote(s)); return s; } static Object vm_generalMap_get(Object key) { return vm_generalMap().get(key); } static A[] makeArray(Class type, int n) { return (A[]) Array.newInstance(type, n); } static A getWeakRef(Reference ref) { return ref == null ? null : ref.get(); } static boolean odd(int i) { return (i & 1) != 0; } static boolean odd(long i) { return (i & 1) != 0; } static boolean odd(BigInteger i) { return odd(toInt(i)); } // i must point at the (possibly imaginary) opening bracket (any of the 3 types, not type parameters) // index returned is index of closing bracket + 1 static int findEndOfBracketPart2(List cnc, int i) { int j = i+2, level = 1; while (j < cnc.size()) { if (eqOneOf(cnc.get(j), "{", "(", "[")) ++level; else if (eqOneOf(cnc.get(j), "}", ")", "]")) --level; if (level == 0) return j+1; ++j; } return cnc.size(); } static HashSet lithashset(A... items) { HashSet set = new HashSet(); for (A a : items) set.add(a); return set; } static String shortenSnippetID(String snippetID) { if (snippetID.startsWith("#")) snippetID = snippetID.substring(1); String httpBlaBla = "http://tinybrain.de/"; if (snippetID.startsWith(httpBlaBla)) snippetID = snippetID.substring(httpBlaBla.length()); return "" + parseLong(snippetID); } static 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)); } }); } static A proxy(Object target, Class intrface) { return proxy(intrface, target); } static String md5(String text) { try { if (text == null) return "-"; return bytesToHex(md5_impl(toUtf8(text))); // maybe different than the way PHP does it... } catch (Exception __e) { throw rethrow(__e); } } static String md5(byte[] data) { if (data == null) return "-"; return bytesToHex(md5_impl(data)); } static byte[] md5_impl(byte[] data) { try { return MessageDigest.getInstance("MD5").digest(data); } catch (Exception __e) { throw rethrow(__e); } } static String md5(File file) { return md5OfFile(file); } static String fileNameEncode_safeChars = " ()[]#,!"; static String fileNameEncode(String s) { StringBuilder buf = new StringBuilder(); int n = l(s); for (int i = 0; i < n; i++) { char c = s.charAt(i); if (contains(fileNameEncode_safeChars, c)) buf.append(c); else buf.append(urlencode(str(c))); } return str(buf); } 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); } } static List collectField(Iterable c, String field) { List l = new ArrayList(); if (c != null) for (Object a : c) l.add(getOpt(a, field)); return l; } static List collectField(String field, Iterable c) { return collectField(c, field); } 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') { // ok } else return false; } return true; } static boolean networkAllowanceTest(String url) { return isAllowed("networkAllowanceTest", url); } static final boolean loadPageThroughProxy_enabled = false; static String loadPageThroughProxy(String url) { return null; } 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; } static void sleepSeconds(double s) { if (s > 0) sleep(round(s*1000)); } static String tb_mainServer_default = "http://code.botcompany.de:8081"; static Object tb_mainServer_override; // func -> S static String tb_mainServer() { if (tb_mainServer_override != null) return (String) callF(tb_mainServer_override); return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default)); } static File tb_mainServer_file() { return getProgramFile("#1001638", "mainserver.txt"); } static boolean tb_mainServer_isDefault() { return eq(tb_mainServer(), tb_mainServer_default); } static A printWithTime(A a) { return printWithTime("", a); } static A printWithTime(String s, A a) { print(hmsWithColons() + ": " + s, a); return a; } static A getAndClearThreadLocal(ThreadLocal tl) { A a = tl.get(); tl.set(null); return a; } 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) { //printShortException(e); } } static Set keys(Map map) { return map == null ? new HashSet() : map.keySet(); } // convenience shortcut for keys_gen static Set keys(Object map) { return keys((Map) map); } static Set keys(MultiMap mm) { return mm.keySet(); } static Map vm_generalSubMap(Object name) { synchronized(get(javax(), "generalMap")) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = synchroMap()); return map; } } static InputStream urlConnection_getInputStream(URLConnection con) throws IOException { UnknownHostException lastException = null; for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) { 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; } static String toHex(byte[] bytes) { return bytesToHex(bytes); } static String toHex(byte[] bytes, int ofs, int len) { return bytesToHex(bytes, ofs, len); } static byte[] utf8(String s) { return toUtf8(s); } static URLConnection openConnection(String url) { try { return openConnection(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } static URLConnection openConnection(URL url) { try { ping(); callOpt(javax(), "recordOpenURLConnection", str(url)); return url.openConnection(); } catch (Exception __e) { throw rethrow(__e); } } 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)); if (o instanceof Boolean) return boolToInt(((Boolean) o)); throw fail("woot not int: " + getClassName(o)); } static int toInt(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } static URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) { con.setConnectTimeout(toInt(timeout)); con.setReadTimeout(toInt(timeout)); if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout) print("Warning: Timeouts not set by JDK."); return con; } static URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) { if (con.getConnectTimeout() == 0) { con.setConnectTimeout(toInt(timeout)); if (con.getConnectTimeout() != timeout) print("Warning: URL connect timeout not set by JDK."); } if (con.getReadTimeout() == 0) { con.setReadTimeout(toInt(timeout)); if (con.getReadTimeout() != timeout) print("Warning: URL read timeout not set by JDK."); } return con; } static byte[] convertToPNG(BufferedImage img) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ImageIO.write(img, "png", stream); return stream.toByteArray(); } catch (Exception __e) { throw rethrow(__e); } } static String postPage(String url, Object... params) { return doPost(litmap(params), url); } static boolean isImageServerSnippet(long id) { return id >= 1100000 && id < 1200000; } static String imageServerLink(String md5OrID) { if (possibleMD5(md5OrID)) return "https://botcompany.de/images/md5/" + md5OrID; return imageServerLink(parseSnippetID(md5OrID)); } static String imageServerLink(long id) { return "https://botcompany.de/images/" + id; } static Map cloneMap(Map map) { if (map == null) return new HashMap(); // assume mutex is equal to map synchronized(map) { return map instanceof TreeMap ? new TreeMap((TreeMap) map) // copies comparator : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map); } } static List cloneMap(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : cloneList(l)) x.add(f.get(o)); return x; } static LinkedHashMap asLinkedHashMap(Map map) { if (map instanceof LinkedHashMap) return (LinkedHashMap) map; LinkedHashMap m = new LinkedHashMap(); if (map != null) synchronized(collectionMutex(map)) { m.putAll(map); } return m; } static Object[] mapToObjectArray(Map map) { List l = new ArrayList(); for (Object o : keys(map)) { l.add(o); l.add(map.get(o)); } return toObjectArray(l); } static Object[] mapToObjectArray(Object f, Collection l) { int n = l(l); Object[] array = new Object[n]; if (n != 0) { Iterator it = iterator(l); for (int i = 0; i < n; i++) array[i] = callF(f, it.next()); } return array; } static Object[] mapToObjectArray(Object f, Object[] l) { int n = l(l); Object[] array = new Object[n]; for (int i = 0; i < n; i++) array[i] = callF(f, l[i]); return array; } static Object[] mapToObjectArray(Collection l, IF1 f) { return mapToObjectArray(f, l); } static A lookupIgnoreCase(Map map, String key) { for (String s : map.keySet()) if (eqic(s, key)) return map.get(s); return null; } static List lookupIgnoreCase(MultiMap map, String key) { for (String s : map.keySet()) if (eqic(s, key)) return map.get(s); return litlist(); } static List scanLog(String progID, String fileName) { return scanLog(getProgramFile(progID, fileName)); } static List scanLog(String fileName) { return scanLog(getProgramFile(fileName)); } static List scanLog(File file) { List l = new ArrayList(); for (File f : concatLists(earlierPartsOfLogFile(file), ll(file))) for (String s : toLines(file)) if (isProperlyQuoted(s)) l.add(unquote(s)); return l; } static Map unstructureMap(String s) { return (Map) unstructure(s); } static boolean getHtmlTagParameters_debug = false; static Map getHtmlTagParameters(String tag) { if (empty(tag)) return null; List tok = codeTokens(tok_joinMinusIdentifiers(htmlFineTok(tag))); if (getHtmlTagParameters_debug) printStruct(tok); assertEquals("<", tok.get(0)); int i = 1; if (eq(tok.get(1), "/")) ++i; String name = tok.get(i++); if (!isMinusIdentifier(name)) throw fail(tag + " (" + name + ")"); Map map = new HashMap(); while (i < l(tok)) { String t = tok.get(i); if (eqOneOf(t, "/", ">")) break; if (!isMinusIdentifier(t)) throw fail(tag + " (" + t + ")"); ++i; String value = "1"; if (eq(tok.get(i), "=")) { ++i; value = htmlunquote(tok.get(i++)); } map.put(t, value); } return map; } static List mapToLines(Map map) { List l = new ArrayList(); for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key))); return l; } static String mapToLines(Map map, Object f) { return lines(map(map, f)); } static String mapToLines(Object f, Map map) { return lines(map(map, f)); } static String mapToLines(Object f, Iterable l) { return lines(map(f, l)); } static String mapToLines(Iterable l, IF1 f) { return mapToLines((Object) f, l); } static String mapToLines(IF1 f, Iterable l) { return mapToLines((Object) f, l); } static String mapToLines(Map map, IF2 f) { return lines(map(map, f)); } static TimeZone localTimeZone() { return getTimeZone(standardTimeZone()); // TimeZone.getDefault()? } static void removeSubList(List l, int from, int to) { if (l != null) subList(l, from, to).clear(); } static void removeSubList(List l, int from) { if (l != null) subList(l, from).clear(); } 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); } static List mechList_opt(String name) { return mechList_opt_tlft(name); } static boolean preferCached = false; static boolean loadSnippet_debug = false; static ThreadLocal loadSnippet_silent = new ThreadLocal(); static ThreadLocal loadSnippet_publicOnly = new ThreadLocal(); static int loadSnippet_timeout = 30000; static String loadSnippet(String snippetID) { try { if (snippetID == null) return null; return loadSnippet(parseSnippetID(snippetID), preferCached); } catch (Exception __e) { throw rethrow(__e); } } static String loadSnippet(String snippetID, boolean preferCached) throws IOException { return loadSnippet(parseSnippetID(snippetID), preferCached); } static IF1 loadSnippet; static String loadSnippet(long snippetID) { return loadSnippet != null ? loadSnippet.get(snippetID) : loadSnippet_base(snippetID); } final static String loadSnippet_fallback(IF1 _f, long snippetID) { return _f != null ? _f.get(snippetID) : loadSnippet_base(snippetID); } static String loadSnippet_base(long snippetID) { try { return loadSnippet(snippetID, preferCached); } catch (Exception __e) { throw rethrow(__e); } } static String loadSnippet(long snippetID, boolean preferCached) throws IOException { String text; if (isLocalSnippetID(snippetID)) return loadLocalSnippet(snippetID); IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadSnippet(fsI(snippetID)); // boss bot disabled for now for shorter transpilations /*text = getSnippetFromBossBot(snippetID); if (text != null) return text;*/ initSnippetCache(); text = DiskSnippetCache_get(snippetID); if (preferCached && text != null) return text; try { if (loadSnippet_debug && text != null) System.err.println("md5: " + md5(text)); String url = tb_mainServer() + "/getraw.php?id=" + snippetID + "&utf8=1"; if (nempty(text)) url += "&md5=" + md5(text); if (!isTrue(loadSnippet_publicOnly.get())) url += standardCredentials(); String text2 = loadSnippet_loadFromServer(url); boolean same = eq(text2, "==*#*=="); if (loadSnippet_debug) print("loadSnippet: same=" + same); if (!same) text = text2; } catch (RuntimeException e) { e.printStackTrace(); throw new IOException("Snippet #" + snippetID + " not found or not public"); } try { initSnippetCache(); DiskSnippetCache_put(snippetID, text); } catch (IOException e) { System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")"); } return text; } static File DiskSnippetCache_dir; public static void initDiskSnippetCache(File dir) { DiskSnippetCache_dir = dir; dir.mkdirs(); } public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException { return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null); } private static File DiskSnippetCache_getFile(long snippetID) { return new File(DiskSnippetCache_dir, "" + snippetID); } public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException { saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet); } public static File DiskSnippetCache_getDir() { return DiskSnippetCache_dir; } public static void initSnippetCache() { if (DiskSnippetCache_dir == null) initDiskSnippetCache(getGlobalCache()); } static String loadSnippet_loadFromServer(String url) { Integer oldTimeout = setThreadLocal(loadPage_forcedTimeout_byThread, loadSnippet_timeout); try { return isTrue(loadSnippet_silent.get()) ? loadPageSilently(url) : loadPage(url); } finally { loadPage_forcedTimeout_byThread.set(oldTimeout); } } static int jfind(String s, String in) { return jfind(javaTok(s), in); } static int jfind(List tok, String in) { return jfind(tok, 1, in); } static int jfind(List tok, int startIdx, String in) { return jfind(tok, startIdx, in, null); } static int jfind(List tok, String in, Object condition) { return jfind(tok, 1, in, condition); } static int jfind(List tok, int startIdx, String in, Object condition) { //LS tokin = jfind_preprocess(javaTok(in)); return jfind(tok, startIdx, javaTokForJFind_array(in), condition); } // assumes you preprocessed tokin static int jfind(List tok, List tokin) { return jfind(tok, 1, tokin); } static int jfind(List tok, int startIdx, List tokin) { return jfind(tok, startIdx, tokin, null); } static int jfind(List tok, int startIdx, String[] tokinC, Object condition) { return findCodeTokens(tok, startIdx, false, tokinC, condition); } static int jfind(List tok, int startIdx, List tokin, Object condition) { return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition); } 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; } static List jfindAll(List tok, String pat) { return jfindAll(tok, jfind_preprocess(javaTok(pat))); } // tokPat must be jfind_preprocess'd static List jfindAll(List tok, List tokPat) { String[] toks = toStringArray(codeTokensOnly(tokPat)); int i = -1; List l = new ArrayList(); while ((i = findCodeTokens(tok, i+1, false, toks)) >= 0) l.add(i); return l; } static String firstJavaToken(String s) { if (s == null) return null; int l = s.length(); int j = 0; char c, d; // scan for whitespace 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 (j >= l) return null; int i = j; c = s.charAt(i); d = i+1 >= l ? '\0' : s.charAt(i+1); // scan for non-whitespace if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors ++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)); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } 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; return quickSubstring(s, i, j); } static String fsIOpt(String s) { return formatSnippetIDOpt(s); } static String loadCachedTranspilation(String id) { try { return loadTextFilePossiblyGZipped(getCachedTranspilationFile(id)); } catch (Throwable __e) { return null; } } static boolean machineIsOffline() { return isFalse(callF(vmGeneralMap_get("areWeOnline"))); } static boolean isOfflineMode() { return eq("1", trim(loadProgramTextFile("#1005806", "offline-mode"))); } static boolean isLocalSnippet(String snippetID) { return isLocalSnippetID(snippetID); } static boolean isLocalSnippet(long snippetID) { return isLocalSnippetID(snippetID); } static String getServerTranspiled(String snippetID) { return getServerTranspiled(snippetID, null); } static boolean getServerTranspiled_printStackTrace = false; // returns "SAME" if md5 matches static String getServerTranspiled(String snippetID, String expectedMD5) { try { if (getServerTranspiled_printStackTrace) printStackTrace(); long id = parseSnippetID(snippetID); /*S t = getTranspilationFromBossBot(id); if (t != null) return t;*/ String text = loadPage_utf8(tb_mainServer() + "/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id + "&utf8=1" + (l(expectedMD5) > 1 ? "&md5=" + urlencode(expectedMD5) : "") + standardCredentials()); if (nempty(text) && neq(text, "SAME")) saveTranspiledCode(snippetID, text); return text; } catch (Exception __e) { throw rethrow(__e); } } static void printExceptionShort(Throwable e) { print(exceptionToStringShort(e)); } static B mapPut_returnValue(Map map, A key, B value) { mapPut(map, key, value); return value; } static boolean warn_on = true; static ThreadLocal> warn_warnings = new ThreadLocal(); static void warn(String s) { if (warn_on) print("Warning: " + s); } static void warn(String s, List warnings) { warn(s); if (warnings != null) warnings.add(s); addToCollection(warn_warnings.get(), s); } 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); } } static String getSnippetTitle(long id) { return getSnippetTitle(fsI(id)); } static String defaultThreadName_name; static String defaultThreadName() { if (defaultThreadName_name == null) defaultThreadName_name = "A thread by " + programID(); return defaultThreadName_name; } static Runnable wrapAsActivity(Object r) { return toRunnable(r); } // runnable = Runnable or String (method name) static Thread newThread(Object runnable) { return new Thread(_topLevelErrorHandling(toRunnable(runnable))); } static Thread newThread(Object runnable, String name) { if (name == null) name = defaultThreadName(); return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name); } static Thread newThread(String name, Object runnable) { return newThread(runnable, name); } static Runnable toRunnable(final Object o) { if (o instanceof Runnable) return (Runnable) o; return new Runnable() { public void run() { try { callF(o) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; }}; } static Map _registerThread_threads; static Object _onRegisterThread; // voidfunc(Thread) static Thread _registerThread(Thread t) { if (_registerThread_threads == null) _registerThread_threads = newWeakHashMap(); _registerThread_threads.put(t, true); vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc())); callF(_onRegisterThread, t); return t; } static void _registerThread() { _registerThread(Thread.currentThread()); } static List nlTok(String s) { return javaTokPlusPeriod(s); } static boolean domainIsUnder(String domain, String mainDomain) { return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain); } static String theAGIBlueDomain() { return "agi.blue"; } static List getClasses(Object[] array) { List l = emptyList(l(array)); for (Object o : array) l.add(_getClass(o)); return l; } static void multiMapPut(Map> map, A a, B b) { List l = map.get(a); if (l == null) map.put(a, l = new ArrayList()); l.add(b); } static void multiMapPut(MultiMap mm, A key, B value) { if (mm != null && key != null && value != null) mm.put(key, value); } static Object pcallF(Object f, Object... args) { return pcallFunction(f, args); } static A pcallF(F0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { return null; } } static B pcallF(F1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { return null; } } static void pcallF(VF1 f, A a) { try { if (f != null) f.get(a); } catch (Throwable __e) { _handleException(__e); } } static Set vm_generalIdentityHashSet(Object name) { synchronized(get(javax(), "generalMap")) { Set set = (Set) (vm_generalMap_get(name)); if (set == null) vm_generalMap_put(name, set = syncIdentityHashSet()); return set; } } static Map vm_generalHashMap(Object name) { synchronized(get(javax(), "generalMap")) { Map m = (Map) (vm_generalMap_get(name)); if (m == null) vm_generalMap_put(name, m = syncHashMap()); return m; } } static String multiLineQuote(String s) { for (int i = 0; ; i++) { String closer = "]" + rep('=', i) + "]"; if (!contains(s, closer)) return "[" + rep('=', i) + "[" + s + closer; } } static boolean sameSnippetID(String a, String b) { if (!isSnippetID(a) || !isSnippetID(b)) return false; return parseSnippetID(a) == parseSnippetID(b); } static volatile String caseID_caseID; static String caseID() { return caseID_caseID; } static void caseID(String id) { caseID_caseID = id; } // i must point at the (possibly imaginary) opening bracket (any of the 2 types, not type parameters) // index returned is index of closing bracket + 1 static int findEndOfBracketPart(List cnc, int i) { int j = i+2, level = 1; while (j < cnc.size()) { if (eqOneOf(cnc.get(j), "{", "(")) ++level; else if (eqOneOf(cnc.get(j), "}", ")")) --level; if (level == 0) return j+1; ++j; } return cnc.size(); } static List replaceSubList(List l, List x, List y) { return replaceSublist(l, x, y); } static List replaceSubList(List l, int fromIndex, int toIndex, List y) { return replaceSublist(l, fromIndex, toIndex, y); } static List javaTok_noMLS(String s) { 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; // scan for whitespace 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); // scan for non-whitespace if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { int c2 = s.charAt(j); if (c2 == opener || c2 == '\n' && opener == '\'') { // allow multi-line strings, but not for ' ++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))); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } else ++j; tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static int parseInt(String s) { return emptyString(s) ? 0 : Integer.parseInt(s); } static int parseInt(char c) { return Integer.parseInt(str(c)); } static Map javaTokForJFind_array_cache = synchronizedMRUCache(1000); 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; } static int findCodeTokens(List tok, String... tokens) { return findCodeTokens(tok, 1, false, tokens); } static int findCodeTokens(List tok, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, 1, ignoreCase, tokens); } static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, startIdx, ignoreCase, tokens, null); } static HashSet findCodeTokens_specials = lithashset("*", "", "", "", "\\*"); static int findCodeTokens_bails, findCodeTokens_nonbails; static interface findCodeTokens_Matcher { boolean get(String token); } static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) { int end = tok.size()-tokens.length*2+2, nTokens = tokens.length; int i = startIdx | 1; // bail out early if first token not found (works great with IndexedList) String firstToken = tokens[0]; if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) { // quickly scan for first token while (i < end && !firstToken.equals(tok.get(i))) i += 2; } findCodeTokens_Matcher[] matchers = new findCodeTokens_Matcher[nTokens]; for (int j = 0; j < nTokens; j++) { String p = tokens[j]; findCodeTokens_Matcher matcher; if (p.equals("*")) matcher = t -> true; else if (p.equals("")) matcher = t -> isQuoted(t); else if (p.equals("")) matcher = t -> isIdentifier(t); else if (p.equals("")) matcher = t -> isInteger(t); else if (p.equals("\\*")) matcher = t -> t.equals("*"); else if (ignoreCase) matcher = t -> eqic(p, t); else matcher = t -> t.equals(p); matchers[j] = matcher; } outer: for (; i < end; i += 2) { for (int j = 0; j < nTokens; j++) if (!matchers[j].get(tok.get(i+j*2))) continue outer; if (condition == null || checkTokCondition(condition, tok, i-1)) // pass N index return i; } return -1; } // "$1" is first code token, "$2" second code token etc. static String jreplaceExpandRefs(String s, List tokref) { if (!contains(s, '$')) return s; List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (t.startsWith("$") && isInteger(t.substring(1))) { String x = tokref.get(-1+parseInt(t.substring(1))*2); tok.set(i, x); } else if (t.equals("\\")) { tok.set(i, ""); i += 2; } } return join(tok); } static void clearAllTokens(List tok) { for (int i = 0; i < tok.size(); i++) tok.set(i, ""); } static void clearAllTokens(List tok, int i, int j) { for (; i < j; i++) tok.set(i, ""); } static List reTok(List tok) { replaceCollection(tok, javaTok(tok)); return tok; } static List reTok(List tok, int i) { return reTok(tok, i, i+1); } static List reTok(List tok, int i, int j) { // extend i to an "N" token // and j to "C" (so j-1 is an "N" token) i = max(i & ~1, 0); j = min(l(tok), j | 1); if (i >= j) return tok; List t = javaTok(joinSubList(tok, i, j)); replaceListPart(tok, i, j, t); // fallback to safety // reTok(tok); return tok; } static List reTok(List tok, IntRange r) { if (r != null) reTok(tok, r.start, r.end); return tok; } static Map vm_generalMap_map; static Map vm_generalMap() { if (vm_generalMap_map == null) vm_generalMap_map = (Map) get(javax(), "generalMap"); return vm_generalMap_map; } static boolean isInstance(Class type, Object arg) { return type.isInstance(arg); } static boolean md5OfFile_verbose = false; static String md5OfFile(String path) { return md5OfFile(newFile(path)); } static String md5OfFile(File f) { try { if (!f.exists()) return "-"; if (md5OfFile_verbose) print("Getting MD5 of " + f); MessageDigest md5 = MessageDigest.getInstance("MD5"); FileInputStream in = new FileInputStream(f); try { byte buf[] = new byte[65536]; int l; while (true) { l = in.read(buf); if (l <= 0) break; md5.update(buf, 0, l); } return bytesToHex(md5.digest()); } finally { _close(in); }} catch (Exception __e) { throw rethrow(__e); } } static volatile Object isAllowed_function; // func(S, O[]) -> bool static volatile boolean isAllowed_all = true; static boolean isAllowed(String askingMethod, Object... args) { // check on VM level Object f = vm_generalMap_get("isAllowed_function"); if (f != null && !isTrue(callF(f, askingMethod, args))) return false; // check locally return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args)); } static String baseClassName(String className) { return substring(className, className.lastIndexOf('.')+1); } static String baseClassName(Object o) { return baseClassName(getClassName(o)); } static String prependIfNempty(String prefix, String s) { return empty(s) ? unnull(s) : prefix + s; } static volatile boolean sleep_noSleep = false; static void sleep(long ms) { ping(); if (ms < 0) return; // allow spin locks if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread"); try { Thread.sleep(ms); } catch (Exception e) { throw new RuntimeException(e); } } static void sleep() { try { if (sleep_noSleep) throw fail("nosleep"); print("Sleeping."); sleepQuietly(); } catch (Exception __e) { throw rethrow(__e); } } static long round(double d) { return Math.round(d); } static String hmsWithColons() { return hmsWithColons(now()); } static String hmsWithColons(long time) { return new SimpleDateFormat("HH:mm:ss").format(time); } static String getComputerID_quick() { return computerID(); } static Object vm_generalMap_put(Object key, Object value) { return mapPutOrRemove(vm_generalMap(), key, value); } static String joinNemptiesWithColonSpace(String... strings) { return joinNempties(": ", strings); } static String joinNemptiesWithColonSpace(Collection strings) { return joinNempties(": ", strings); } static String tryToReadErrorStreamFromURLConnection(URLConnection conn) { try { if (conn instanceof HttpURLConnection) return stream2string(((HttpURLConnection) conn).getErrorStream()); // TODO: ensure some max length return null; } catch (Throwable __e) { return null; } } static int boolToInt(boolean b) { return b ? 1 : 0; } static ThreadLocal doPost_silently = new ThreadLocal(); static ThreadLocal doPost_timeout = new ThreadLocal(); static ThreadLocal> doPost_extraHeaders = new ThreadLocal(); static String doPost(Map urlParameters, String url) { return doPost(makePostData(urlParameters), url); } static String doPost(String urlParameters, String url) { try { URL _url = new URL(url); ping(); return doPost(urlParameters, _url.openConnection(), _url); } catch (Exception __e) { throw rethrow(__e); } } static String doPost(String urlParameters, URLConnection conn, URL url) { try { boolean silently = isTrue(optParam(doPost_silently)); Long timeout = optParam(doPost_timeout); Map extraHeaders = optPar(doPost_extraHeaders); setHeaders(conn); for (String key : keys(extraHeaders)) { conn.setRequestProperty(key, extraHeaders.get(key)); } int l = lUtf8(urlParameters); if (!silently) print("Sending POST request: " + hideCredentials(url) + " (" + l + " bytes)"); // connect and do POST if (timeout != null) setURLConnectionTimeouts(conn, timeout); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", str(l)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); writer.write(urlParameters); writer.flush(); String contents = loadPage_utf8(conn, url, false); writer.close(); return contents; } catch (Exception __e) { throw rethrow(__e); } } static boolean possibleMD5(String s) { return isMD5(s); } static Object[] toObjectArray(Collection c) { List l = asList(c); return l.toArray(new Object[l.size()]); } static ArrayList litlist(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } static List earlierPartsOfLogFile(File file) { String name = file.getName() + ".part"; try { Matches m = new Matches(); TreeMap map = new TreeMap(); for (File p : listFiles(file.getParent())) { try { String n = p.getName(); if (startsWith(n, name, m)) map.put(parseFirstInt(m.rest()), p); } catch (Throwable __e) { _handleException(__e); }} return valuesList(map); } catch (Throwable e) { _handleException(e); return ll(); } } static boolean isProperlyQuoted(String s) { return s.length() >= 2 && s.startsWith("\"") && s.endsWith("\"") && (!s.endsWith("\\\"") || s.endsWith("\\\\\"")) && !containsNewLine(s); } static Object unstructure(String text) { return unstructure(text, false); } static Object unstructure(String text, final boolean allDynamic) { return unstructure(text, allDynamic, null); } static int structure_internStringsLongerThan = 50; static int unstructure_unquoteBufSize = 100; static int unstructure_tokrefs; // stats abstract static class unstructure_Receiver { abstract void set(Object o); } // classFinder: func(name) -> class (optional) static Object unstructure(String text, boolean allDynamic, Object classFinder) { if (text == null) return null; return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder); } static Object unstructure_reader(BufferedReader reader) { return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null); } static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object _classFinder) { final boolean debug = unstructure_debug; final class X { int i = -1; final Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder(); HashMap refs = new HashMap(); HashMap tokrefs = new HashMap(); HashSet concepts = new HashSet(); HashMap classesMap = new HashMap(); List stack = new ArrayList(); String curT; char[] unquoteBuf = new char[unstructure_unquoteBufSize]; Class findAClass(String fullClassName) { return classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName); } String unquote(String s) { return unquoteUsingCharArray(s, unquoteBuf); } // look at current token String t() { return curT; } // get current token, move to next String tpp() { String t = curT; consume(); return t; } void parse(final unstructure_Receiver out) { String t = t(); int refID = 0; if (structure_isMarker(t, 0, l(t))) { refID = parseInt(t.substring(1)); consume(); } final int _refID = refID; // if (debug) print("parse: " + quote(t)); final int tokIndex = i; parse_inner(refID, tokIndex, new unstructure_Receiver() { void set(Object o) { if (_refID != 0) refs.put(_refID, o); if (o != null) tokrefs.put(tokIndex, o); out.set(o); } }); } void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) { String t = t(); // if (debug) print("parse_inner: " + quote(t)); Class c = classesMap.get(t); if (c == null) { if (t.startsWith("\"")) { String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan); out.set(s); return; } if (t.startsWith("'")) { out.set(unquoteCharacter(tpp())); return; } if (t.equals("bigint")) { out.set(parseBigInt()); return; } if (t.equals("d")) { out.set(parseDouble()); return; } if (t.equals("fl")) { out.set(parseFloat()); return; } if (t.equals("sh")) { consume(); t = tpp(); if (t.equals("-")) { t = tpp(); out.set((short) (-parseInt(t))); return; } out.set((short) parseInt(t)); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); //if (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t)); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("false") || t.equals("f")) { consume(); out.set(false); return; } if (t.equals("true") || t.equals("t")) { consume(); out.set(true); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); //if (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t)); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("File")) { consume(); File f = new File(unquote(tpp())); out.set(f); return; } if (t.startsWith("r") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = refs.get(ref); if (o == null) throw fail("unsatisfied back reference " + ref); out.set(o); return; } if (t.startsWith("t") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = tokrefs.get(ref); if (o == null) throw fail("unsatisfied token reference " + ref + " at " + tokIndex); out.set(o); return; } if (t.equals("hashset")) { parseHashSet(out); return; } if (t.equals("lhs")) { parseLinkedHashSet(out); return; } if (t.equals("treeset")) { parseTreeSet(out); return; } if (t.equals("ciset")) { parseCISet(out); return; } if (eqOneOf(t, "hashmap", "hm")) { consume(); parseMap(new HashMap(), out); return; } if (t.equals("lhm")) { consume(); parseMap(new LinkedHashMap(), out); return; } if (t.equals("tm")) { consume(); parseMap(new TreeMap(), out); return; } if (t.equals("cimap")) { consume(); parseMap(ciMap(), out); return; } if (t.equals("ll")) { consume(); { parseList(new LinkedList(), out); return; } } if (t.equals("syncLL")) { // legacy consume(); { parseList(synchroLinkedList(), out); return; } } if (t.equals("sync")) { consume(); { parse(new unstructure_Receiver() { void set(Object value) { if (value instanceof Map) { // Java 7 if (value instanceof NavigableMap) { out.set(Collections.synchronizedNavigableMap((NavigableMap) value)); return; } if (value instanceof SortedMap) { out.set(Collections.synchronizedSortedMap((SortedMap) value)); return; } { out.set(Collections.synchronizedMap((Map) value)); return; } } else { out.set(Collections.synchronizedList((List) value)); return; } } }); return; } } if (t.equals("{")) { parseMap(out); return; } if (t.equals("[")) { this.parseList(new ArrayList(), out); return; } if (t.equals("bitset")) { parseBitSet(out); return; } if (t.equals("array") || t.equals("intarray") || t.equals("dblarray")) { parseArray(out); return; } if (t.equals("ba")) { consume(); String hex = unquote(tpp()); out.set(hexToBytes(hex)); return; } if (t.equals("boolarray")) { consume(); int n = parseInt(tpp()); String hex = unquote(tpp()); out.set(boolArrayFromBytes(hexToBytes(hex), n)); return; } if (t.equals("class")) { out.set(parseClass()); return; } if (t.equals("l")) { parseLisp(out); return; } if (t.equals("null")) { consume(); out.set(null); return; } if (eq(t, "c")) { consume(); t = t(); assertTrue(isJavaIdentifier(t)); concepts.add(t); } // custom deserialization (new static method method) if (eq(t, "cu")) { consume(); t = tpp(); assertTrue(isJavaIdentifier(t)); String fullClassName = "main$" + t; Class _c = findAClass(fullClassName); if (_c == null) throw fail("Class not found: " + fullClassName); parse(new unstructure_Receiver() { void set(Object value) { out.set(call(_c, "_deserialize", value)); } }); return; } } if (eq(t, "j")) { consume("j"); out.set(parseJava()); return; } if (c == null && !isJavaIdentifier(t)) throw new RuntimeException("Unknown token " + (i+1) + ": " + quote(t)); // any other class name (or package name) consume(); String className, fullClassName; // Is it a package name? if (eq(t(), ".")) { consume(); className = fullClassName = t + "." + assertIdentifier(tpp()); } else { className = t; fullClassName = "main$" + t; } if (c == null) { // First, find class if (allDynamic) c = null; else c = findAClass(fullClassName); if (c != null) classesMap.put(className, c); } // Check if it has an outer reference boolean hasBracket = eq(t(), "("); if (hasBracket) consume(); boolean hasOuter = hasBracket && eq(t(), "this$1"); DynamicObject dO = null; Object o = null; final String thingName = t; if (c != null) { o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c); if (o instanceof DynamicObject) dO = (DynamicObject) o; } else { if (concepts.contains(t) && (c = findAClass("main$Concept")) != null) o = dO = (DynamicObject) nuEmptyObject(c); else dO = new DynamicObject(); dO.className = className; } // Save in references list early because contents of object // might link back to main object if (refID != 0) refs.put(refID, o != null ? o : dO); tokrefs.put(tokIndex, o != null ? o : dO); // NOW parse the fields! final LinkedHashMap fields = new LinkedHashMap(); // preserve order final Object _o = o; final DynamicObject _dO = dO; if (hasBracket) { stack.add(new Runnable() { public void run() { try { if (eq(t(), ",")) consume(); if (eq(t(), ")")) { consume(")"); objRead(_o, _dO, fields, hasOuter); out.set(_o != null ? _o : _dO); } else { final String key = unquote(tpp()); String t = tpp(); if (!eq(t, "=")) throw fail("= expected, got " + t + " after " + quote(key) + " in object " + thingName /*+ " " + sfu(fields)*/); stack.add(this); parse(new unstructure_Receiver() { void set(Object value) { fields.put(key, value); /*ifdef unstructure_debug print("Got field value " + value + ", next token: " + t()); endifdef*/ //if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef unstructure_debug\r\n print(\"in object values, token: \" + t())..."; }}); } else { objRead(o, dO, fields, hasOuter); out.set(o != null ? o : dO); } } void objRead(Object o, DynamicObject dO, Map fields, boolean hasOuter) { if (o != null) { if (dO != null) { setOptAllDyn(dO, fields); } else { setOptAll_pcall(o, fields); } if (hasOuter) fixOuterRefs(o); } else for (Map.Entry e : fields.entrySet()) setDynObjectValue(dO, intern(e.getKey()), e.getValue()); if (o != null) pcallOpt_noArgs(o, "_doneLoading"); } void parseSet(final Set set, final unstructure_Receiver out) { this.parseList(new ArrayList(), new unstructure_Receiver() { void set(Object o) { set.addAll((List) o); out.set(set); } }); } void parseLisp(final unstructure_Receiver out) { throw fail("class Lisp not included"); } void parseBitSet(final unstructure_Receiver out) { consume("bitset"); consume("{"); final BitSet bs = new BitSet(); stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); out.set(bs); } else { stack.add(this); parse(new unstructure_Receiver() { void set(Object o) { bs.set((Integer) o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n ..."; }}); } void parseList(final List list, final unstructure_Receiver out) { tokrefs.put(i, list); consume("["); stack.add(new Runnable() { public void run() { try { if (eq(t(), "]")) { consume(); out.set(list); } else { stack.add(this); parse(new unstructure_Receiver() { void set(Object o) { //if (debug) print("List element type: " + getClassName(o)); list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"]\")) {\r\n consume();\r\n ifdef unstructure_debug\r..."; }}); } void parseArray(final unstructure_Receiver out) { final String type = tpp(); consume("{"); final List list = new ArrayList(); stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); out.set( type.equals("intarray") ? toIntArray(list) : type.equals("dblarray") ? toDoubleArray(list) : list.toArray()); } else { stack.add(this); parse(new unstructure_Receiver() { void set(Object o) { list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(\r\n ..."; }}); } Object parseClass() { consume("class"); consume("("); String name = unquote(tpp()); consume(")"); Class c = allDynamic ? null : findAClass(name); if (c != null) return c; DynamicObject dO = new DynamicObject(); dO.className = "java.lang.Class"; name = dropPrefix("main$", name); dO.fieldValues.put("name", name); return dO; } Object parseBigInt() { consume("bigint"); consume("("); String val = tpp(); if (eq(val, "-")) val = "-" + tpp(); consume(")"); return new BigInteger(val); } Object parseDouble() { consume("d"); consume("("); String val = unquote(tpp()); consume(")"); return Double.parseDouble(val); } Object parseFloat() { consume("fl"); String val; if (eq(t(), "(")) { consume("("); val = unquote(tpp()); consume(")"); } else { val = unquote(tpp()); } return Float.parseFloat(val); } void parseHashSet(unstructure_Receiver out) { consume("hashset"); parseSet(new HashSet(), out); } void parseLinkedHashSet(unstructure_Receiver out) { consume("lhs"); parseSet(new LinkedHashSet(), out); } void parseTreeSet(unstructure_Receiver out) { consume("treeset"); parseSet(new TreeSet(), out); } void parseCISet(unstructure_Receiver out) { consume("ciset"); parseSet(ciSet(), out); } void parseMap(unstructure_Receiver out) { parseMap(new TreeMap(), out); } Object parseJava() { String j = unquote(tpp()); Matches m = new Matches(); if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m)) return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2))); else { warn("Unknown Java object: " + j); return null; } } void parseMap(final Map map, final unstructure_Receiver out) { consume("{"); stack.add(new Runnable() { boolean v = false; Object key; public void run() { if (v) { v = false; stack.add(this); if (!eq(tpp(), "=")) throw fail("= expected, got " + t() + " in map of size " + l(map)); parse(new unstructure_Receiver() { void set(Object value) { map.put(key, value); if (eq(t(), ",")) consume(); } }); } else { if (eq(t(), "}")) { consume("}"); out.set(map); } else { v = true; stack.add(this); parse(new unstructure_Receiver() { void set(Object o) { key = o; } }); } } // if v else } // run() }); } /*void parseSub(unstructure_Receiver out) { int n = l(stack); parse(out); while (l(stack) > n) stack }*/ void consume() { curT = tok.next(); ++i; } void consume(String s) { if (!eq(t(), s)) { /*S prevToken = i-1 >= 0 ? tok.get(i-1) : ""; S nextTokens = join(tok.subList(i, Math.min(i+2, tok.size()))); fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");*/ throw fail(quote(s) + " expected, got " + quote(t())); } consume(); } // outer wrapper function getting first token and unwinding the stack void parse_initial(unstructure_Receiver out) { consume(); // get first token parse(out); while (nempty(stack)) popLast(stack).run(); } } ThreadLocal tlLoading = dynamicObjectIsLoading_threadLocal(); Boolean b = tlLoading.get(); tlLoading.set(true); try { final Var v = new Var(); X x = new X(); x.parse_initial(new unstructure_Receiver() { void set(Object o) { v.set(o); } }); unstructure_tokrefs = x.tokrefs.size(); return v.get(); } finally { tlLoading.set(b); } } static boolean unstructure_debug = false; static List tok_joinMinusIdentifiers(List tok) { for (int i = 1; i+4 < l(tok); i += 2) if (isMinusIdentifier(get(tok, i)) && eq(get(tok, i+2), "-") && isIdentifier(get(tok, i+4))) { replaceSublist(tok, i, i+5, ll(join(subList(tok, i, i+5)))); i -= 2; } return tok; } static List htmlFineTok(String s) { List tok = new ArrayList(); int l = s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; // scan for whitespace 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 break; } tok.add(quickSubstring(s, i, j)); ++n; i = j; if (i >= l) break; c = s.charAt(i); d = i+1 >= l ? '\0' : s.charAt(i+1); // scan for non-whitespace if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings ++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)); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } else ++j; tok.add(quickSubstring(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static boolean isMinusIdentifier(String s) { if (empty(s)) return false; if (!Character.isJavaIdentifierStart(s.charAt(0)) && !s.startsWith("-")) return false; for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)) && s.charAt(i) != '-') return false; return true; } static String htmlunquote(String s) { if (s.startsWith("'") && s.endsWith("'") && s.length() >= 2 || s.startsWith("\"") && s.endsWith("\"") && s.length() >= 2) s = s.substring(1, s.length()-1); return htmldecode(s); } static TimeZone getTimeZone(String name) { return TimeZone.getTimeZone(name); } static String standardTimeZone_name = "Europe/Berlin"; static String standardTimeZone() { return standardTimeZone_name; } static int lastIndexOf(String a, String b) { return a == null || b == null ? -1 : a.lastIndexOf(b); } static int lastIndexOf(String a, char b) { return a == null ? -1 : a.lastIndexOf(b); } // starts searching from i-1 static int lastIndexOf(List l, int i, A a) { if (l == null) return -1; for (i = min(l(l), i)-1; i >= 0; i--) if (eq(l.get(i), a)) return i; return -1; } static List mechList_opt_tlft(String name) { return mechList_opt_tlft_cached(name); } static boolean isLocalSnippetID(String snippetID) { return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID)); } static boolean isLocalSnippetID(long snippetID) { return snippetID >= 1000 && snippetID <= 9999; } static String loadLocalSnippet(String snippetID) { return loadLocalSnippet(psI(snippetID)); } static String loadLocalSnippet(long snippetID) { return loadTextFile(localSnippetFile(snippetID)); } static String standardCredentials() { String user = standardCredentialsUser(); String pass = standardCredentialsPass(); if (nempty(user) && nempty(pass)) return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass); return ""; } static File getGlobalCache() { File file = new File(javaxCachesDir(), "Binary Snippets"); file.mkdirs(); return file; } 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; } // syntax 1: replace all occurrences of x in l with y 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; replaceSublist(l, i, i+l(x), y); i += l(y); } return l; } // syntax 2: splice l at fromIndex-toIndex and replace middle part with y static List replaceSublist(List l, int fromIndex, int toIndex, List y) { int n = y.size(), toIndex_new = fromIndex+n; if (toIndex_new < toIndex) { removeSubList(l, toIndex_new, toIndex); copyListPart(y, 0, l, fromIndex, n); } else { copyListPart(y, 0, l, fromIndex, toIndex-fromIndex); if (toIndex_new > toIndex) l.addAll(toIndex, subList(y, toIndex-fromIndex)); } return l; } static List replaceSublist(List l, IntRange r, List y) { return replaceSublist(l, r.start, r.end, y); } static String quickSubstring(String s, int i, int j) { if (i == j) return ""; return s.substring(i, j); } static String loadTextFilePossiblyGZipped(String fileName) { return loadTextFilePossiblyGZipped(fileName, null); } static String loadTextFilePossiblyGZipped(String fileName, String defaultContents) { File gz = new File(fileName + ".gz"); return gz.exists() ? loadGZTextFile(gz) : loadTextFile(fileName, defaultContents); } static String loadTextFilePossiblyGZipped(File fileName) { return loadTextFilePossiblyGZipped(fileName, null); } static String loadTextFilePossiblyGZipped(File fileName, String defaultContents) { return loadTextFilePossiblyGZipped(fileName.getPath(), defaultContents); } static File getCachedTranspilationFile(String id) { return newFile(getCodeProgramDir(id), "Transpilation"); } static Object vmGeneralMap_get(Object key) { return vm_generalMap_get(key); } static String loadProgramTextFile(String name) { return loadTextFile(getProgramFile(name)); } static String loadProgramTextFile(String progID, String name) { return loadTextFile(getProgramFile(progID, name)); } static String loadProgramTextFile(String progID, String name, String defaultText) { return loadTextFile(getProgramFile(progID, name), defaultText); } static String loadPage_utf8(URL url) { return loadPage_utf8(url.toString()); } static String loadPage_utf8(String url) { AutoCloseable __1 = tempSetTL(loadPage_charset, "UTF-8"); try { return loadPage(url); } finally { _close(__1); }} static String loadPage_utf8(URLConnection con, URL url, boolean addHeaders) throws IOException { AutoCloseable __2 = tempSetTL(loadPage_charset, "UTF-8"); try { return loadPage(con, url, addHeaders); } finally { _close(__2); }} static void saveTranspiledCode(String progID, String code) { File dir = getCodeProgramDir(progID); new File(dir, "Transpilation").delete(); saveGZTextFile(new File(dir, "Transpilation.gz"), code); } static boolean addToCollection(Collection c, A a) { return c != null && c.add(a); } 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"); } static String muricaCredentialsQuery() { return htmlQuery(muricaCredentials()); } static boolean isGeneralFileServerSnippet(long id) { return id >= 1400000 && id < 1500000; } static String standardCredentials_noCookies() { return standardCredentials() + "&noCookies=1"; } static boolean saveTextFileIfChanged(File f, String contents) { return saveTextFileIfDifferent(f, contents); } static File snippetTitle_cacheFile(String snippetID) { return javaxCachesDir("Snippet Titles/" + psI(snippetID)); } static Runnable _topLevelErrorHandling(final Runnable runnable) { final Object info = _threadInfo(); return new Runnable() { public void run() { try { try { _threadInheritInfo(info); runnable.run(); } catch (Throwable __e) { _handleException(__e); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }"; }}; } static Map vm_generalWeakSubMap(Object name) { synchronized(get(javax(), "generalMap")) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = newWeakMap()); return map; } } static WeakReference weakRef(A a) { return newWeakReference(a); } static Object pcallFunction(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); } return null; } static Set syncIdentityHashSet() { return (Set) synchronizedSet(identityHashSet()); } static Map syncHashMap() { return synchroHashMap(); } static boolean emptyString(String s) { return s == null || s.length() == 0; } static boolean checkTokCondition(Object condition, List tok, int i) { if (condition instanceof TokCondition) return ((TokCondition) condition).get(tok, i); return checkCondition(condition, tok, i); } static void replaceCollection(Collection dest, Collection src) { if (dest == src) return; dest.clear(); dest.addAll(src); } static void replaceListPart(List l, int i, int j, List l2) { replaceSublist(l, i, j, l2); } static Object sleepQuietly_monitor = new Object(); static void sleepQuietly() { try { assertFalse(isAWTThread()); synchronized(sleepQuietly_monitor) { sleepQuietly_monitor.wait(); } } catch (Exception __e) { throw rethrow(__e); } } static String _computerID; static Lock computerID_lock = lock(); public static String computerID() { if (_computerID == null) { Lock __0 = computerID_lock; lock(__0); try { if (_computerID != null) return _computerID; File file = computerIDFile(); _computerID = loadTextFile(file.getPath()); if (_computerID == null) { // legacy load _computerID = loadTextFile(userDir(".tinybrain/computer-id")); if (_computerID == null) _computerID = makeRandomID(12, new SecureRandom()); saveTextFile(file, _computerID); } } finally { unlock(__0); } } return _computerID; } static B mapPutOrRemove(Map map, A key, B value) { if (map != null && key != null) if (value != null) return map.put(key, value); else return map.remove(key); return null; } static String joinNempties(String sep, String... strings) { return joinStrings(sep, strings); } static String joinNempties(String sep, Collection strings) { return joinStrings(sep, strings); } static String stream2string(InputStream in) { return utf8streamToString(in); } 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(/*escapeMultichars*/(value))); } } return str(buf); } 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(/*escapeMultichars*/(value))); } } return str(buf); } static int lUtf8(String s) { return l(utf8(s)); } static File[] listFiles(File dir) { File[] files = dir.listFiles(); return files == null ? new File[0] : files; } static File[] listFiles(String dir) { return listFiles(new File(dir)); } static int parseFirstInt(String s) { return parseInt(jextract("", s)); } static int parseFirstInt(Iterable l) { return parseInt(firstIntegerString(l)); } static List valuesList(Map map) { return cloneListSynchronizingOn(values(map), map); } static List valuesList(MultiMap mm) { return mm == null ? emptyList() : concatLists(values(mm.data)); } static Producer javaTokC_noMLS_iterator(final String s) { return javaTokC_noMLS_iterator(s, 0); } static Producer javaTokC_noMLS_iterator(final String s, final int startIndex) { return new Producer() { final int l = s.length(); int i = startIndex; public String next() { if (i >= l) return null; int j = i; char c, d; // scan for whitespace while (j < l) { c = s.charAt(j); d = j+1 >= l ? '\0' : s.charAt(j+1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/")); j = Math.min(j+2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } i = j; if (i >= l) return null; c = s.charAt(i); d = i+1 >= l ? '\0' : s.charAt(i+1); // scan for non-whitespace if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors ++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))); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } else ++j; String t = quickSubstring(s, i, j); i = j; return t; } }; } static Producer javaTokC_noMLS_onReader(final BufferedReader r) { final class X implements Producer { StringBuilder buf = new StringBuilder(); // stores from "i" char c, d, e = 'x'; // just not '\0' X() { // fill c, d and e nc(); nc(); nc(); } // get next character(s) into c, d and e void nc() { try { c = d; d = e; if (e == '\0') return; int i = r.read(); e = i < 0 ? '\0' : i == '\0' ? '_' // shouldn't happen anymore : (char) i; } catch (Exception __e) { throw rethrow(__e); } } void ncSave() { if (c != '\0') { buf.append(c); nc(); } } public String next() { // scan for whitespace while (c != '\0') { if (c == ' ' || c == '\t' || c == '\r' || c == '\n') nc(); else if (c == '/' && d == '*') { do nc(); while (c != '\0' && !(c == '*' && d == '/')); nc(); nc(); } else if (c == '/' && d == '/') { do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0); } else break; } if (c == '\0') return null; // scan for non-whitespace if (c == '\'' || c == '"') { char opener = c; ncSave(); while (c != '\0') { if (c == opener || c == '\n') { // end at \n to not propagate unclosed string literal errors ncSave(); break; } else if (c == '\\') { ncSave(); ncSave(); } else ncSave(); } } else if (Character.isJavaIdentifierStart(c)) do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\''); // for stuff like "don't" else if (Character.isDigit(c)) { do ncSave(); while (Character.isDigit(c)); if (c == 'L') ncSave(); // Long constants like 1L } else ncSave(); String t = buf.toString(); buf.setLength(0); return t; } } return new X(); } static Object _defaultClassFinder_value = defaultDefaultClassFinder(); static Object _defaultClassFinder() { return _defaultClassFinder_value; } static HashMap findClass_fullName_cache = new HashMap(); // returns null on not found // this is the simple version that is not case-tolerant 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; } } static String unquoteUsingCharArray(String s, char[] buf) { if (s == null) return null; if (startsWith(s, '[')) { int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; if (i < s.length() && s.charAt(i) == '[') { String m = s.substring(1, i); if (s.endsWith("]" + m + "]")) return s.substring(i+1, s.length()-i-1); } } if (s.length() > 1) { char c = s.charAt(0); if (c == '\"' || c == '\'') { int l = endsWith(s, c) ? s.length()-1 : s.length(); if (l > buf.length) return unquote(s); // fallback int n = 0; for (int i = 1; i < l; i++) { char ch = s.charAt(i); if (ch == '\\') { char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1); // Octal escape? if (nextChar >= '0' && nextChar <= '7') { String code = "" + nextChar; i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; } } buf[n++] = (char) Integer.parseInt(code, 8); continue; } switch (nextChar) { case '\"': ch = '\"'; break; case '\\': ch = '\\'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\'': ch = '\''; break; // Hex Unicode: u???? case 'u': if (i >= l - 5) { ch = 'u'; break; } int code = Integer.parseInt( "" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16); char[] x = Character.toChars(code); int lx = x.length; for (int j = 0; j < lx; j++) buf[n++] = x[j]; i += 5; continue; default: ch = nextChar; // added by Stefan } i++; } buf[n++] = ch; } return new String(buf, 0, n); } } return s; // not quoted - return original } static boolean structure_isMarker(String s, int i, int j) { if (i >= j) return false; if (s.charAt(i) != 'm') return false; ++i; while (i < j) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } static String internIfLongerThan(String s, int l) { return s == null ? null : l(s) >= l ? intern(s) : s; } static char unquoteCharacter(String s) { assertTrue(s.startsWith("'") && s.length() > 1); return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length()-1 : s.length()) + "\"").charAt(0); } static BigInteger parseBigInt(String s) { return new BigInteger(s); } static double parseDouble(String s) { return Double.parseDouble(s); } static float parseFloat(String s) { return Float.parseFloat(s); } static boolean isLongConstant(String s) { if (!s.endsWith("L")) return false; s = s.substring(0, l(s)-1); return isInteger(s); } static TreeMap ciMap() { return caseInsensitiveMap(); } static List parseList(String s) { return (List) safeUnstructure(s); } static List synchroLinkedList() { return Collections.synchronizedList(new LinkedList()); } 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; } static boolean[] boolArrayFromBytes(byte[] a, int n) { boolean[] b = new boolean[n]; int m = min(n, l(a)*8); for (int i = 0; i < m; i++) b[i] = (a[i/8] & 1 << (i & 7)) != 0; return b; } static A nuStubInnerObject(Class c) { return nuStubInnerObject(c, null); } static A nuStubInnerObject(Class c, Object classFinder) { try { Class outerType = getOuterClass(c, classFinder); Constructor m = c.getDeclaredConstructor(outerType); makeAccessible(m); return (A) m.newInstance(new Object[] {null}); } catch (Exception __e) { throw rethrow(__e); } } static Map nuEmptyObject_cache = newDangerousWeakHashMap(); static A nuEmptyObject(Class c) { try { Constructor ctr; synchronized(nuEmptyObject_cache) { ctr = nuEmptyObject_cache.get(c); if (ctr == null) { nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c)); makeAccessible(ctr); } } try { return (A) ctr.newInstance(); } catch (InstantiationException e) { if (empty(e.getMessage())) if ((c.getModifiers() & Modifier.ABSTRACT) != 0) throw fail("Can't instantiate abstract class " + className(c), e); else throw fail("Can't instantiate " + className(c), e); else throw rethrow(e); } } catch (Exception __e) { throw rethrow(__e); } } static Constructor nuEmptyObject_findConstructor(Class c) { for (Constructor m : c.getDeclaredConstructors()) if (m.getParameterTypes().length == 0) return m; throw fail("No default constructor declared in " + c.getName()); } static void setOptAllDyn(DynamicObject o, Map fields) { if (fields == null) return; HashMap fieldMap = instanceFieldsMap(o); for (Map.Entry e : fields.entrySet()) { String field = e.getKey(); Object val = e.getValue(); boolean has = fieldMap.containsKey(field); if (has) setOpt(o, field, val); else { o.fieldValues = syncMapPut2_createLinkedHashMap(o.fieldValues, intern(field), val); } } } static void setOptAll_pcall(Object o, Map fields) { if (fields == null) return; for (String field : keys(fields)) try { setOpt(o, field, fields.get(field)); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } static void setOptAll_pcall(Object o, Object... values) { //values = expandParams(c.getClass(), values); warnIfOddCount(values); for (int i = 0; i+1 < l(values); i += 2) { String field = (String) values[i]; Object value = values[i+1]; try { setOpt(o, field, value); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } } static void fixOuterRefs(Object o) { try { if (o == null) return; Field[] l = thisDollarOneFields(o.getClass()); if (l.length <= 1) return; Object father = null; for (Field f : l) { father = f.get(o); if (father != null) break; } if (father == null) return; for (Field f : l) f.set(o, father); } catch (Exception __e) { throw rethrow(__e); } } static void setDynObjectValue(DynamicObject o, String field, Object value) { o.fieldValues = syncMapPut2_createLinkedHashMap(o.fieldValues, field, value); } static String intern(String s) { return fastIntern(s); } static void pcallOpt_noArgs(Object o, String method) { try { callOpt_noArgs(o, method); } catch (Throwable __e) { _handleException(__e); } } static int[] toIntArray(Collection l) { int[] a = new int[l(l)]; int i = 0; if (a.length != 0) for (int x : l) a[i++] = x; return a; } static double[] toDoubleArray(Collection l) { double[] a = new double[l(l)]; int i = 0; if (a.length != 0) for (double x : l) a[i++] = x; return a; } static TreeSet ciSet() { return caseInsensitiveSet(); } static boolean jmatch(String pat, String s) { return jmatch(pat, s, null); } static boolean jmatch(String pat, String s, Matches matches) { if (s == null) return false; return jmatch(pat, javaTok(s), matches); } static boolean jmatch(String pat, List toks) { return jmatch(pat, toks, null); } static boolean jmatch(String pat, List toks, Matches matches) { List tokpat = javaTok(pat); String[] m = match2(tokpat, toks); //print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m)); if (m == null) return false; else { if (matches != null) matches.m = m; return true; } } static Object nuObject(String className, Object... args) { try { return nuObject(classForName(className), args); } catch (Exception __e) { throw rethrow(__e); } } // too ambiguous - maybe need to fix some callers /*static O nuObject(O realm, S className, O... args) { ret nuObject(_getClass(realm, className), args); }*/ static A nuObject(Class c, Object... args) { try { if (args.length == 0) return nuObjectWithoutArguments(c); // cached! Constructor m = nuObject_findConstructor(c, args); makeAccessible(m); return (A) m.newInstance(args); } catch (Exception __e) { throw rethrow(__e); } } static Constructor nuObject_findConstructor(Class c, Object... args) { for (Constructor m : c.getDeclaredConstructors()) { if (!nuObject_checkArgs(m.getParameterTypes(), args, false)) continue; return m; } throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : "")); } static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) { if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } static ThreadLocal dynamicObjectIsLoading_threadLocal() { return DynamicObject_loading; } static Map>> mechList_opt_tlft_cached_cache = ciMap(); static Lock mechList_opt_tlft_cached_lock = lock(); static List mechList_opt_tlft_cached(String name) { MechListDependentCache> listCache; { Lock __0 = mechList_opt_tlft_cached_lock; lock(__0); try { listCache = mechList_opt_tlft_cached_cache.get(name); if (listCache == null) mechList_opt_tlft_cached_cache.put(name, listCache = new MechListDependentCache(name, new F1>() { public List < String > get(String x) { try { return tlft(x); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tlft(x)"; }})); } finally { unlock(__0); } } return listCache.get(); } static long psI(String snippetID) { return parseSnippetID(snippetID); } static File localSnippetFile(long snippetID) { return localSnippetsDir(snippetID + ".text"); } static File localSnippetFile(String snippetID) { return localSnippetFile(parseSnippetID(snippetID)); } static String standardCredentialsUser() { return trim(loadTextFile( oneOfTheFiles( javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username")))); } static String standardCredentialsPass() { return trim(loadTextFile( oneOfTheFiles( javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass")))); } static void copyListPart(List a, int i1, List b, int i2, int n) { if (a == null || b == null) return; for (int i = 0; i < n; i++) b.set(i2+i, a.get(i1+i)); } static String loadGZTextFile(File file) { try { if (!file.isFile()) return null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream fis = new FileInputStream(file); GZIPInputStream gis = newGZIPInputStream(fis); try { byte[] buffer = new byte[1024]; int len; while((len = gis.read(buffer)) != -1){ baos.write(buffer, 0, len); } } finally { fis.close(); } baos.close(); return fromUtf8(baos.toByteArray()); // TODO: use a Reader } catch (Exception __e) { throw rethrow(__e); } } static File getCodeProgramDir() { return getCodeProgramDir(getProgramID()); } static File getCodeProgramDir(String snippetID) { return new File(javaxCodeDir(), formatSnippetID(snippetID)); } static File getCodeProgramDir(long snippetID) { return getCodeProgramDir(formatSnippetID(snippetID)); } static void saveGZTextFile(File file, String contents) { saveGZTextFile(file, contents, "UTF-8"); } static void saveGZTextFile(File file, String contents, String encoding) { try { File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = file.getPath() + "_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()); GZIPOutputStream gos = new GZIPOutputStream(fileOutputStream); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gos, encoding); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); gos.close(); fileOutputStream.close(); } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + file.getPath()); if (contents != null) if (!tempFile.renameTo(file)) throw new IOException("Can't rename " + tempFile + " to " + file); } catch (Exception __e) { throw rethrow(__e); } } static String getFileInfoField(File f, String field) { return getOneLineFileInfoField(f, field); } static File dropExtension(File f) { return f == null ? null : fileInSameDir(f, dropExtension(f.getName())); } static String dropExtension(String s) { return takeFirst(s, smartLastIndexOf(s, '.')); } static String htmlQuery(Map params) { return empty(params) ? "" : "?" + makePostData(params); } static String htmlQuery(Object... data) { return empty(data) ? "" : "?" + makePostData(data); } static Object[] muricaCredentials() { String pass = muricaPassword(); return nempty(pass) ? new Object[] {"_pass", pass } : new Object[0]; } static boolean saveTextFileIfDifferent(File f, String contents) { if (eq(loadTextFile(f), contents)) return false; // TODO: optimize { saveTextFile(f, contents); return true; } } static List> _threadInfo_makers = synchroList(); static Object _threadInfo() { if (empty(_threadInfo_makers)) return null; HashMap map = new HashMap(); pcallFAll(_threadInfo_makers, map); return map; } static List> _threadInheritInfo_retrievers = synchroList(); static void _threadInheritInfo(Object info) { if (info == null) return; pcallFAll(_threadInheritInfo_retrievers, (Map) info); } static Map newWeakMap() { return newWeakHashMap(); } static WeakReference newWeakReference(A a) { return a == null ? null : new WeakReference(a); } static Object callFunction(Object f, Object... args) { return callF(f, args); } static Set synchronizedSet() { return synchroHashSet(); } static Set synchronizedSet(Set set) { return Collections.synchronizedSet(set); } static Set identityHashSet() { return Collections.newSetFromMap(new IdentityHashMap()); } static boolean checkCondition(Object condition, Object... args) { return isTrue(callF(condition, args)); } static boolean checkCondition(IF1 condition, A arg) { return isTrue(callF(condition, arg)); } static void assertFalse(Object o) { if (!(eq(o, false) /*|| isFalse(pcallF(o))*/)) throw fail(str(o)); } static boolean assertFalse(boolean b) { if (b) throw fail("oops"); return b; } static boolean assertFalse(String msg, boolean b) { if (b) throw fail(msg); return b; } static File computerIDFile() { return javaxDataDir("Basic Info/computer-id.txt"); } static String joinStrings(String sep, String... strings) { return joinStrings(sep, Arrays.asList(strings)); } 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); } static String utf8streamToString(InputStream in) { return readerToString(utf8bufferedReader(in)); } // returns from C to C static String jextract(String pat, String s) { return jextract(pat, javaTok(s)); } 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); } static String firstIntegerString(Iterable c) { Iterator it = c.iterator(); while (it.hasNext()) { String s = it.next(); if (isInteger(s)) return s; } return null; } static ArrayList cloneListSynchronizingOn(Collection l, Object mutex) { if (l == null) return new ArrayList(); synchronized(mutex) { return new ArrayList(l); } } static Object defaultDefaultClassFinder() { return new F1() { public Class get(String name) { Class c = findClass_fullName(name); if (c != null) return c; if (name.startsWith("loadableUtils.utils$")) return findClass_fullName("main" + name.substring(19)); return null; } }; } static TreeMap caseInsensitiveMap() { return new TreeMap(caseInsensitiveComparator()); } static Object safeUnstructure(String s) { return unstructure(s, true); } 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; } static Class getOuterClass(Class c) { return getOuterClass(c, null); } static Class getOuterClass(Class c, Object classFinder) { try { String s = c.getName(); int i = s.lastIndexOf('$'); String name = substring(s, 0, i); if (classFinder != null) return (Class) callF(classFinder, name); return Class.forName(name); } catch (Exception __e) { throw rethrow(__e); } } static HashMap instanceFieldsMap(Object o) { Class c = o.getClass(); HashMap map; synchronized(getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } return map; } static Field setOpt_findField(Class c, String field) { HashMap map; synchronized(getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } return map.get(field); } static void setOpt(Object o, String field, Object value) { try { if (o == null) return; Class c = o.getClass(); HashMap map; if (getOpt_cache == null) map = getOpt_makeCache(c); // in class init else synchronized(getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } if (map == getOpt_special) { if (o instanceof Class) { setOpt((Class) o, field, value); return; } // It's probably a subclass of Map. Use raw method setOpt_raw(o, field, value); return; } Field f = map.get(field); if (f != null) { smartSet(f, o, value); return; } // possible improvement: skip setAccessible if (o instanceof DynamicObject) setDyn(((DynamicObject) o), field, value); } catch (Exception __e) { throw rethrow(__e); } } static void setOpt(Class c, String field, Object value) { if (c == null) return; try { Field f = setOpt_findStaticField(c, field); // TODO: optimize if (f != null) smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } static Field setOpt_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) { makeAccessible(f); return f; } _c = _c.getSuperclass(); } while (_c != null); return null; } static LinkedHashMap syncMapPut2_createLinkedHashMap(LinkedHashMap map, A key, B value) { if (key != null) if (value != null) { if (map == null) map = new LinkedHashMap(); synchronized(collectionMutex(map)) { map.put(key, value); } } else if (map != null) synchronized(collectionMutex(map)) { map.remove(key); } return map; } static void warnIfOddCount(Object... list) { if (odd(l(list))) printStackTrace("Odd list size: " + list); } static Map thisDollarOneFields_cache = newDangerousWeakHashMap(); static Field[] thisDollarOneFields(Class c) { synchronized(thisDollarOneFields_cache) { Field[] l = thisDollarOneFields_cache.get(c); if (l == null) thisDollarOneFields_cache.put(c, l = thisDollarOneFields_uncached(c)); return l; } } static Field[] thisDollarOneFields_uncached(Class c) { List fields = new ArrayList(); do { for (Field f : c.getDeclaredFields()) if (f.getName().equals("this$1")) fields.add(makeAccessible(f)); c = c.getSuperclass(); } while (c != null); return toArray(new Field[l(fields)], fields); } static Method fastIntern_method; static String fastIntern(String s) { try { if (s == null) return null; if (fastIntern_method == null) { fastIntern_method = findMethodNamed(javax(), "internPerProgram"); if (fastIntern_method == null) upgradeJavaXAndRestart(); } return (String) fastIntern_method.invoke(null, s); } catch (Exception __e) { throw rethrow(__e); } } static Map> callOpt_noArgs_cache = newDangerousWeakHashMap(); static Object callOpt_noArgs(Object o, String method) { try { if (o == null) return null; if (o instanceof Class) return callOpt(o, method); // not optimized Class c = o.getClass(); HashMap map; synchronized(callOpt_noArgs_cache) { map = callOpt_noArgs_cache.get(c); if (map == null) map = callOpt_noArgs_makeCache(c); } Method m = map.get(method); return m != null ? m.invoke(o) : null; } catch (Exception __e) { throw rethrow(__e); } } // used internally - we are in synchronized block static HashMap callOpt_noArgs_makeCache(Class c) { HashMap map = new HashMap(); Class _c = c; do { for (Method m : c.getDeclaredMethods()) if (m.getParameterTypes().length == 0 && !reflection_isForbiddenMethod(m)) { makeAccessible(m); String name = m.getName(); if (!map.containsKey(name)) map.put(name, m); } _c = _c.getSuperclass(); } while (_c != null); callOpt_noArgs_cache.put(c, map); return map; } static TreeSet caseInsensitiveSet() { return caseInsensitiveSet_treeSet(); } static TreeSet caseInsensitiveSet(Collection c) { return caseInsensitiveSet_treeSet(c); } static Map classForName_cache = synchroHashMap(); static Class classForName(String name) { try { if (classForName_cache == null) return Class.forName(name); // in class init Class c = classForName_cache.get(name); if (c == null) classForName_cache.put(name, c = Class.forName(name)); return c; } catch (Exception __e) { throw rethrow(__e); } } static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap(); static Object nuObjectWithoutArguments(String className) { try { return nuObjectWithoutArguments(classForName(className)); } catch (Exception __e) { throw rethrow(__e); } } static A nuObjectWithoutArguments(Class c) { try { if (nuObjectWithoutArguments_cache == null) // in class init return (A) nuObjectWithoutArguments_findConstructor(c).newInstance(); Constructor m = nuObjectWithoutArguments_cache.get(c); if (m == null) nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c)); return (A) m.newInstance(); } catch (Exception __e) { throw rethrow(__e); } } static Constructor nuObjectWithoutArguments_findConstructor(Class c) { for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) { makeAccessible(m); return m; } throw fail("No default constructor found in " + c.getName()); } static File localSnippetsDir() { return javaxDataDir("Personal Programs"); } static File localSnippetsDir(String sub) { return newFile(localSnippetsDir(), sub); } static File oneOfTheFiles(String... paths) { if (paths != null) for (String path : paths) if (fileExists(path)) return newFile(path); return null; } static File oneOfTheFiles(File... files) { if (files != null) for (File f : files) if (fileExists(f)) return f; return null; } static File javaxSecretDir_dir; // can be set to work on different base dir static File javaxSecretDir() { return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret"); } static File javaxSecretDir(String sub) { return newFile(javaxSecretDir(), sub); } static String fromUtf8(byte[] bytes) { try { return bytes == null ? null : new String(bytes, "UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } static File javaxCodeDir_dir; // can be set to work on different base dir static File javaxCodeDir() { return javaxCodeDir_dir != null ? javaxCodeDir_dir : new File(userHome(), "JavaX-Code"); } static File javaxCodeDir(String sub) { return newFile(javaxCodeDir(), sub); } static String getOneLineFileInfoField(File f, String field) { File infoFile = associatedInfosFile(f); List lines = lines(loadTextFile(infoFile)); return firstStartingWithIC_drop(lines, field + ": "); } static File fileInSameDir(File f, String newName) { return newFile(parentFile(f), newName); } static int smartLastIndexOf(String s, char c) { if (s == null) return 0; int i = s.lastIndexOf(c); return i >= 0 ? i : l(s); } static volatile boolean muricaPassword_pretendNotAuthed = false; static String muricaPassword() { if (muricaPassword_pretendNotAuthed) return null; return trim(loadTextFile(muricaPasswordFile())); } static Set synchroHashSet() { return Collections.synchronizedSet(new HashSet()); } 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; //if ((n % loadPage_verboseness) == 0) print(" " + n + " chars read"); } return buf.toString(); } finally { r.close(); } } catch (Exception __e) { throw rethrow(__e); } } static Comparator caseInsensitiveComparator() { return betterCIComparator(); } static int charDiff(char a, char b) { return (int) a-(int) b; } static int charDiff(String a, char b) { return charDiff(stringToChar(a), b); } static void setOpt_raw(Object o, String field, Object value) { try { if (o == null) return; if (o instanceof Class) setOpt_raw((Class) o, field, value); else { Field f = setOpt_raw_findField(o.getClass(), field); if (f != null) { makeAccessible(f); smartSet(f, o, value); } } } catch (Exception __e) { throw rethrow(__e); } } static void setOpt_raw(Class c, String field, Object value) { try { if (c == null) return; Field f = setOpt_raw_findStaticField(c, field); if (f != null) { makeAccessible(f); smartSet(f, null, value); } } catch (Exception __e) { throw rethrow(__e); } } static Field setOpt_raw_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static Field setOpt_raw_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static void smartSet(Field f, Object o, Object value) throws Exception { try { f.set(o, value); } catch (Exception e) { Class type = f.getType(); // take care of common case (long to int) if (type == int.class && value instanceof Long) value = ((Long) value).intValue(); if (type == LinkedHashMap.class && value instanceof Map) { f.set(o, asLinkedHashMap((Map) value)); return; } throw e; } } static A setDyn(A o, String key, Object value) { if (o == null) return o; setDynObjectValue(o, key, value); return o; } static Object[] toArray(Collection c) { return toObjectArray(c); } static A[] toArray(Iterable c, Class type) { A[] a = arrayOfType(l(c), type); if (a.length == 0) return a; asList(c).toArray(a); return a; } // array must have correct length and will be filled static A[] toArray(A[] array, Collection c) { if (array == null || c == null) return null; asList(c).toArray(array); return array; } static void upgradeJavaXAndRestart() { run("#1001639"); restart(); sleep(); } static boolean reflection_isForbiddenMethod(Method m) { return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives"); } static TreeSet caseInsensitiveSet_treeSet() { return new TreeSet(caseInsensitiveComparator()); } static TreeSet caseInsensitiveSet_treeSet(Collection c) { return toCaseInsensitiveSet_treeSet(c); } static boolean fileExists(String path) { return path != null && new File(path).exists(); } static boolean fileExists(File f) { return f != null && f.exists(); } static File associatedInfosFile(File f) { return replaceExtension(f, ".infos"); } 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; } static String firstStartingWithIC_drop(String prefix, Collection l) { return firstStartingWithIC_drop(l, prefix); } static File parentFile(File f) { return dirOfFile(f); } static File muricaPasswordFile() { return new File(javaxSecretDir(), "murica/muricaPasswordFile"); } static betterCIComparator_C betterCIComparator_instance; static betterCIComparator_C betterCIComparator() { if (betterCIComparator_instance == null) betterCIComparator_instance = new betterCIComparator_C(); return betterCIComparator_instance; } static class betterCIComparator_C implements Comparator { public int compare(String s1, String s2) { if (s1 == null) return s2 == null ? 0 : -1; if (s2 == null) return 1; int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) { // No overflow because of numeric promotion return c1 - c2; } } } } return n1 - n2; } } static char stringToChar(String s) { if (l(s) != 1) throw fail("bad stringToChar: " + s); return firstChar(s); } static Class run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } static void restart() { Object j = getJavaX(); call(j, "cleanRestart", get(j, "fullArgs")); } static TreeSet toCaseInsensitiveSet_treeSet(Iterable c) { if (isCISet(c)) return (TreeSet) c; TreeSet set = caseInsensitiveSet_treeSet(); addAll(set, c); return set; } static TreeSet toCaseInsensitiveSet_treeSet(String... x) { TreeSet set = caseInsensitiveSet_treeSet(); addAll(set, x); return set; } static File replaceExtension(File f, String extOld, String extNew) { return newFile(replaceExtension(f2s(f), extOld, extNew)); } static File replaceExtension(File f, String extNew) { return replaceExtension(f, fileExtension(f), extNew); } static String replaceExtension(String s, String extOld, String extNew) { s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s); return s + addPrefixOptIfNempty(".", extNew); } static String replaceExtension(String name, String extNew) { return replaceExtension(name, fileExtension(name), extNew); } static File dirOfFile(File f) { return f == null ? null : f.getParentFile(); } static char firstChar(String s) { return s.charAt(0); } static Class hotwire(String src) { assertFalse(_inCore()); Class j = getJavaX(); if (isAndroid()) { synchronized(j) { // hopefully this goes well... List libraries = new ArrayList(); File srcDir = (File) call(j, "transpileMain", src, libraries); if (srcDir == null) throw fail("transpileMain returned null (src=" + quote(src) + ")"); Object androidContext = get(j, "androidContext"); return (Class) call(j, "loadx2android", srcDir, src); } } else { Class c = (Class) (call(j, "hotwire", src)); hotwire_copyOver(c); return c; } } static A callMain(A c, String... args) { callOpt(c, "main", new Object[] {args}); return c; } static void callMain() { callMain(mc()); } static boolean isCISet(Iterable l) { return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator(); } static String fileExtension(File f) { if (f == null) return null; return fileExtension(f.getName()); } static String fileExtension(String s) { return substring(s, smartLastIndexOf(s, '.')); } static String dropSuffixIC(String suffix, String s) { return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s)-l(suffix)) : s; } static String addPrefixOptIfNempty(String prefix, String s) { return addPrefixIfNotEmpty2(prefix, s); } static boolean _inCore() { return false; } static List hotwire_copyOver_after = synchroList(); static void hotwire_copyOver(Class c) { // TODO: make a mechanism for making such "inheritable" fields for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field)); setOptIfNotNull(c, "mainBot" , getMainBot()); setOpt(c, "creator_class" , new WeakReference(mc())); pcallFAll(hotwire_copyOver_after, c); } static String addPrefixIfNotEmpty2(String prefix, String s) { return empty(s) ? "" : addPrefix(prefix, s); } static void setOptIfNotNull(Object o, String field, Object value) { if (value != null) setOpt(o, field, value); } static Object mainBot; static Object getMainBot() { return mainBot; } static String addPrefix(String prefix, String s) { return s.startsWith(prefix) ? s : prefix + s; } // immutable, has strong refs final static class _MethodCache { final Class c; final HashMap> cache = new HashMap(); _MethodCache(Class c) { this.c = c; _init(); } void _init() { Class _c = c; while (_c != null) { for (Method m : _c.getDeclaredMethods()) if (!isAbstract(m) && !reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); _c = _c.getSuperclass(); } // add default methods - this might lead to a duplication // because the overridden method is also added, but it's not // a problem except for minimal performance loss. for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); } // Returns only matching methods Method findMethod(String method, Object[] args) { try { List m = cache.get(method); if (m == null) return null; int n = m.size(); for (int i = 0; i < n; i++) { Method me = m.get(i); if (call_checkArgs(me, args, false)) return me; } return null; } catch (Exception __e) { throw rethrow(__e); } } Method findStaticMethod(String method, Object[] args) { try { List m = cache.get(method); if (m == null) return null; int n = m.size(); for (int i = 0; i < n; i++) { Method me = m.get(i); if (isStaticMethod(me) && call_checkArgs(me, args, false)) return me; } return null; } catch (Exception __e) { throw rethrow(__e); } } }static abstract class VF1 implements IVF1 { public abstract void get(A a); }static class Matches { String[] m; Matches() {} Matches(String... m) { this.m = m;} String get(int i) { return i < m.length ? m[i] : null; } String unq(int i) { return unquote(get(i)); } String tlc(int i) { return unq(i).toLowerCase(); } boolean bool(int i) { return "true".equals(unq(i)); } String rest() { return m[m.length-1]; } // for matchStart int psi(int i) { return Integer.parseInt(unq(i)); } public String toString() { return "Matches(" + joinWithComma(quoteAll(asList(m))) + ")"; } public int hashCode() { return _hashCode(toList(m)); } public boolean equals(Object o) { return o instanceof Matches && arraysEqual(m, ((Matches) o).m); } } static class Var implements IVar { Var() {} Var(A v) { this.v = v;} A v; // you can access this directly if you use one thread public synchronized void set(A a) { if (v != a) { v = a; notifyAll(); } } public synchronized A get() { return v; } public synchronized boolean has() { return v != null; } public synchronized void clear() { v = null; } public String toString() { return str(get()); } } static class MechListDependentCache extends Cache { // maker is now F1 String listName, lastListContents; MechListDependentCache() {} MechListDependentCache(String listName, Object maker) { this.maker = maker; this.listName = listName;} A make() { return (A) callF(maker, lastListContents); } A get() { if (hasLock(lock)) return value; // Must be called from within maker { String listContents = mL_raw(listName); Lock __0 = lock; lock(__0); try { if (!eqOrSame(listContents, lastListContents)) clear(); lastListContents = listContents; } finally { unlock(__0); } } return super.get(); } }static abstract class TokCondition { abstract boolean get(List tok, int i); // i = N Index }static class GlobalID implements Comparable { // We need 76 bits for 26^16 IDs long a; // lower 64 bits int b; // 76-64=12 higher bits; could be short. change to short when unstructure() is smarter GlobalID() {} GlobalID(String id) { assertGlobalID(id); BigInteger value = bigint(0); for (int i = 0; i < l(id); i++) value = plus(mul(value, 26), charDiff(id.charAt(i), 'a')); a = value.longValue(); value = value.shiftRight(64); b = value.shortValue(); } public String toString() { BigInteger value = bigint(b); value = value.shiftLeft(32); value = plus(value, (a >> 32) & 0xFFFFFFFFL); value = value.shiftLeft(32); value = plus(value, a & 0xFFFFFFFFL); return bigintToGlobalID(value); } public boolean equals(Object o) { if (!(o instanceof GlobalID)) return false; return ((GlobalID) o).a == a && ((GlobalID) o).b == b; } public int hashCode() { return (int) a; } // matches ID's lexical ordering public int compareTo(GlobalID id) { int diff = b-id.b; return diff != 0 ? diff : Long.compareUnsigned(a, id.a); } }static class MultiMap { Map> data = new HashMap>(); MultiMap() {} MultiMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); } MultiMap(MultiMap map) { putAll(map); } MultiMap(Map> data) { this.data = data;} void put(A key, B value) { synchronized(data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); list.add(value); }} void add(A key, B value) { put(key, value); } void addAll(A key, Collection values) { putAll(key, values); } void addAllIfNotThere(A key, Collection values) { synchronized(data) { for (B value : values) setPut(key, value); }} void setPut(A key, B value) { synchronized(data) { if (!containsPair(key, value)) put(key, value); }} boolean containsPair(A key, B value) { synchronized(data) { return get(key).contains(value); }} void putAll(A key, Collection values) { synchronized(data) { if (nempty(values)) getActual(key).addAll(values); }} void removeAll(A key, Collection values) { synchronized(data) { for (B value : values) remove(key, value); }} List get(A key) { synchronized(data) { List list = data.get(key); return list == null ? Collections. emptyList() : list; }} List getOpt(A key) { synchronized(data) { return data.get(key); }} // returns actual mutable live list // creates the list if not there List getActual(A key) { synchronized(data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); return list; }} void clean(A key) { synchronized(data) { List list = data.get(key); if (list != null && list.isEmpty()) data.remove(key); }} Set keySet() { synchronized(data) { return data.keySet(); }} Set keys() { synchronized(data) { return data.keySet(); }} void remove(A key) { synchronized(data) { data.remove(key); }} void remove(A key, B value) { synchronized(data) { List list = data.get(key); if (list != null) { list.remove(value); if (list.isEmpty()) data.remove(key); } }} void clear() { synchronized(data) { data.clear(); }} boolean containsKey(A key) { synchronized(data) { return data.containsKey(key); }} B getFirst(A key) { synchronized(data) { List list = get(key); return list.isEmpty() ? null : list.get(0); }} void addAll(MultiMap map) { putAll(map); } void putAll(MultiMap map) { synchronized(data) { for (A key : map.keySet()) putAll(key, map.get(key)); }} void putAll(Map map) { synchronized(data) { if (map != null) for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue()); }} int keysSize() { synchronized(data) { return l(data); }} // full size - note: expensive operation int size() { synchronized(data) { int n = 0; for (List l : data.values()) n += l(l); return n; }} // expensive operation List reverseGet(B b) { synchronized(data) { List l = new ArrayList(); for (A key : data.keySet()) if (data.get(key).contains(b)) l.add(key); return l; }} Map> asMap() { synchronized(data) { return cloneMap(data); }} boolean isEmpty() { synchronized(data) { return data.isEmpty(); }} // override in subclasses List _makeEmptyList() { return new ArrayList(); } // returns live lists Collection> allLists() { synchronized(data) { return new ArrayList(data.values()); } } Collection> values() { return allLists(); } List allValues() { return concatLists(data.values()); } Object mutex() { return data; } public String toString() { return "mm" + str(data); } }static interface IResourceLoader { String loadSnippet(String snippetID); String getTranspiled(String snippetID); // with libs int getSnippetType(String snippetID); String getSnippetTitle(String snippetID); File loadLibrary(String snippetID); File pathToJavaXJar(); File getSnippetJar(String snippetID, String transpiledSrc); } abstract static class DynTalkBot2 extends DynServerAwareDiscordBot { static boolean _switchableField_myName = true; String myName = "Anonymous bot"; transient boolean useAGIBlueForDropPunctuation = true; transient boolean preprocessAtSelfToMyName = true; transient boolean dropPunctuation = true; transient boolean ngbCommands = true; List authorizedUsers = ll(547706854680297473L); // stefan static class ISaid implements IFieldsToList{ long channelID; long date; String text; ISaid() {} ISaid(long channelID, long date, String text) { this.text = text; this.date = date; this.channelID = channelID;} public String toString() { return shortClassName(this) + "(" + channelID + ", " + date + ", " + text + ")"; } public boolean equals(Object o) { if (!(o instanceof ISaid)) return false; ISaid __9 = (ISaid) o; return channelID == __9.channelID && date == __9.date && eq(text, __9.text); } public int hashCode() { int h = 69986258; h = boostHashCombine(h, _hashCode(channelID)); h = boostHashCombine(h, _hashCode(date)); h = boostHashCombine(h, _hashCode(text)); return h; } public Object[] _fieldsToList() { return new Object[] {channelID, date, text}; } } void init() { super.init(); onPostedInChannel.add((channel, msg) -> { if (channel instanceof Channel) { Guild guild = ((Channel) channel).getGuild(); if (guild == null) return; ByServer bs = getByServer(guild); long channelID = ((Channel) channel).getIdLong(); mapPut(bs.lastSaidInChannel, channelID, nu(ISaid.class, "channelID", channelID, "text" , msg)); change(); } }); // We leave it as null to force subclasses to set this // (avoids serializing bad instances) // makeByServer = () -> (A) new ByServer; dm_vmBus_onMessage_q("discordGuildJoin",new VF1() { public void get(Map map) { try { { if (!(map.get("module") == module())) return; } print("Got join"); getByServer(getLong("guildID",map), true) .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 get..."; }}); onDiscordEvent(e -> { //print("Generic Discord event: " + e); if (e instanceof UserUpdateOnlineStatusEvent) getByServer(((UserUpdateOnlineStatusEvent) e).getGuild()).onOnlineStatusChange(((UserUpdateOnlineStatusEvent) e)); }); } class ByServer extends DynServerAwareDiscordBot.ByServer { transient Lock lock; List guildAuthorizedUsers = synchroList(); Map lastSaidInChannel = synchroMap(); long preferredChannelInGuild; DynTalkBot2 m2() { return DynTalkBot2.this; } // for debugging // overridable void onUserJoin(long userID, Object... __) {} void onOnlineStatusChange(UserUpdateOnlineStatusEvent e) {} @Override String answer(String input, Map map) { if (preferredChannelInGuild == 0) { long channelID = longPar("channelID",map); if (channelID != 0) { preferredChannelInGuild = channelID; change(); } } String answer = processLine(input, map); { String __2 = super.answer(input, map); if (!empty(__2)) return __2; } // server-aware stuff return answer; } String dropMyPrefixOpt(String s) { return or(dropMyPrefixOrNull(s), s); } String dropMyPrefixOrNull(String s) { String sOld = s; s = dropPrefixICTrim_orNull(myPrefix(), s); if (s == null) print("no got prefix: " + quote(myPrefix()) + " / " + quote(sOld)); return s; } String processLine(String s, Object... __) { s = preprocess(s, __); return processSimplifiedLine(s, __); } String preprocess(String s, Object... __) { print("Preprocessing: " + s); //pcall { print("mother: " + DynTalkBot2.this); } 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; } String myPrefix() { return preprocessAtSelfToMyName ? (endsWithLetterOrDigit(myName) ? myName + " " : myName) : (dropPunctuation ? replace(atSelf(), "@", "") /* @ is killed by preprocessing */ : atSelf()) + " "; } synchronized Lock myLock() { if (lock == null) lock = lock(); return lock; } // extend me String processSimplifiedLine(String input, Object... __) { Lock __0 = myLock(); lock(__0); try { Matches m = new Matches(); input = dropMyPrefixOrNull(input); if (input == null) return null; if (ngbCommands) { 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 __3 = checkAuth(__); if (!empty(__3)) return __3; setAdd(authorizedUsers, parseFirstLong(m.rest())); change(); return "Okidoki. Have " + n2(l(authorizedUsers), "master"); } if (eqic(input, "masters")) return renderMasters(); if (swic_trim(input, "delete master ", m)) { String __4 = checkAuth(__); if (!empty(__4)) return __4; remove(authorizedUsers, parseFirstLong(m.rest())); change(); return "Okidoki. Have " + n2(l(authorizedUsers), "master"); } if (swic_trim(input, "add guild master ", m)) { String __5 = checkPerGuildAuth(__); if (!empty(__5)) return __5; setAdd(guildAuthorizedUsers, parseFirstLong(m.rest())); change(); return "Okidoki. " + renderGuildMasters(); } if (eqic(input, "guild masters")) return renderGuildMasters(); if (swic_trim(input, "delete guild master ", m)) { String __6 = checkPerGuildAuth(__); if (!empty(__6)) return __6; remove(guildAuthorizedUsers, parseFirstLong(m.rest())); change(); return "Okidoki. " + renderGuildMasters(); } if (eqic(input, "guild count")) { String __7 = checkAuth(__); if (!empty(__7)) return __7; return renderGuildCount(); } if (eqic(input, "guild names")) { String __8 = checkAuth(__); if (!empty(__8)) return __8; return renderGuildNames(); } return null; } finally { unlock(__0); } } String renderGuildMasters() { return empty(guildAuthorizedUsers) ? "Only this guild's owner can control me." : "I am controlled by this guild's owner and these people: " + joinWithComma(map("discordAtPlusID",guildAuthorizedUsers)); } String renderGuildCount() { return "Total guilds joined: " + guildCount + ". Live guilds: " + liveGuildCount(); } String renderGuildNames() { return lines(map(discord.getGuilds(), g -> g.getName())); } boolean authed(Object... __) { return contains(authorizedUsers, optPar("userID",__)); } boolean perGuildAuthed(Object... __) { long userID = longPar("userID",__); return contains(guildAuthorizedUsers, userID) || guildID != 0 && userID == getGuild().getOwner().getUser().getIdLong(); } Guild getGuild() { return guildID == 0 ? null : discord.getGuildById(guildID); } 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; } String checkPerGuildAuth(Object... __) { long userID = longPar("userID",__); boolean result = perGuildAuthed(__); print("Guild-auth-checking user ID: " + userID + " => " + result); if (!result) return "You are not authorized"; return null; } String guildStructure() { return structure_nullingInstancesOfClass(_getClass(module()), this); } } // end of class ByServer String serveGuildBackup(MessageChannel channel, Guild guild, String data) { if (guild == null) return "Do this in a guild"; if (containsDiscordToken(data)) return "DISCORD TOKEN EXPOSED ALARM!! NOTIFY ADMINISTRATOR"; String baseName = urlencode(jda_selfUserName(discord)) + "-" + guild.getIdLong() + "-" + ymd_minus_hms(); String zipName = baseName + ".zip"; File zip = programFile("backups/" + zipName); createZipFileWithSingleTextFile(zip, baseName + ".txt", data); channel.sendMessage("Here's my latest brain contents for this guild.").addFile(zip).queue(); return null; } // use structure() on ByServer String serveGuildBackup(MessageChannel channel, Guild guild, ByServer bs) { return serveGuildBackup(channel, guild, bs.guildStructure()); } // e.g. for help texts String atSelfOrMyName() { return preprocessAtSelfToMyName ? myName : atSelf(); } String atSelfOrMyName_space() { return preprocessAtSelfToMyName ? appendSpaceIfEndsWithLetter(myName) : atSelf(); } String renderMasters() { return empty(authorizedUsers) ? "I have no masters." : "My masters are: " + joinWithComma(map("discordAtPlusID",authorizedUsers)); } }static class T3 { A a; B b; C c; T3() {} T3(A a, B b, C c) { this.c = c; this.b = b; this.a = a;} T3(T3 t) { a = t.a; b = t.b; c = t.c; } public int hashCode() { return _hashCode(a) + 2*_hashCode(b) - 4*_hashCode(c); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof T3)) return false; T3 t = (T3) o; return eq(a, t.a) && eq(b, t.b) && eq(c, t.c); } public String toString() { return "(" + quoteBorderless(a) + ", " + quoteBorderless(b) + ", " + quoteBorderless(c) + ")"; } }static class Pair implements Comparable> { A a; B b; Pair() {} Pair(A a, B b) { this.b = b; this.a = a;} public int hashCode() { return hashCodeFor(a) + 2*hashCodeFor(b); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Pair)) return false; Pair t = (Pair) o; return eq(a, t.a) && eq(b, t.b); } public String toString() { return "<" + a + ", " + b + ">"; } public int compareTo(Pair p) { if (p == null) return 1; int i = ((Comparable) a).compareTo(p.a); if (i != 0) return i; return ((Comparable) b).compareTo(p.b); } }static class FunctionNameAndPattern implements IFieldsToList{ String function; String pattern; FunctionNameAndPattern() {} FunctionNameAndPattern(String function, String pattern) { this.pattern = pattern; this.function = function;} public String toString() { return shortClassName(this) + "(" + function + ", " + pattern + ")"; } public boolean equals(Object o) { if (!(o instanceof FunctionNameAndPattern)) return false; FunctionNameAndPattern __1 = (FunctionNameAndPattern) o; return eq(function, __1.function) && eq(pattern, __1.pattern); } public int hashCode() { int h = -413151044; h = boostHashCombine(h, _hashCode(function)); h = boostHashCombine(h, _hashCode(pattern)); return h; } public Object[] _fieldsToList() { return new Object[] {function, pattern}; } }// it's unclear whether the end is inclusive or exclusive // (usually exclusive I guess) static class IntRange { int start, end; IntRange() {} IntRange(int start, int end) { this.end = end; this.start = start;} IntRange(IntRange r) { start = r.start; end = r.end; } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } final int length() { return end-start; } final boolean empty() { return start >= end; } static String _fieldOrder = "start end"; public String toString() { return "[" + start + ";" + end + "]"; } }static abstract class F0 { abstract A get(); }static abstract class F1 { abstract B get(A a); }// you still need to implement hasNext() and next() static abstract class IterableIterator implements Iterator, Iterable { public Iterator iterator() { return this; } public void remove() { unsupportedOperation(); } }static class PhilosophyBot1 { static class LogicRule implements IFieldsToList, Transformable, Visitable{ Object lhs; Object rhs; LogicRule() {} LogicRule(Object lhs, Object rhs) { this.rhs = rhs; this.lhs = lhs;} public boolean equals(Object o) { if (!(o instanceof LogicRule)) return false; LogicRule __0 = (LogicRule) o; return eq(lhs, __0.lhs) && eq(rhs, __0.rhs); } public int hashCode() { int h = 274479962; h = boostHashCombine(h, _hashCode(lhs)); h = boostHashCombine(h, _hashCode(rhs)); return h; } public Object[] _fieldsToList() { return new Object[] {lhs, rhs}; } public Object transformUsing(IF1 f) { return new LogicRule(f.get(lhs), f.get(rhs)); } public void visitUsing(IVF1 f) { f.get(lhs); f.get(rhs); } int n; // when added Object trail; public String toString() { return (n == 0 ? "" : "[" + n + "] ") + lhs + " => " + rhs; } } static class And implements IFieldsToList, Transformable, Visitable{ Object a; Object b; And() {} And(Object a, Object b) { this.b = b; this.a = a;} public String toString() { return shortClassName(this) + "(" + a + ", " + b + ")"; } public boolean equals(Object o) { if (!(o instanceof And)) return false; And __1 = (And) o; return eq(a, __1.a) && eq(b, __1.b); } public int hashCode() { int h = 65975; h = boostHashCombine(h, _hashCode(a)); h = boostHashCombine(h, _hashCode(b)); return h; } public Object[] _fieldsToList() { return new Object[] {a, b}; } public Object transformUsing(IF1 f) { return new And(f.get(a), f.get(b)); } public void visitUsing(IVF1 f) { f.get(a); f.get(b); } } static class If implements IFieldsToList, Transformable, Visitable{ Object condition; Object thenBlock; Object elseBlock; If() {} If(Object condition, Object thenBlock, Object elseBlock) { this.elseBlock = elseBlock; this.thenBlock = thenBlock; this.condition = condition;} public String toString() { return shortClassName(this) + "(" + condition + ", " + thenBlock + ", " + elseBlock + ")"; } public boolean equals(Object o) { if (!(o instanceof If)) return false; If __2 = (If) o; return eq(condition, __2.condition) && eq(thenBlock, __2.thenBlock) && eq(elseBlock, __2.elseBlock); } public int hashCode() { int h = 2365; h = boostHashCombine(h, _hashCode(condition)); h = boostHashCombine(h, _hashCode(thenBlock)); h = boostHashCombine(h, _hashCode(elseBlock)); return h; } public Object[] _fieldsToList() { return new Object[] {condition, thenBlock, elseBlock}; } public Object transformUsing(IF1 f) { return new If(f.get(condition), f.get(thenBlock), f.get(elseBlock)); } public void visitUsing(IVF1 f) { f.get(condition); f.get(thenBlock); f.get(elseBlock); } } static class For implements IFieldsToList, Transformable, Visitable{ Object var; Object condition; Object body; For() {} For(Object var, Object condition, Object body) { this.body = body; this.condition = condition; this.var = var;} public String toString() { return shortClassName(this) + "(" + var + ", " + condition + ", " + body + ")"; } public boolean equals(Object o) { if (!(o instanceof For)) return false; For __3 = (For) o; return eq(var, __3.var) && eq(condition, __3.condition) && eq(body, __3.body); } public int hashCode() { int h = 70825; h = boostHashCombine(h, _hashCode(var)); h = boostHashCombine(h, _hashCode(condition)); h = boostHashCombine(h, _hashCode(body)); return h; } public Object[] _fieldsToList() { return new Object[] {var, condition, body}; } public Object transformUsing(IF1 f) { return new For(f.get(var), f.get(condition), f.get(body)); } public void visitUsing(IVF1 f) { f.get(var); f.get(condition); f.get(body); } } // don't need var actually static class ForIn implements IFieldsToList, Transformable, Visitable{ Object var; Object expr; Object body; ForIn() {} ForIn(Object var, Object expr, Object body) { this.body = body; this.expr = expr; this.var = var;} public String toString() { return shortClassName(this) + "(" + var + ", " + expr + ", " + body + ")"; } public boolean equals(Object o) { if (!(o instanceof ForIn)) return false; ForIn __4 = (ForIn) o; return eq(var, __4.var) && eq(expr, __4.expr) && eq(body, __4.body); } public int hashCode() { int h = 68065198; h = boostHashCombine(h, _hashCode(var)); h = boostHashCombine(h, _hashCode(expr)); h = boostHashCombine(h, _hashCode(body)); return h; } public Object[] _fieldsToList() { return new Object[] {var, expr, body}; } public Object transformUsing(IF1 f) { return new ForIn(f.get(var), f.get(expr), f.get(body)); } public void visitUsing(IVF1 f) { f.get(var); f.get(expr); f.get(body); } } static class Assignment implements IFieldsToList, Transformable, Visitable{ Object var; Object expr; Assignment() {} Assignment(Object var, Object expr) { this.expr = expr; this.var = var;} public String toString() { return shortClassName(this) + "(" + var + ", " + expr + ")"; } public boolean equals(Object o) { if (!(o instanceof Assignment)) return false; Assignment __5 = (Assignment) o; return eq(var, __5.var) && eq(expr, __5.expr); } public int hashCode() { int h = -1275239699; h = boostHashCombine(h, _hashCode(var)); h = boostHashCombine(h, _hashCode(expr)); return h; } public Object[] _fieldsToList() { return new Object[] {var, expr}; } public Object transformUsing(IF1 f) { return new Assignment(f.get(var), f.get(expr)); } public void visitUsing(IVF1 f) { f.get(var); f.get(expr); } } static class While implements IFieldsToList, Transformable, Visitable{ Object condition; Object body; While() {} While(Object condition, Object body) { this.body = body; this.condition = condition;} public String toString() { return shortClassName(this) + "(" + condition + ", " + body + ")"; } public boolean equals(Object o) { if (!(o instanceof While)) return false; While __6 = (While) o; return eq(condition, __6.condition) && eq(body, __6.body); } public int hashCode() { int h = 83548945; h = boostHashCombine(h, _hashCode(condition)); h = boostHashCombine(h, _hashCode(body)); return h; } public Object[] _fieldsToList() { return new Object[] {condition, body}; } public Object transformUsing(IF1 f) { return new While(f.get(condition), f.get(body)); } public void visitUsing(IVF1 f) { f.get(condition); f.get(body); } } // native predicate return type (Bool/SS/null) // like a native predicate, but doesn't return anything static class CodeFragment { String head; IVF2, Env> body; boolean keepBrackets = false; CodeFragment(String head, IVF2, Env> body, boolean keepBrackets) { this.keepBrackets = keepBrackets; this.body = body; this.head = head;} CodeFragment(String head, IVF2, Env> body) { this.body = body; this.head = head;} public String toString() { return stdToString(this); } } static class Env { boolean wantAlternatives = false; boolean wantAlternatives() { return wantAlternatives; } } static class WithAlternative implements IFieldsToList{ IF0 alternative; Object result; WithAlternative() {} WithAlternative(IF0 alternative, Object result) { this.result = result; this.alternative = alternative;} public String toString() { return shortClassName(this) + "(" + alternative + ", " + result + ")"; } public boolean equals(Object o) { if (!(o instanceof WithAlternative)) return false; WithAlternative __9 = (WithAlternative) o; return eq(alternative, __9.alternative) && eq(result, __9.result); } public int hashCode() { int h = -1195262233; h = boostHashCombine(h, _hashCode(alternative)); h = boostHashCombine(h, _hashCode(result)); return h; } public Object[] _fieldsToList() { return new Object[] {alternative, result}; } } // body takes variable mapping // body can return // Bool => immediate result (ok or fail) // SS => variable mapping // WithAlternative // Iterator // null => not applicable // For "for $x in ..." statements, return a Iterable? static class NativePredicate implements IFieldsToList{ static final String _fieldOrder = "head body"; String head; IF2, Env, Object> body; NativePredicate() {} NativePredicate(String head, IF2, Env, Object> body) { this.body = body; this.head = head;} public String toString() { return shortClassName(this) + "(" + head + ", " + body + ")"; } public boolean equals(Object o) { if (!(o instanceof NativePredicate)) return false; NativePredicate __10 = (NativePredicate) o; return eq(head, __10.head) && eq(body, __10.body); } public int hashCode() { int h = 1520196416; h = boostHashCombine(h, _hashCode(head)); h = boostHashCombine(h, _hashCode(body)); return h; } public Object[] _fieldsToList() { return new Object[] {head, body}; } } // procedures are a list of statements // trail of a transformed fact static class TTransformed implements IFieldsToList{ String fact; IF1 transformer; TTransformed() {} TTransformed(String fact, IF1 transformer) { this.transformer = transformer; this.fact = fact;} public String toString() { return shortClassName(this) + "(" + fact + ", " + transformer + ")"; } public boolean equals(Object o) { if (!(o instanceof TTransformed)) return false; TTransformed __11 = (TTransformed) o; return eq(fact, __11.fact) && eq(transformer, __11.transformer); } public int hashCode() { int h = 1921333271; h = boostHashCombine(h, _hashCode(fact)); h = boostHashCombine(h, _hashCode(transformer)); return h; } public Object[] _fieldsToList() { return new Object[] {fact, transformer}; } } transient String program; transient boolean programLoaded = false; transient int maxRounds = 1000; transient int maxFacts = 1000; transient Set facts = syncLinkedCISet(); transient Set originalFacts = ciSet(); transient LinkedHashSet logicRules = new LinkedHashSet(); // modified with sync transient AllOnAll rulesOnFacts = new AllOnAll(); transient AllOnAll codeOnFacts = new AllOnAll(); transient AllOnAllWithUpdates, String> anyCodeOnFacts = new AllOnAllWithUpdates(); transient AllOnAll/*WithUpdates*/, LogicRule> anyCodeOnRules = new AllOnAll(); transient List proceduresToRun = new ArrayList(); // parsed procedures transient long proceduresExecuted; transient List nativePredicates = new ArrayList(); transient boolean debugNativeCalls = true, debugAllCmds = true; transient boolean verbose = true; transient boolean printStackTraces = false; transient List onProcedureEnded = new ArrayList(); transient List> onLogicRuleAdded = new ArrayList(); transient List> onFactAdded = new ArrayList(); transient boolean printNonMatches, debugContradictionChecks; transient boolean standardImportsLoaded = false; transient boolean curryAllRules = true; // rewrite "a & b => c" to a => b => c transient int logicRulesCounter; transient boolean thoughtBegun = false; transient boolean printFactsAfterThinking = true; transient boolean noteSimplificationsAsFacts = false; // not a good idea - leads to endless loops transient boolean parsing = false; // return true when you handled adding the rule transient List> logicRulePreprocessors = new ArrayList(); // return true when you handled adding the fact transient List> factPreprocessors = new ArrayList(); // extra stuff that is done every round transient List extraLogicOperations = new ArrayList(); transient Set vars = litciset("x", "y", "z"); // phrase replacements that are made in every fact. // functionality is enabled by philosophyBot1_addDeepReplacement transient Map deepReplacements; transient List> deepTransformers; transient List>> trailEnabledDeepTransformers; // fact -> trail. to enable, initialize with ciMap() transient Map trails; Map extensions; PhilosophyBot1() { // find contradictions anyCodeOnFacts.newA(fact -> { Boolean b = checkNativeCondition(fact); if (debugContradictionChecks) print("Fact check: " + b + " - " + fact); if (isFalse(b)) addFactWithTrail("contradiction", trails == null ? null : fact); }); _standardHandlers(); } PhilosophyBot1(String program) { this(); this.program = program; } void addRule(String s) { Pair p = splitAtFirstDoubleArrow(javaTokWithBrackets(s)); if (p == null) if (verbose) print("addRule failed: " + s); addLogicRuleWithTrail(new LogicRule(splitAtAmpersand2(p.a), p.b), litorderedmap("op" , "addRule", "s", s)); } void addRules(Iterable l) { for (String s : unnull(l)) addRule(s); } Object splitRuleRHS(Object rhs) { if (rhs instanceof String) { Pair p = splitAtFirstDoubleArrow(javaTokWithBrackets(((String) rhs))); if (p != null) return splitRuleRHS(new LogicRule(splitAtAmpersand2(p.a), splitRuleRHS(p.b))); return splitAtAmpersand2(((String) rhs)); } return rhs; } LogicRule curryLHS(LogicRule rule) { while (licensed()) { Object lhs = rule.lhs; if (lhs instanceof And) { Object a = ((And) lhs).a; Object b = ((And) lhs).b; LogicRule r = rule; rule = new LogicRule(a, new LogicRule(b, rule.rhs)); rule.trail = r.trail; } else break; } return rule; } void addLogicRuleWithTrail(LogicRule rule, Object trail) { rule.trail = trail; addLogicRule(rule); } void addLogicRule(LogicRule rule, String originalText) { //print("originalText=" + originalText + " for " + rule); addLogicRuleWithTrail(rule, originalText); } void addLogicRule(LogicRule rule) { rule.rhs = splitRuleRHS(rule.rhs); if (curryAllRules) rule = curryLHS(rule); for (IF1 p : logicRulePreprocessors) if (p.get(rule)) return; // has been preprocessed rule.n = ++logicRulesCounter; if (printStackTraces) printStackTrace(str(rule)); if (trails != null && rule.trail == null) if (parsing) rule.trail = "initial rule"; else throw fail("No trail for rule: " + rule); // is LHS a native predicate? then eval immediately // TODO: multiple conditions Boolean b = checkConditionOpt(rule.lhs); if (isFalse(b)) return; // drop rule if (isTrue(b)) addRewrittenRHS(rule.rhs, rule); if (syncAdd(logicRules, rule)) { if (verbose) print("Got logic rule", rule); pcallFAll(onLogicRuleAdded, rule); anyCodeOnRules.newB(rule); rulesOnFacts.newA(rule); // to combine it with the facts } } void addFacts(Iterable l) { for (String fact : unnull(l)) addFact(fact); } void addFactWithTrail(WithTrail fact) { if (fact != null) addFactWithTrail(fact.get(), fact.trail); } void addFactWithTrail(String fact, Object trail) { String cleaned = addFact(fact); setTrail(cleaned, trail); } void setTrail(String fact, Object trail) { mapPut(trails, fact, trail); } // return cleaned version String addFact(String fact) { ping(); fact = trim(fact); if (empty(fact)) return null; if (l(facts) >= maxFacts) return null; fact = tok_deRoundBracket(fact); if (printStackTraces) printStackTrace("Adding fact: " + fact); if (parsing && getTrail(fact) == null) setTrail(fact, "initial fact"); for (IF1 p : factPreprocessors) if (p.get(fact)) return null; // has been preprocessed // Check if it's a procedure List tok = mainTokenize(fact); if (countCodeTokens(tok) == 2 && firstTokenEqic(tok, "proc") && isCurlyBracketed(getCodeToken(tok, 1))) { try { // It's a procedure! String proc = uncurly_keepSpaces(getCodeToken(tok, 1)); if (proceduresToRun.add(parseProcedure(proc))) { if (verbose) print("Got procedure:"); if (verbose) print(indentx("> ", proc)); } } catch (Throwable __e) { _handleException(__e); }} /*else if (countCodeTokens(tok) == 2 && firstTokenEqic(tok, "java") && isCurlyBracketed(getCodeToken(tok, 1))) pcall { // It's Java code }*/ else // It's a fact, not a procedure if (facts.add(fact)) { if (verbose) print("Got fact: " + fact); pcallFAll(onFactAdded, fact); rulesOnFacts.newB(fact); // to combine it with the rules codeOnFacts.newB(fact); anyCodeOnFacts.newB(fact); } return fact; } void addRewrittenRHS(Object o, Object trail) { if (o instanceof LogicRule) addLogicRuleWithTrail(((LogicRule) o), trail); else if (o instanceof And) { Object a = ((And) o).a; Object b = ((And) o).b; addRewrittenRHS(a, o); addRewrittenRHS(b, o); } else if (o != null) addFactWithTrail((String) o, trail); } void addFactFromProgram(String fact) { if (countJavaTokens(fact) == 0) return; fact = javaDropAllComments(fact); originalFacts.add(fact); addFact(fact); } void runProcedure(String proc) { try { if (verbose) print("Running procedure."); runParsedProcedure(parseProcedure(proc)); } catch (Throwable __e) { _handleException(__e); }} void runParsedProcedure(List commands) { runParsedProcedure(commands, proceduresToRun); } void runParsedProcedure(List commands, List whereToPostCode) { ++proceduresExecuted; Env env = new Env(); List remainingCommands = cloneLinkedList(commands); Object cmd; while ((cmd = popFirst_ping(remainingCommands)) != null) { if (cmd instanceof List) { runParsedProcedure(((List) cmd)); continue; } if (cmd instanceof Runnable) { ((Runnable) cmd).run(); continue; } if (debugAllCmds) print("Running cmd: " + sfu(cmd)); if (cmd instanceof If) { Object condition = ((If) cmd).condition; Object thenBlock = ((If) cmd).thenBlock; Object elseBlock = ((If) cmd).elseBlock; Object blockToRun = checkCondition(condition) ? thenBlock : elseBlock; runParsedProcedure(ll(blockToRun)); } else if (cmd instanceof For) { Object var = ((For) cmd).var; Object condition = ((For) cmd).condition; Object body = ((For) cmd).body; // make a new logic rule and add it // assume the variable is globally declared as a variable addLogicRuleWithTrail(new LogicRule(condition, "proc {\n" + body + "\n}"), litorderedmap("op" , "for")); } else if (cmd instanceof While) { Object condition = ((While) cmd).condition; Object body = ((While) cmd).body; boolean b = checkCondition(condition); if (!b) continue; whereToPostCode.add(ll(body, cmd)); } else if (cmd instanceof Assignment && ((Assignment) cmd).var instanceof String && ((Assignment) cmd).expr instanceof String) { String var = (String) (((Assignment) cmd).var); String expr = (String) (((Assignment) cmd).expr); String result = (String) (runNativePredicate(expr, new Env())); Map mapping = litcimap(var, result); remainingCommands = mapToLinkedList(remainingCommands, c -> replaceVars(c, mapValues(__87 -> optRound(__87),mapping))); } else if (cmd instanceof ForIn && ((ForIn) cmd).var instanceof String && ((ForIn) cmd).expr instanceof String) { String var = (String) (((ForIn) cmd).var); String expr = (String) (((ForIn) cmd).expr); Object body = ((ForIn) cmd).body; // XXX Object result = runNativePredicate(expr, new Env()); if (!(result instanceof Iterable)) { if (verbose) print("Warning: result of " + expr + " not iterable (" + shortClassName(result) + ")"); continue; } Iterator it = iterator((Iterable) result); Runnable step = new Runnable() { public void run() { try { if (!it.hasNext()) return; String value = str(it.next()); Map map = litcimap(var, value); Object body2 = replaceVars(body, map); //print("ForIn: " + map + " => " + body2); whereToPostCode.add(ll(body2, this)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) return;\r\n String value = str(it.next());\r\n ..."; }}; step.run(); } else if (cmd instanceof String) { Object result = runNativePredicate(((String) cmd), env); if (result != null) { result = unpackWithAlternativeOrIterator(result); if (isFalse(result)) return; if (isTrueOpt(result)) continue; if (result instanceof String) { addFact(((String) result)); continue; } Map mapping = (Map) result; // assume it's a variable mapping // apply to all remaining commands and continue List remainingCommands2 = mapToLinkedList(remainingCommands, c -> replaceVars(c, mapValues(__88 -> optRound(__88),mapping))); if (verbose) print("Applying var mapping " + mapping + " to " + remainingCommands + " => " + remainingCommands2); remainingCommands = remainingCommands2; } else addFact(((String) cmd)); } else if (cmd != null) throw fail("Unimplemented command: " + cmd); } pcallFAll(onProcedureEnded, commands); // notify listeners } // return var mapping (SS), Bool or null for no matching predicate // or result verbatim (e.g. Iterable) Object runNativePredicate(String s, Env env) { for (NativePredicate np : nativePredicates) { Map map = zipIt(np.head, s); if (map != null) { try { Object result = np.body.get(mapValues(__89 -> tok_deRoundBracket(__89),map), env); if (debugNativeCalls) print("Native predicate result: " + np.head + " => " + result); if (result instanceof Map && nempty(map)) { result = mapKeys((Map) result, var -> lookupOrKeep(map, var)); if (debugNativeCalls) print("Rewrote native predicate result: " + result); } { Object __8= result; if (__8 != null) return __8; } } catch (Throwable e) { handleException(e); } } else if (printNonMatches) print("Non-match: " + quote(np.head) + " / " + quote(s)); } return null; } // returns false if unknown boolean checkCondition(Object o) { return isTrue(checkConditionOpt(o)); } // returns null if unknown Boolean checkConditionOpt(Object o) { if (o instanceof String) { if (contains(facts, ((String) o))) return true; { Boolean b = checkNativeCondition(((String) o)); if (b != null) return b; } } //print("Ignoring condition: " + o); return null; } Boolean checkNativeCondition(String o) { Object result = runNativePredicate(o, new Env()); result = unpackWithAlternativeOrIterator(result); if (result instanceof Boolean) return ((Boolean) result); if (result instanceof Map) return true; // TODO return null; } boolean parsePythonesqueProcedure_debug = false; List parsePythonesqueProcedure(String proc) { //printStruct(proc); proc = withoutLinesEmptyAfterTrim(proc); //printStruct(proc); //proc = autoUnindent(proc); proc = autoUnindent_honoringBrackets(proc); //printStruct(proc); //print(indentx("> ", proc)); List l = groupPythonStyleIndents_honoringBrackets(proc); //pnl("unpythonized ", l); List out = new ArrayList(); If lastIf = null; for (int i = 0; i < l(l); i++) { String s = l.get(i); List tok = javaTokWithBrackets(s); if (eqic(firstCodeToken(tok), "if")) { assertEquals(s, ":", getCodeToken(tok, 2)); out.add(lastIf = new If(deRoundBracket(getCodeToken(tok, 1)), parsePythonesqueProcedure(joinSubList(tok, 3*2)), null)); continue; } if (eqic(firstCodeToken(tok), "unless")) { assertEquals(s, ":", getCodeToken(tok, 2)); out.add(lastIf = new If(deRoundBracket(getCodeToken(tok, 1)), null, parsePythonesqueProcedure(joinSubList(tok, 3*2)))); continue; } if (eqic(firstCodeToken(tok), "while")) { assertEquals(s, ":", getCodeToken(tok, 2)); out.add(new While(deRoundBracket(getCodeToken(tok, 1)), parsePythonesqueProcedure(joinSubList(tok, 3*2)))); continue; } if (eqic(firstCodeToken(tok), "else") && eqic(secondCodeToken(tok), "if")) { Object last = last(out); if (lastIf == null) throw fail("Else if without if"); assertEquals(s, ":", getCodeToken(tok, 3)); lastIf.elseBlock = lastIf = new If(deRoundBracket(getCodeToken(tok, 2)), parsePythonesqueProcedure(joinSubList(tok, 4*2)), null); continue; } if (eqic(firstCodeToken(tok), "else")) { Object last = last(out); if (lastIf == null) throw fail("Else without if"); assertEquals(s, ":", getCodeToken(tok, 1)); lastIf.elseBlock = joinSubList(tok, 2*2); continue; } // assignment if (eqGet(tok, 3, ":") && eqGet(tok, 5, "=")) { out.add(new Assignment(get(tok, 1), joinSubList(tok, 7))); continue; } lastIf = null; if (eqic(firstCodeToken(tok), "for")) { if (eq(getCodeToken(tok, 2), "in")) { int idx = indexOf(tok, ":"); assertTrue(s, idx >= 0); String var = getCodeToken(tok, 1); String expr = joinSubList(tok, 3*2+1, idx-1); Object body = parsePythonesqueProcedure(joinSubList(tok, idx+1)); out.add(new ForIn(var, expr, body)); } else { assertEquals(s, ":", getCodeToken(tok, 2)); String cond = getCodeToken(tok, 1); // cond looks like: "(y | x has a y)" cond = deRoundBracket(cond); List tok2 = javaTok(cond); assertEquals(cond, "|", getCodeToken(tok2, 1)); String var = assertIdentifier(cond, getCodeToken(tok2, 0)); String actualCondition = trimJoinSubList(tok2, 2*2+1); out.add(new For(var, actualCondition, parsePythonesqueProcedure(joinSubList(tok, 3*2)))); } } else out.add(s); } if (parsePythonesqueProcedure_debug) pnl("Parsed procedure ", out); return out; } List parseProcedure(String s) { return parsePythonesqueProcedure(s); } Object splitAtAmpersand2(String s) { List l = tok_splitAtAmpersand(s); if (l(l) == 1) return s; return new And(first(l), splitAtAmpersand2(join(" & ", dropFirst(l)))); } // "zip" a condition with a fact (match word-by-word) Map zipIt(String cond, String fact) { Map map = zipIt_keepBrackets(cond, fact); if (map == null) return null; // no match map = mapValues(__90 -> tok_deRoundOrCurlyBracket(__90),map); // handle special case, e.g. "i am x", "i am (x)" removeFromMapWhere(map, (k, v) -> eqic(k, v)); return map; } Map zipIt_deBracket(String pat, String s) { Map map = zipIt(pat, s); return map == null ? null : mapValues(__91 -> tok_deRoundOrCurlyBracket(__91),map); } // "zip" a condition with a fact (match word-by-word) Map zipIt_keepBrackets(String cond, String fact) { Map map = gazelle_deepZip_keepBrackets(cond, fact); if (map == null) return null; // no match if (!all(keys(map), s -> isVar(s))) return null; /*with print("Non-variable changes, exiting")*/; return map; } boolean isVar(String s) { return s != null && (vars.contains(s) || s.startsWith("var_") || isDollarVar(s)); } Object replaceVars(Object o, Map map) { if (empty(map)) return o; return transform(x -> replaceVars_base(x, map), o); } Object replaceVars_base(Object o, Map map) { if (o instanceof String) return replaceCodeTokensUsingMap(((String) o), map); return null; } String format(String s, Map map) { return replaceCodeTokensUsingMap(s, mapValues(__92 -> optRound(__92),map)); } // if f returns null, go through structure Object transform(IF1 f, Object o) { return transform_understandsTransformableAndList(f, o); } void applyLogicRuleToFact(LogicRule rule, String fact) { Object lhs = rule.lhs, rhs = rule.rhs; Object cond, remaining = null; if (lhs instanceof And) { Object a = ((And) lhs).a; Object b = ((And) lhs).b; cond = a; remaining = b; } else cond = lhs; // now we match the condition with the fact Map map = zipIt_keepBrackets((String) cond, fact); if (map == null) { if (printNonMatches) print("Non-match: " + quote(cond) + " / " + quote(fact)); return; // no match } // Now we have a proper mapping with the keys being variables! if (verbose) print("Match: " + quote(cond) + " / " + quote(fact)); // drop round brackets // XXX? map = mapValues tok_deRoundBracket(map); // Apply mapping to right hand side Object rhs_replaced = replaceVars(rhs, map); if (verbose) print("rhs_replaced", rhs_replaced); Map trail = litorderedmap("op" , "applyLogicRuleToFact", "rule", rule, "fact", fact, "rhs_replaced", rhs_replaced, "remaining", remaining); if (remaining == null) { // No more conditions. Add as fact / new rule addRewrittenRHS(rhs_replaced, trail); } else { // Apply mapping to remaining condition Object remaining_replaced = replaceVars(remaining, map); trail.put("remaining_replaced", remaining_replaced); addLogicRuleWithTrail(new LogicRule(remaining_replaced, rhs_replaced), trail); } } public void run() { think(); } boolean smartParser1_verbose = false; void smartParser1(String program) { // split into paragraphs and unindent List paragraphs = map(s -> withoutLeadingLinesEmptyAfterTrim_autoUnindent(rtrim(s)), tok_splitAtEmptyLines(program)); if (smartParser1_verbose) print("Got " + n2(paragraphs, "parapraph")); // print the parapraphs if (smartParser1_verbose) print(joinWithEmptyLines(map(s -> indentx("> ", s), paragraphs))); // throw away comment-only and quoted paragraphs (assume it's a title) List paragraphs2 = antiFilter(paragraphs, s -> isSingleLine(trim(s)) && isQuoted(trim(s)) || countJavaTokens(s) == 0 || endsWith(rtrim(s), "----")); if (smartParser1_verbose) print("Got " + n2(paragraphs2, "filtered paragraph")); if (smartParser1_verbose) print(joinWithEmptyLines(map(s -> indentx("> ", s), paragraphs2))); // find fact paragraphs if (smartParser1_verbose) print(map("allLinesAreUnindented",paragraphs2)); Pair, List> p1 = filterAntiFilter(s -> !isSingleLine(trim(s)) && allLinesAreUnindented(s), paragraphs2); List multiFactParagraphs = p1.a, paragraphs3 = p1.b; for (String para : multiFactParagraphs) for (String s : tlft(para)) addFactFromProgram(s); // find logic rules List paragraphs4 = new ArrayList(); for (String para : paragraphs3) { Pair p = splitAtFirstDoubleArrow(javaTokWithBrackets(para)); if (p == null) { paragraphs4.add(para); continue; } addLogicRule(new LogicRule(splitAtAmpersand2(p.a), p.b), para); } if (smartParser1_verbose) pnlStruct("Unparsed - assuming facts", paragraphs4); // assume the unparsed stuff consists of facts for (String para : paragraphs4) addFactFromProgram(para); } void parseProgram() { if (programLoaded) return; programLoaded = true; loadProgram(program); } void loadProgram(String program) { parsing = true; try { smartParser1(program); } finally { parsing = false; } } boolean doSomeLogic() { boolean anyAction = false; Pair p; while ((p = rulesOnFacts.next()) != null) { ping(); anyAction = true; //print("Combination: " + p); applyLogicRuleToFact(p.a, p.b); } Pair p2; while ((p2 = codeOnFacts.next()) != null) { ping(); anyAction = true; //print("Combination: " + p2); applyCodeFragmentToFact(p2.a, p2.b); } Pair, String> p3; while ((p3 = anyCodeOnFacts.next()) != null) { ping(); anyAction = true; //print("Combination: " + p3); pcallF(p3.a, p3.b); } Pair, LogicRule> p4; while ((p4 = anyCodeOnRules.next()) != null) { ping(); anyAction = true; pcallF(p4.a, p4.b); } return anyAction; } void applyCodeFragmentToFact(CodeFragment cf, String fact) { Map map = cf.keepBrackets ? zipIt_keepBrackets(cf.head, fact) : zipIt(cf.head, fact); if (map != null) cf.body.get(mapValues(__93 -> tok_deRoundBracket(__93),map), new Env()); } // indicator for end of thought process (when this stays stable) long size() { return l(logicRules) + l(facts) + proceduresExecuted; } void think() { parseProgram(); thoughtBegun = true; int round = 0; while (round++ < maxRounds) { ping(); long lastSize = size(); if (verbose) print("Logic round " + round + ", size: " + lastSize); while (doSomeLogic() && round++ < maxRounds && l(facts) < maxFacts) {} for (List proc : getAndClearList(proceduresToRun)) { ping(); runParsedProcedure(proc); } callFAll(extraLogicOperations); if (size() == lastSize) { if (verbose) print("No changes, exiting"); break; } } // We're done logicking, so print all the facts gathered Collection madeFacts = factsDeduced(); if (printFactsAfterThinking) pnlWithHeading("Facts I deduced", madeFacts); // Print say () and print () separately List output = new ArrayList(); for (String fact : madeFacts) { List tok = mainTokenize(fact); if (countCodeTokens(tok) == 2 && eqicOneOf(getCodeToken(tok, 0), "print", "say")) // For the user, we print without all the round brackets output.add(tok_dropRoundBrackets(getCodeToken(tok, 1))); } pnlWithHeadingIfNempty("Bot Output", output); } void addNativePredicate(String head, IF0 body) { nativePredicates.add(new NativePredicate(head, (map, env) -> body.get())); } void addNativePredicate(String head, IF1, Object> body) { nativePredicates.add(new NativePredicate(head, (map, env) -> body.get(map))); } void addNativePredicate(String head, IF2, Env, Object> body) { nativePredicates.add(new NativePredicate(head, body)); } // when you only need one result Object unpackWithAlternativeOrIterator(Object result) { if (result instanceof Iterator) return first((Iterator) result); if (result instanceof WithAlternative) return ((WithAlternative) result).result; return result; } void onFactDo(String head, IVF2, Env> body) { codeOnFacts.newA(new CodeFragment(head, body)); } void onFactDo_keepBrackets(String head, IVF2, Env> body) { codeOnFacts.newA(new CodeFragment(head, body, true)); } List filterByPattern(String pat, Iterable items) { return filter(items, i -> zipIt(pat, i) != null); } // pat = pattern with variables // results are mappings with debracketed values List> matchFacts(String pat) { return matchStrings(pat, facts); } Map matchString(String pat, String input) { return zipIt_deBracket(pat, input); } List> matchStrings(String pat, Iterable items) { List> out = new ArrayList(); for (String s : items) { Map map = zipIt_deBracket(pat, s); if (map != null) out.add(map); } return out; } List>> matchFacts2(String pat) { return matchStrings2(pat, facts); } // returns items too List>> matchStrings2(String pat, Iterable items) { List>> out = new ArrayList(); for (String s : items) { Map map = zipIt_deBracket(pat, s); if (map != null) out.add(pair(s, map)); } return out; } List matchFacts(String var, String pat) { return map(matchFacts(pat), map -> map.get(var)); } // pat = pattern with variables // results are mappings with debracketed values List> matchFacts_keepBrackets(String pat) { List> out = new ArrayList(); for (String fact : facts) { Map map = zipIt_keepBrackets(pat, fact); if (map != null) out.add(map); } return out; } void openAllTheories() { for (Map map : matchFacts_keepBrackets("theory $x $y")) openTheory(tok_deRoundOrCurlyBracket(map.get("$x")), map.get("$y")); } void openTheory(String name) { for (Map map : matchFacts_keepBrackets("theory $x $y")) if (eqic(properUnquote(tok_deRoundBracket($x(map))), name)) { openTheory(name, $y(map)); return; } throw fail("Theory not defined: " + quote(name)); } void openTheory(String name, String body) { //print("Raw theory: " + quote(s)); loadProgram(withoutLeadingLinesEmptyAfterTrim_autoUnindent(tok_deRoundOrCurlyBracket_keepFirstSpacing(body))); if (verbose) print("Opened theory " + name); } void autoOpenTheories() { onFactDo_keepBrackets("theory $x $y", (map, env) -> openTheory(tok_deRoundOrCurlyBracket(map.get("$x")), map.get("$y"))); } // returns number of expectations checked int checkExpectations() { int n = 0; // check if all expect (...) facts are met for (Map map : matchFacts("expect $x")) { assertContains(facts, firstValue(map)); ++n; } // check if all don't expect (...) facts are met for (Map map : matchFacts("don't expect $x")) { assertDoesntContain(facts, firstValue(map)); ++n; } return n; } void standardImports() { if (standardImportsLoaded) return; standardImportsLoaded = true; registerImport("math", () -> philosophyBot1_math(this)); registerImport("bool", () -> philosophyBot1_bool(this)); registerImport("or", () -> philosophyBot1_orHandler(this)); registerImport("iota", () -> philosophyBot1_iotaHandler(this)); registerImport("tlft_honoringBrackets", () -> addNativePredicate("tlft_honoringBrackets $x", map -> printIf(verbose, "tlft output", tlft_honoringBrackets($x(map))))); addNativePredicate("printNonMatches", () -> { printNonMatches = true; return true; }); philosophyBot1_enableAddSimplifier_withTrails(this); } void addFactPreprocessor(IF1 f) { factPreprocessors.add(f); } void addLogicRulePreprocessor(IF1 f) { logicRulePreprocessors.add(f); } void registerImport(String name, Runnable handler) { String line = "import " + name; factPreprocessors.add(s -> { if (eqic(s, line)) { if (verbose) print("Importing " + name); handler.run(); return true; } return false; }); } boolean hasFact(String fact) { return contains(facts, fact); } boolean hasContradiction() { return hasFact("contradiction"); } List mainTokenize(String s) { return javaTokWithBrackets(s); } // sanitize untrusted input - overly safe version String sanitizeInput(String s) { return joinWithSpace(antiFilter(words2_plusApostrophe(s), w -> isVar(w))); } void deleteFacts(Iterable l) { Set set = asCISet(l); facts = filterCISet(facts, f -> !contains(set, f)); } Collection factsDeduced() { return listMinusList(facts, originalFacts); } Collection deducedFacts() { return factsDeduced(); } Collection factsDeducedAfterThought() { think(); return deducedFacts(); } boolean containsDollarVars(Object o) { // abuse transform function Flag flag = new Flag(); withCancelPoint(cp -> { transform(x -> { if (x instanceof String) { if (main.containsDollarVars(((String) x))) { flag.raise(); cancelTo(cp); } return ((String) x); } return null; }, o); }); return flag.get(); } List allLogicRulesWithoutLHSVars() { return filter(logicRules, r -> !containsDollarVars(leftmostCondition(r.lhs))); } Object leftmostCondition(Object o) { while (o instanceof And) o = ((And) o).a; return o; } void _standardHandlers() { philosophyBot_autoOpenTheoriesHandler(this); addFactPreprocessor(s -> { if (eqic(s, "standard imports")) { standardImports(); return true; } return false; }); } void runAndCheckExpectations() { run(); checkExpectations(); } void addDeepTransformer(IF1 transformer) { if (deepTransformers == null) { deepTransformers = new ArrayList(); // enable transformers anyCodeOnFacts.newA(fact -> addFactWithTrail(gazelle_deepTransform( s -> firstTransformersResult(deepTransformers, s), fact), trails == null ? null : new TTransformed(fact, transformer))); } deepTransformers.add(transformer); } void addTrailEnabledDeepTransformer(IF1> transformer) { if (trailEnabledDeepTransformers == null) { trailEnabledDeepTransformers = new ArrayList(); // enable transformers anyCodeOnFacts.newA(fact -> { WithTrail simplified = gazelle_deepTransform_withTrail( s -> firstTransformersResult_trailEnabled(trailEnabledDeepTransformers, s), fact); if (simplified == null) return; addFactWithTrail(simplified); if (noteSimplificationsAsFacts) addFact(format("$x simplifies $y", litmap("$x" , fact, "$y" , simplified.get()))); }); } trailEnabledDeepTransformers.add(transformer); } Object getExtension(Object key) { return mapGet(extensions, key); } void addExtension(Object key, Object value) { if (extensions == null) extensions = new HashMap(); extensions.put(key, value); } void enableTrails() { if (trails == null) trails = ciMap(); } Object getTrail(String fact) { return mapGet(trails, fact); } // get trail for arbitrary object (fact/rule) Object getTrail(Object o) { if (o instanceof LogicRule) return ((LogicRule) o).trail; if (o instanceof String) return mapGet(trails, ((String) o)); return null; } void printDeducedFactsWithTrails() { printAsciiHeading("Deduced facts with trails"); for (String fact : factsDeduced()) { print(fact); printUnlessNull(" << ", getTrail(fact)); } } List> deducedFactsWithTrails() { return map(factsDeduced(), s -> new WithTrail(getTrail(s), s)); } void setTrailForAllLogicRules(Object trail) { for (LogicRule r : logicRules) r.trail = trail; } List logicRules() { return cloneList(logicRules); } Pair, Set> rulesAndFactsUsedForMaking(Object factOrLogicRule) { Set l = thingsUsedForMaking(factOrLogicRule); return pair(instancesOfAsSet(LogicRule.class,l), setIntersection(asCISet(stringsOnly(l)), facts)); } Set thingsUsedForMaking(Object factOrLogicRule) { return philosophyBot1_visitTrailsTree_gen(this, null, factOrLogicRule); } void addExtraLogicOperation(Runnable r) { extraLogicOperations.add(r); } void addCodeOnFact(IVF1 f) { anyCodeOnFacts.newA(f); } void updateCodeOnFact(IVF1 f) { anyCodeOnFacts.updateA(f); } void addCodeOnRule(IVF1 f) { anyCodeOnRules.newA(f); } /*void updateCodeOnRule(IVF1 f) { anyCodeOnRules.updateA(f); }*/ void handleException(Throwable e) { print("BOT", e); } }static interface IFactStore { void store(String fact); void deleteAll(IF1 filter); Collection facts(); }// elements are put to front when added (not when accessed) static class MRUCache extends LinkedHashMap { int maxSize = 10; MRUCache() {} MRUCache(int maxSize) { this.maxSize = maxSize;} protected boolean removeEldestEntry(Map.Entry eldest) { return size() > maxSize; } Object _serialize() { return ll(maxSize, cloneLinkedHashMap(this)); } static MRUCache _deserialize(List l) { MRUCache m = new MRUCache(); m.maxSize = (int) first(l); m.putAll((LinkedHashMap) second(l)); return m; } }static abstract class CloseableIterableIterator extends IterableIterator implements AutoCloseable { public void close() throws Exception {} }static interface IF2 { C get(A a, B b); }static interface Producer { public A next(); // null when end }static ThreadLocal DynamicObject_loading = new ThreadLocal(); static class DynamicObject { String className; // just the name, without the "main$" LinkedHashMap fieldValues; DynamicObject() {} // className = just the name, without the "main$" DynamicObject(String className) { this.className = className;} Map _map() { return fieldValues; } public String toString() { return getClass() == DynamicObject.class ? "dyn " + className : super.toString(); } }static interface IF1 { B get(A a); }static class PersistableThrowable { String className; String msg; String stacktrace; PersistableThrowable() {} PersistableThrowable(Throwable e) { if (e == null) className = "Crazy Null Error"; else { className = getClassName(e).replace('/', '.'); msg = e.getMessage(); stacktrace = getStackTrace_noRecord(e); } } public String toString() { return nempty(msg) ? className + ": " + msg : className; } }static class RGBImage implements MakesBufferedImage { transient BufferedImage bufferedImage; File file; int width, height; int[] pixels; RGBImage() {} RGBImage(BufferedImage image) { this(image, null); } RGBImage(BufferedImage image, File file) { this.file = file; bufferedImage = image; width = image.getWidth(); height = image.getHeight(); pixels = new int[width*height]; PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width); try { if (!pixelGrabber.grabPixels()) throw new RuntimeException("Could not grab pixels"); cleanPixels(); // set upper byte to 0 } catch (InterruptedException e) { throw new RuntimeException(e); } } /** We assume it's a file name to load from */ RGBImage(String file) throws IOException { this(new File(file)); } RGBImage(Dimension size, Color color) { this(size.width, size.height, color); } RGBImage(Dimension size, RGB color) { this(size.width, size.height, color); } private void cleanPixels() { for (int i = 0; i < pixels.length; i++) pixels[i] &= 0xFFFFFF; } RGBImage(int width, int height, int[] pixels) { this.width = width; this.height = height; this.pixels = pixels; } RGBImage(int w, int h, RGB[] pixels) { this.width = w; this.height = h; this.pixels = asInts(pixels); } public static int[] asInts(RGB[] pixels) { int[] ints = new int[pixels.length]; for (int i = 0; i < pixels.length; i++) ints[i] = pixels[i] == null ? 0 : pixels[i].getColor().getRGB(); return ints; } public RGBImage(int w, int h) { this(w, h, Color.black); } RGBImage(int w, int h, RGB rgb) { this.width = w; this.height = h; this.pixels = new int[w*h]; int col = rgb.asInt(); if (col != 0) for (int i = 0; i < pixels.length; i++) pixels[i] = col; } RGBImage(RGBImage image) { this(image.width, image.height, copyPixels(image.pixels)); } RGBImage(int width, int height, Color color) { this(width, height, new RGB(color)); } RGBImage(File file) throws IOException { this(javax.imageio.ImageIO.read(file)); } RGBImage(MakesBufferedImage img) { this(toBufferedImage(img)); } private static int[] copyPixels(int[] pixels) { int[] copy = new int[pixels.length]; System.arraycopy(pixels, 0, copy, 0, pixels.length); return copy; } public int getIntPixel(int x, int y) { if (inRange(x, y)) return pixels[y * width + x]; else return 0xFFFFFF; } public static RGB asRGB(int packed) { int r = (packed >> 16) & 0xFF; int g = (packed >> 8) & 0xFF; int b = packed & 0xFF; return new RGB(r / 255f, g / 255f, b / 255f); } public RGB getRGB(int x, int y) { if (inRange(x, y)) return asRGB(pixels[y * width + x]); else return new RGB(0xFFFFFF); } /** alias of getRGB - I kept typing getPixel instead of getRGB all the time, so I finally created it */ RGB getPixel(int x, int y) { return getRGB(x, y); } RGB getPixel(Pt p) { return getPixel(p.x, p.y); } public int getWidth() { return width; } public int getHeight() { return height; } int w() { return width; } int h() { return height; } /** Attention: cached, i.e. does not change when image itself changes */ /** @NotNull */ public BufferedImage getBufferedImage() { if (bufferedImage == null) { bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //bufferedImage.setData(Raster.createRaster(new SampleModel())); for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) bufferedImage.setRGB(x, y, pixels[y*width+x]); } return bufferedImage; } RGBImage clip(Rect r) { return r == null ? null : clip(r.getRectangle()); } RGBImage clip(Rectangle r) { r = fixClipRect(r); if (r.x == 0 && r.y == 0 && r.width == width && r.height == height) return this; int[] newPixels; try { newPixels = new int[r.width*r.height]; } catch (RuntimeException e) { System.out.println(r); throw e; } for (int y = 0; y < r.height; y++) { System.arraycopy(pixels, (y+r.y)*width+r.x, newPixels, y*r.width, r.width); } return new RGBImage(r.width, r.height, newPixels); } private Rectangle fixClipRect(Rectangle r) { r = r.intersection(new Rectangle(0, 0, width, height)); if (r.isEmpty()) r = new Rectangle(r.x, r.y, 0, 0); return r; } public File getFile() { return file; } /** can now also do GIF (not just JPEG) */ public static RGBImage load(String fileName) { return load(new File(fileName)); } /** can now also do GIF (not just JPEG) */ public static RGBImage load(File file) { try { BufferedImage bufferedImage = javax.imageio.ImageIO.read(file); return new RGBImage(bufferedImage); } catch (IOException e) { throw new RuntimeException(e); } } public int getInt(int x, int y) { return pixels[y * width + x]; } public void save(File file) throws IOException { String name = file.getName().toLowerCase(); String type; if (name.endsWith(".png")) type = "png"; else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) type = "jpeg"; else throw new IOException("Unknown image extension: " + name); javax.imageio.ImageIO.write(getBufferedImage(), type, file); } public static RGBImage dummyImage() { return new RGBImage(1, 1, new int[] {0xFFFFFF}); } public int[] getPixels() { return pixels; } void setPixel(int x, int y, int r, int g, int b) { if (x >= 0 && y >= 0 && x < width && y < height) pixels[y*width+x] = (limitToUByte(r) << 16) | (limitToUByte(g) << 8) | limitToUByte(b); } public void setPixel(int x, int y, RGB rgb) { if (x >= 0 && y >= 0 && x < width && y < height) pixels[y*width+x] = rgb.asInt(); } public void setPixel(int x, int y, Color color) { setPixel(x, y, new RGB(color)); } void setInt(int x, int y, int rgb) { setPixel(x, y, rgb); } public void setPixel(int x, int y, int rgb) { if (x >= 0 && y >= 0 && x < width && y < height) pixels[y*width+x] = rgb; } void setPixel(Pt p, RGB rgb) { setPixel(p.x, p.y, rgb); } void setPixel(Pt p, Color color) { setPixel(p.x, p.y, color); } public RGBImage copy() { return new RGBImage(this); } public boolean inRange(int x, int y) { return x >= 0 && y >= 0 && x < width && y < height; } public Dimension getSize() { return new Dimension(width, height); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RGBImage rgbImage = (RGBImage) o; if (height != rgbImage.height) return false; if (width != rgbImage.width) return false; if (!Arrays.equals(pixels, rgbImage.pixels)) return false; return true; } @Override public int hashCode() { int result = width; result = 31 * result + height; result = 31 * result + Arrays.hashCode(pixels); return result; } public String getHex(int x, int y) { return getPixel(x, y).getHexString(); } public RGBImage clip(int x, int y, int width, int height) { return clip(new Rectangle(x, y, width, height)); } public RGBImage clipLine(int y) { return clip(0, y, width, 1); } public int numPixels() { return width*height; } void uncacheBufferedImage() { bufferedImage = null; } } static class SimpleFactStore implements IFactStore { List facts = synchroList(); transient boolean verbose = false; transient List onChange = syncList(); static class Fact extends HasGlobalID { long created = now(); String text; Fact() {} Fact(String text) { this.text = text;} public String toString() { return text; } } public void store(String fact) { if (!any(facts, f -> eqic(f.text, fact))) { facts.add(new Fact(fact)); pcallFAll(onChange); } } public void deleteAll(IF1 filter) { for (Fact f : cloneList(facts)) if (filter.get(f.text)) { if (verbose) print("Deleting fact: " + f); facts.remove(f); pcallFAll(onChange); } } public List facts() { return map(facts, f -> f.text); } public String toString() { return sfu(this); } void onChange(Runnable r) { onChange.add(r); } void clear() { facts.clear(); pcallFAll(onChange); } }static class StringClustersWithIDs { List clusters = new ArrayList(); transient List onChange = syncList(); void change() { pcallFAll(onChange); } StringClustersWithIDs onChange(Runnable r) { onChange.add(r); return this; } void removeChangeListener(Runnable r) { onChange.remove(r); } static class Cluster { GlobalID globalID = aGlobalIDObject(); Set synonyms = ciSet(); Cluster() {} Cluster(String s) { synonyms.add(s); } public String toString() { return "Cluster " + globalID + ": " + synonyms; } boolean add(String s) { return synonyms.add(s); } } List searchForCluster(String s) { return filter(clusters, c -> contains(c.synonyms, s)); } Cluster clusterWith(String s) { return first(searchForCluster(s)); } void add(Cluster cluster) { clusters.add(cluster); change(); } void remove(Cluster cluster) { clusters.remove(cluster); change(); } // also adds to list Cluster newCluster(String s) { Cluster c = new Cluster(s); add(c); return c; } // also adds to list Cluster newCluster(Collection synonyms) { Cluster c = new Cluster(); addAll(c.synonyms, synonyms); add(c); return c; } // also merges clusters void addPair(String a, String b) { Cluster c1 = clusterWith(a), c2 = clusterWith(b); if (c1 != null) if (c2 != null) mergeClusters(c1, c2); else { c1.add(b); change(); } else if (c2 != null) { c2.add(a); change(); } else newCluster(ll(a, b)); } void mergeClusters(Cluster a, Cluster b) { if (a == b) return; a.synonyms.addAll(b.synonyms); remove(b); } // either return s or all synonyms from the first cluster containing s Set extend(String s) { Cluster c = clusterWith(s); return c == null ? litciset(s) : c.synonyms; } int totalCount() { return intSum(map(clusters, c -> l(c.synonyms))); } boolean eqicOrInSameCluster(String a, String b) { if (eqic(a, b)) return true; if (a == null || b == null) return false; for (Cluster c : clusters) if (contains(c.synonyms, a) && contains(c.synonyms, b)) return true; return false; } } static class Rect { int x, y, w, h; Rect() {} Rect(Rectangle r) { x = r.x; y = r.y; w = r.width; h = r.height; } Rect(int x, int y, int w, int h) { this.h = h; this.w = w; this.y = y; this.x = x;} Rect(Pt p, int w, int h) { this.h = h; this.w = w; x = p.x; y = p.y; } Rect(Rect r) { x = r.x; y = r.y; w = r.w; h = r.h; } Rectangle getRectangle() { return new Rectangle(x, y, w, h); } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } public String toString() { return x + "," + y + " / " + w + "," + h; } int x2() { return x + w; } int y2() { return y + h; } boolean contains(Pt p) { return contains(p.x, p.y); } boolean contains(int _x, int _y) { return _x >= x && _y >= y && _x < x+w && _y < y+h; } boolean empty() { return w <= 0 || h <= 0; } }static class AllOnAll implements Producer> { List aList = new ArrayList(); List bList = new ArrayList(); List> todo = new LinkedList(); List> todo2 = new LinkedList(); void addA(A a) { newA(a); } void addAIfNotNull(A a) { if (a != null) newA(a); } synchronized void newA(A a) { add(aList, a); addPair(todo, intRange_last(aList), intRange(0, l(bList))); } synchronized void newAs(Iterable l) { for (A a : unnull(l)) newA(a); } void addB(B b) { newB(b); } void addBIfNotNull(B b) { if (b != null) newB(b); } synchronized void newB(B b) { add(bList, b); addPair(todo, intRange(0, l(aList)), intRange_last(bList)); } synchronized void newBs(Iterable l) { for (B b : unnull(l)) newB(b); } public synchronized Pair next() { while (empty(todo2)) { if (empty(todo)) return null; Pair p = popFirst(todo); addAll(todo2, outerProduct_pairs(subList(aList, p.a), subList(bList, p.b))); } return popFirst(todo2); } synchronized List cloneBList() { return clonedList(bList); } List getAs() { return aList; } List getBs() { return bList; } }static class Pt { int x, y; Pt() {} Pt(Point p) { x = p.x; y = p.y; } Pt(int x, int y) { this.y = y; this.x = x;} Point getPoint() { return new Point(x, y); } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } public String toString() { return x + ", " + y; } }static interface Visitable { void visitUsing(IVF1 f); } static class Cluster extends HasGlobalID { Set synonyms = linkedCISet(); void addSynonym(String s) { synonyms.add(s); } String firstSynonym() { return first(synonyms); } public String toString() { return curly(joinWithSlash(synonyms)); } }static interface Transformable { Object transformUsing(IF1 f); } static class RGB { public float r, g, b; // can't be final cause persistence RGB() {} public RGB(float r, float g, float b) { this.r = r; this.g = g; this.b = b; } public RGB(double r, double g, double b) { this.r = (float) r; this.g = (float) g; this.b = (float) b; } public RGB(int rgb) { this(new Color(rgb)); } public RGB(double brightness) { this.r = this.g = this.b = max(0f, min(1f, (float) brightness)); } public RGB(Color color) { this.r = color.getRed()/255f; this.g = color.getGreen()/255f; this.b = color.getBlue()/255f; } public RGB(String hex) { int i = l(hex)-6; r = Integer.parseInt(hex.substring(i, i+2), 16)/255f; g = Integer.parseInt(hex.substring(i+2, i+4), 16)/255f; b = Integer.parseInt(hex.substring(i+4, i+6), 16)/255f; } public float getComponent(int i) { return i == 0 ? r : i == 1 ? g : b; } public Color getColor() { return new Color(r, g, b); } public static RGB newSafe(float r, float g, float b) { return new RGB(Math.max(0, Math.min(1, r)), Math.max(0, Math.min(1, g)), Math.max(0, Math.min(1, b))); } int asInt() { return getColor().getRGB() & 0xFFFFFF; } int getInt() { return getColor().getRGB() & 0xFFFFFF; } public float getBrightness() { return (r+g+b)/3.0f; } public String getHexString() { return Integer.toHexString(asInt() | 0xFF000000).substring(2).toUpperCase(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RGB)) return false; RGB rgb = (RGB) o; if (Float.compare(rgb.b, b) != 0) return false; if (Float.compare(rgb.g, g) != 0) return false; if (Float.compare(rgb.r, r) != 0) return false; return true; } @Override public int hashCode() { int result = (r != +0.0f ? Float.floatToIntBits(r) : 0); result = 31 * result + (g != +0.0f ? Float.floatToIntBits(g) : 0); result = 31 * result + (b != +0.0f ? Float.floatToIntBits(b) : 0); return result; } public boolean isBlack() { return r == 0f && g == 0f && b == 0f; } public boolean isWhite() { return r == 1f && g == 1f && b == 1f; } public String toString() { return getHexString(); } int redInt() { return iround(r*255); } int greenInt() { return iround(g*255); } int blueInt() { return iround(b*255); } }static class HasGlobalID implements IHasGlobalID { GlobalID globalID = aGlobalIDObjUnlessLoading(); public GlobalID globalID() { return globalID; } public String globalIDStr() { return strOrNull(globalID); } String prependGlobalID(String s) { return globalID == null ? s : "[" + globalID + "] " + s; } }static interface MakesBufferedImage { BufferedImage getBufferedImage(); int getWidth(); int getHeight(); }/** this class is fully thread-safe */ static class Flag implements Runnable { private boolean up = false; /** returns true if flag was down before (i.e. flag was actually raised right now) */ public synchronized boolean raise() { if (!up) { up = true; notifyAll(); return true; } else return false; } public synchronized void waitUntilUp() { while (!up) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void waitUntilUp(long timeout) { if (!up) { try { wait(timeout); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized boolean isUp() { return up; } boolean get() { return isUp(); } public String toString() { return isUp() ? "up" : "down"; } // currently does a semi-active wait with latency = 50 ms public void waitForThisOr(Flag otherFlag) { try { while (!isUp() && !otherFlag.isUp()) Thread.sleep(50); } catch (Exception __e) { throw rethrow(__e); } } public void run() { raise(); } }static interface IF0 { A get(); }static interface IFieldsToList { Object[] _fieldsToList(); }static class And implements IFieldsToList, Transformable, Visitable{ A a; A b; And() {} And(A a, A b) { this.b = b; this.a = a;} public String toString() { return shortClassName(this) + "(" + a + ", " + b + ")"; } public boolean equals(Object o) { if (!(o instanceof And)) return false; And __0 = (And) o; return eq(a, __0.a) && eq(b, __0.b); } public int hashCode() { int h = 65975; h = boostHashCombine(h, _hashCode(a)); h = boostHashCombine(h, _hashCode(b)); return h; } public Object[] _fieldsToList() { return new Object[] {a, b}; } public Object transformUsing(IF1 f) { return new And((A) f.get(a), (A) f.get(b)); } public void visitUsing(IVF1 f) { f.get(a); f.get(b); } }static interface IVF1 { void get(A a); }static interface IVF2 { void get(A a, B b); }abstract static class DynServerAwareDiscordBot extends DynDiscordHopper { Map dataByServer = new HashMap(); int guildCount; transient IF0 makeByServer; // mandatory void startMe() { super.startMe(); dm_vmBus_onMessage_q("incomingDiscordReaction",new VF1() { public void get(Map map) { try { if (!enabled) return; Object module = map.get("module"); if (!dm_isMe(module)) return; MessageReaction reaction = (MessageReaction) (map.get("reaction")); Guild guild = reaction.getGuild(); if (guild == null) { print("Ignoring reaction without guild"); return; } getByServer(guild).onMessageReaction(map, true); } 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..."; }}); dm_vmBus_onMessage_q("discordReactionRemoved",new VF1() { public void get(Map map) { try { if (!enabled) return; Object module = map.get("module"); if (!dm_isMe(module)) return; MessageReaction reaction = (MessageReaction) (map.get("reaction")); Guild guild = reaction.getGuild(); if (guild == null) { print("Ignoring reaction remove without guild"); return; } getByServer(guild).onMessageReaction(map, false); } 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..."; }}); } class ByServer extends DynamicObject { long guildID; boolean isGuild = false; transient Guild guild; String answer(String s, Map map) { return null; } boolean setField(String name, Object value) { if (set_trueIfChanged(this, name, value)) return false; { _change(); return true; } } Member getSelfMember(Guild guild) { return guild.getMember(getSelfUser()); } void onMessageReaction(Map map, boolean added) { print("onMessageReaction " + added); } } @Override String answer(String input, Map map) { String __1 = super.answer(input, map); if (!empty(__1)) return __1; // discord hopping long guildID = toLong(map.get("guildID")); Guild guild = (Guild) (map.get("guild")); long id = guildID; print("Guild ID: " + guildID); if (id == 0) { id = toLong(map.get("userID")); print("User ID: " + id); } // config by guild or user A data = guild != null ? getByServer(guild) : getByServer(id, id == guildID); Message msg = (Message) (map.get("msg")); if (msg != null && nempty(msg.getAttachments())) return data.answer(input, map); else return lines_rtrim(nempties( map(s -> data.answer(s, map), splitIntoLines(input)))); } A getByServer(long id, boolean isGuild) { return pairA(getByServer2(id, isGuild)); } Pair getByServer2(long id, boolean isGuild) { A data; boolean isNew = false; Pair __2= syncGetOrCreate2(dataByServer, id, makeByServer); data = __2.a; isNew = __2.b; data.isGuild = isGuild; if (isGuild && data.guildID == 0) { data.guildID = id; change(); } if (isNew) { if (data.isGuild) ++guildCount; change(); } return pair(data, isNew); } A getByServer(Guild guild) { if (guild == null) return null; A a = getByServer(guild.getIdLong(), true); a.guild = guild; return a; } void start() { try { super.start(); if (guildCount == 0) setField("guildCount" , countValuesWhere_sync(dataByServer, "isGuild" , true)); } catch (Exception __e) { throw rethrow(__e); } } int liveGuildCount() { return l(discord.getGuilds()); } long idForByServer(ByServer bs) { return bs == null ? 0 : toLong(keyForValue_sync(dataByServer, (A) bs)); } List splitIntoLines(String s) { return tlft(s); } }static class WithTrail extends Var { Object trail; WithTrail() {} WithTrail(A value) { super(value); } WithTrail(Object trail, A value) { super(value); this.trail = trail; } public String toString() { if (trail == null) return super.toString(); return super.toString() + "\n" + indentx("[Trail: " + trail + "]"); } }static class AllOnAllWithUpdates { long aCounter, bCounter; TreeMap aList = new TreeMap(); TreeMap bList = new TreeMap(); List> todo = new LinkedList(); List> todo2 = new LinkedList(); synchronized void newA(A a) { long c = aCounter++; aList.put(c, a); addPair(todo, longRange_one(c), longRange(0, bCounter)); } synchronized void newB(B b) { long c = bCounter++; bList.put(c, b); addPair(todo, longRange(0, aCounter), longRange_one(c)); } synchronized void updateA(A a) { removeValue(aList, a); newA(a); } synchronized void updateB(B b) { removeValue(bList, b); newB(b); } synchronized Pair next() { while (licensed()) { while (empty(todo2)) { if (empty(todo)) return null; Pair p = popFirst(todo); addAll(todo2, outerProduct_pairs(keys(subMap_longRange(aList, p.a)), keys(subMap_longRange(bList, p.b)))); } Pair p = popFirst(todo2); A a = aList.get(p.a); B b = bList.get(p.b); if (a != null && b != null) return pair(a, b); } return null; } }static interface IVar extends IF0 { void set(A a); A get(); default boolean has() { return get() != null; } default void clear() { set(null); } }static class Cache { Object maker; // func -> A A value; long loaded; static boolean debug = false; long changeCount; Lock lock = lock(); Cache() {} Cache(Object maker) { this.maker = maker;} Cache(IF0 maker) { this.maker = maker;} A get() { if (hasLock(lock)) return value; // Must be called from within maker Lock __0 = lock; lock(__0); try { if (loaded == 0) { value = make(); changeCount++; loaded = sysNow(); } return value; } finally { unlock(__0); } } void clear() { Lock __1 = lock; lock(__1); try { if (debug && loaded != 0) print("Clearing cache"); value = null; changeCount++; loaded = 0; } finally { unlock(__1); } } // clear if older than x seconds // 0 does not do anything void clear(double seconds) { Lock __2 = lock; lock(__2); try { if (seconds != 0 && loaded != 0 && sysNow() >= loaded+seconds*1000) clear(); } finally { unlock(__2); } } // override void set(A a) { Lock __3 = lock; lock(__3); try { value = a; ++changeCount; loaded = sysNow(); } finally { unlock(__3); } } A make() { return (A) callF(maker); } } static interface IHasGlobalID { public GlobalID globalID(); }final static class LongRange { long start, end; LongRange() {} LongRange(long start, long end) { this.end = end; this.start = start;} public boolean equals(Object o) { if (o instanceof LongRange) return start == ((LongRange) o).start && end == ((LongRange) o).end; return false; } public int hashCode() { return boostHashCombine(hashOfLong(start), hashOfLong(end)); } long length() { return end-start; } static String _fieldOrder = "start end"; public String toString() { return "[" + start + ";" + end + "]"; } }abstract static class DynDiscordHopper extends DynPrintLogAndEnabled { static boolean _switchableField_discordToken = true; String discordToken; String discordBotName; long discordBotID; boolean reactToBots = true; transient boolean sendToPostedLinesCRUD = true; transient JDA discord; transient Color discordImageEmbedMysteriousLineColor = colorFromHex("36393f"); transient List> onPostedInChannel = syncList(); //transient bool debugPosting; // when a discord action failed transient Consumer onQueueError = error -> { AutoCloseable __69 = enter(); try { printStackTrace(error); } finally { _close(__69); }}; void startDiscord() { if (!discordEnabled()) { print("Not enabled"); return; } vm_cleanPrints(); // avoid Swing Unicode problem logModuleOutput(); // good idea for chat bots // TODO: log JDA output going to System.out/err discord = discordBot(new ListenerAdapter() { @Override public void onMessageUpdate(MessageUpdateEvent e) { try { AutoCloseable __70 = enter(); try { { if (!discordEnabled() || !licensed()) return; } Message msg = e.getMessage(); long msgID = msg.getIdLong(); User user = e.getAuthor(); long userID = user == null ? 0 : user.getIdLong(); String content = e.getMessage().getContentRaw(); MessageChannel channel = e.getChannel(); long channelID = channel.getIdLong(); String rendered = msgID + ": " + content; //print("Message edited: " + rendered); vmBus_send("editedDiscordMessage", litmapparams("event" , e, "module" , dm_me(), "msgID", msgID, "msg", msg, "content", content, "channelID", channelID, "channel", channel, "user", user, "userID", userID)); Object lineConcept = dm_discord_lineForMsgID_unimported(msgID); if (lineConcept == null) return; // logging module not enabled call(lineConcept, "_setField", "editedText" , content); } finally { _close(__70); }} catch (Throwable __e) { _handleException(__e); }} @Override public void onMessageReceived(MessageReceivedEvent e) { try { AutoCloseable __71 = enter(); try { { if (!discordEnabled() || !licensed()) return; } // send out raw event vmBus_send("discord_onMessageReceived",module(), e); User user = e.getAuthor(); if (!reactToUser(user)) { print("Not reacting to user " + user); return; } boolean bot = user.isBot(); long msgID = e.getMessage().getIdLong(); long userID = user.getIdLong(); Guild guild = e.getGuild(); long guildID = toLong(call(guild, "getIdLong")); Member member = e.getMember(); String userName = member == null ? null : member.getNickname(); // the changeable nick name - null sometimes? 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); vmBus_send("incomingDiscordMessage", litmapparams("fromBot" , bot, "module" , dm_me(), "msgID", msgID, "userID", userID, "userName", userName, "event" , e, "guildID", guildID, "guild", guild, "member", member, "msg", msg, "content", content, "isPrivate", isPrivate, "channelID", channelID, "channel", channel)); } finally { _close(__71); }} catch (Throwable __e) { _handleException(__e); }} @Override public void onMessageReactionAdd(MessageReactionAddEvent e) { try { AutoCloseable __72 = enter(); try { { if (!discordEnabled() || !licensed()) return; } MessageReaction r = e.getReaction(); User user = e.getUser(); if (!reactToUser(user)) return; boolean bot = user.isBot(); long msgID = r.getMessageIdLong(); String emoji = r.getReactionEmote().getName(); vmBus_send("incomingDiscordReaction", litmapparams( "reaction" , r, "fromBot" , bot, "user", user, "userID" , user.getIdLong(), "module" , dm_me(), "msgID", msgID, "emoji", emoji )); } finally { _close(__72); }} catch (Throwable __e) { _handleException(__e); }} @Override public void onMessageReactionRemove(MessageReactionRemoveEvent e) { try { AutoCloseable __73 = enter(); try { { if (!discordEnabled() || !licensed()) return; } MessageReaction r = e.getReaction(); User user = e.getUser(); if (!reactToUser(user)) return; boolean bot = user.isBot(); long msgID = r.getMessageIdLong(); String emoji = r.getReactionEmote().getName(); vmBus_send("discordReactionRemoved", litmapparams( "reaction" , r, "fromBot" , bot, "user", user, "userID" , user.getIdLong(), "module" , dm_me(), "msgID", msgID, "emoji", emoji )); } finally { _close(__73); }} catch (Throwable __e) { _handleException(__e); }} @Override public void onMessageReactionRemoveAll(MessageReactionRemoveAllEvent e) { try { AutoCloseable __74 = enter(); try { print("TODO: onMessageReactionRemoveAll"); } finally { _close(__74); }} catch (Throwable __e) { _handleException(__e); }} @Override public void onGuildMemberJoin(GuildMemberJoinEvent event) { try { AutoCloseable __75 = 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, "guildID" , discord_guildIDFromEvent_gen(event) )); } finally { _close(__75); }} catch (Throwable __e) { _handleException(__e); }} @Override public void onGuildMemberLeave(GuildMemberLeaveEvent event) { try { AutoCloseable __76 = 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(__76); }} 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); } void cleanMeUp() { if (discord != null) { try { print("Shutting down discord"); discord.shutdown(); print("Bot shut down"); } catch (Throwable __e) { _handleException(__e); }} discord = null; } 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; } // API MessageChannel getChannel(long channelID) { return discord.getTextChannelById(channelID); } void postInChannel(long channelID, String msg) { postInChannel(channelID, msg, null); } void postInChannel(long channelID, String msg, IVF1 onPost) { if (channelID == 0) return; postInChannel(getChannel(channelID), msg, onPost); } void uploadFileInChannel(long channelID, File file, String fileName, String msg, IVF1 onPost) { if (channelID == 0) return; uploadFileInChannel(getChannel(channelID), file, fileName, msg, onPost); } void postInChannel(MessageChannel channel, String msg, IVF1 onPost) { String originalMsg = msg; msg = shortenForDiscord(msg); if (empty(msg)) return; String postID = !sendToPostedLinesCRUD ? null : (String) dm_pcall(gazelle_postedLinesCRUD(), "postingLine", channel.getId(), msg); print("Posting in channel " + channel + ": " + msg); pcallFAll(onPostedInChannel, channel, msg); MessageAction a = channel.sendMessage(msg); if (msg != originalMsg) a.addFile(toUtf8(originalMsg), genericTextFileName()); a.queue(m -> msgPosted(m, onPost, postID), onQueueError); } String genericTextFileName() { return ymd_minus_hms() + ".txt"; } void msgPosted(Message m, IVF1 onPost, String postID) { AutoCloseable __77 = enter(); try { if (nempty(postID)) dm_call(gazelle_postedLinesCRUD(), "donePosting", postID, "discord msg " + m.getId()); long msgId = m.getIdLong(); print("I sent msg: " + msgId); pcallF(onPost, m); } finally { _close(__77); }} void postInChannel(String channel, String msg) { long id = dm_discord_channelID(channel); if (id == 0) throw fail("Channel not found: " + channel); postInChannel(id, msg); } void postInChannel(MessageChannel channel, String msg) { postInChannel(channel, msg, null); } void postImage(Map msgMap, String url) { postImage(msgMap, url, ""); } void postImage(Map msgMap, String url, String description) { postImage((MessageChannel) get("channel",msgMap), url, description); } void postImage(MessageChannel channel, String url, String description) { print("Posting image: " + url); channel.sendMessage( new EmbedBuilder() .setImage(absoluteURL(url)) //.setTitle(unnull(title)) .setDescription(unnull(description)) .setColor(discordImageEmbedMysteriousLineColor) .build()).queue(null, onQueueError); // TODO: posted lines } void editMessage(long channelID, long msgID, String text) { getChannel(channelID).editMessageById(str(msgID), text).queue(null, onQueueError); } void sendPM(long userID, String _text) { String text = shortenForDiscord(_text); if (empty(text)) return; print("Sending PM to " + userID + ": " + text); discord.getUserById(userID).openPrivateChannel().queue(channel -> { channel.sendMessage(text).queue(null, onQueueError); }, onQueueError); print("PM queued"); } void reply(Map msgMap, String text) { reply(msgMap, text, null); } void reply(Map msgMap, String text, Object onPost) { if (empty(text = trim(text))) return; postInChannel((MessageChannel) msgMap.get("channel"), text, toIVF1(onPost)); } void iAmTyping(Map msgMap) { try { ((MessageChannel) msgMap.get("channel")).sendTyping().queue(null, onQueueError); } catch (Throwable __e) { _handleException(__e); }} String startKeepAliveModule() { AutoCloseable __78 = enter(); try { return dm_discord_startKeepAliveModule(module()); } finally { _close(__78); }} boolean reactToUser(User user) { boolean bot = user.isBot(); // don't react to other bots if (bot && !reactToBots) return false; // don't read msgs from myself if (user.getIdLong() == discordBotID) return false; return true; } void uploadFileInChannel(MessageChannel channel, File file, String fileName, String msg, IVF1 onPost) { msg = shortenForDiscord(msg); MessageAction a = empty(msg) ? channel.sendFile(file, fileName) : channel.sendMessage(msg).addFile(file, fileName); a.queue(m -> msgPosted(m, onPost, null), onQueueError); } void uploadFileInChannel(MessageChannel channel, byte[] data, String fileName, String msg, IVF1 onPost) { msg = shortenForDiscord(msg); MessageAction a = empty(msg) ? channel.sendFile(data, fileName) : channel.sendMessage(msg).addFile(data, fileName); a.queue(m -> msgPosted(m, onPost, null), onQueueError); } void uploadFileInChannel(long channelID, byte[] data, String fileName, String msg, IVF1 onPost) { uploadFileInChannel(getChannel(channelID), data, fileName, msg, onPost); } void queue(RestAction action) { action.queue(null, onQueueError); } boolean discordEnabled() { return enabled; } boolean printToModule() { return true; } boolean discordHopperMetaCmdsEnabled = false; long preferredChannelID; transient double minutesToKeepRecordedAnswers = 60.0; List recordedAnswers = syncList(); static class RecordedAnswer { long timestamp; long questionMsgID, answerMsgID, channelID; String questionText, answerText; public String toString() { return stdToString(this); } } static boolean _switchableField_verboseEvents = true; transient boolean verboseEvents = false; transient List onDiscordStarted = new ArrayList(); transient List> onDiscordEvent = syncList(); ListenerAdapter genericListener = new ListenerAdapter() { public void onGenericEvent(Event e) { AutoCloseable __1 = enter(); try { if (verboseEvents) print("Discord event: " + e); pcallFAll(onDiscordEvent, e); } finally { _close(__1); }} }; void onDiscordEvent(IVF1 e) { onDiscordEvent.add(e); } 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();"; }})); minFrameSize(f, 300, 300); } // Note: Breaking change - moved start to thread void start() { try { super.start(); startThread("Start", new Runnable() { public void run() { try { AutoCloseable __2 = enter(); try { try { init(); startMe(); } catch (Throwable __e) { _handleException(__e); }} finally { _close(__2); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __2 = enter(); try { try {\r\n init();\r\n startMe();\r\n } ca..."; }});} catch (Exception __e) { throw rethrow(__e); } } void startMe() { 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); cleanRecordedAnswers(); String answer = answer(s, map); sendReply(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..."; }}); if (!enabled) return; startDiscord(); discord.addEventListener(genericListener); pcallFAll(onDiscordStarted); } void sendReply(Map map, String answer) { if (empty(answer)) return; cleanRecordedAnswers(); RecordedAnswer a = new RecordedAnswer(); if (minutesToKeepRecordedAnswers > 0) { a.timestamp = now(); a.questionMsgID = getLong("msgID",map); a.channelID = getLong("channelID",map); a.questionText = getString("content",map); a.answerText = answer; print("Recording answer : " + a); recordedAnswers.add(a); change(); } dm_rcall("reply",map.get("module"), map, answer, (IVF1) msg -> { a.answerMsgID = rcall_long("getIdLong",msg); change(); }); } String answer(String s, Map map) { if (discordHopperMetaCmdsEnabled && eq(s, "!bot count")) return lstr(dm_activeDiscordTokens()); if (eq(s, "!ip address")) return myPublicIP(); List tokens = extractPossibleDiscordTokens(s); for (String token : unnull(tokens)) { if (getLong("guildID",map) != 0) return "Send tokens only in private messages!!"; 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; } String atSelf() { return discordAt(discordBotID); } // sometimes mentions come in like this? String atExclamSelf() { return discordAtExclam(discordBotID); } void onDiscordStarted(Runnable r) { onDiscordStarted.add(r); } User getSelfUser() { return discord.getSelfUser(); } // OVERRIDE ME void init() { dm_watchField("discordToken",new Runnable() { public void run() { try { if (nempty(discordToken) && enabled) dm_reloadModule() ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (nempty(discordToken) && enabled) dm_reloadModule()"; }}); dm_reloadOnFieldChange("enabled"); } void cleanRecordedAnswers() { RecordedAnswer a; boolean change = false; synchronized(recordedAnswers) { while ((a = first(recordedAnswers)) != null && elapsedMinutes_timestamp(a.timestamp) > minutesToKeepRecordedAnswers) { print("Removing old answer: " + a); recordedAnswers.remove(a); } change = true; } if (change) change(); } public JComponent visualize() { JComponent _c = super.visualize(); if (empty(discordToken)) containerAddFirst(buttons, jThreadedButton("Give me a token!", new Runnable() { public void run() { try { AutoCloseable __3 = enter(); try { dm_stringFieldDialog("discordToken"); } finally { _close(__3); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter(); dm_stringFieldDialog discordToken();"; }})); addToContainer(buttons, jPopDownButton_noText( "Export all my data...", runnableThread(new Runnable() { public void run() { try { dm_exportStructureToTextFileDialog(module()) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "dm_exportStructureToTextFileDialog(module())"; }}), "Import all my data...", runnableThread(new Runnable() { public void run() { try { dm_importStructureFromTextFileDialog(module()) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "dm_importStructureFromTextFileDialog(module())"; }}) )); return _c; } boolean warnOnDelete() { return true; } // API String migrateToType(String moduleLibID) { String moduleID = assertNotNull(dm_showNewModuleWithParams(moduleLibID, "discordToken", discordToken)); print("Migrated to new module " + moduleID + ", disabling me"); setEnabled(false); dm_reload(); // actually disable Discord return moduleID; } } abstract static class DynPrintLogAndEnabled extends DynPrintLog { volatile boolean enabled = true; transient JPanel buttons; public JComponent visualize() { return dm_visualizeWithEnabled(super.visualize()); } JComponent visualizeWithoutEnabled() { return super.visualize(); } JComponent dm_visualizeWithEnabled(JComponent main) { return centerAndSouthWithMargins(main, buttons = makeControlArea()); } JPanel makeControlArea() { return jrightalignedline(makeEnabledCheckBox()); } static JCheckBox makeEnabledCheckBox() { return dm_fieldCheckBox("enabled"); } void setEnabled(boolean b) { setField("enabled" , b); } } abstract static class DynPrintLog extends DynModule { transient JFastLogView_noWrap printLogView; transient Lock updatePrintLog_lock = lock(); transient StringBuffer actualPrintLog; transient int printLogUpdateInterval = 500; public JComponent visualize() { JComponent section = jSection("Log", jscroll_copyBackground(printLogView = jFastLogView_noWrap(getPrintLog()))); componentPopupMenuItem(section, "Clear", new Runnable() { public void run() { try { AutoCloseable __3 = enter(); try { dm_clearModulePrintLog(); } finally { _close(__3); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter(); dm_clearModulePrintLog();"; }}); return awtEvery(section, printLogUpdateInterval, new Runnable() { public void run() { try { updatePrintLog(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "updatePrintLog();"; }}); } void updatePrintLog() { swing(new Runnable() { public void run() { try { // TODO: optimize Lock __0 = updatePrintLog_lock; lock(__0); try { JFastLogView_noWrap _view = printLogView; if (_view == null) return; if (_view.setText(getPrintLog())) { // Still trying to reliably scroll down scrollAllTheWayDown(_view); awtLater(100, new Runnable() { public void run() { try { scrollAllTheWayDown(_view) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "scrollAllTheWayDown(_view)"; }}); } } finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// TODO: optimize\r\n Lock __0 = updatePrintLog_lock; lock(__0); try {\r\n ..."; }}); } JFastLogView_noWrap myPrintLogComponent() { return printLogView; } void enableWordWrap() { // TODO } String getPrintLog() { if (actualPrintLog == null) { if (printToModule()) actualPrintLog = _printLog; else actualPrintLog = liveLocalPrintLog_realMC(this); } return str(actualPrintLog); } } static class JFastLogView_noWrap extends JComponent implements Scrollable { List lines = syncList(); boolean endsWithNewLine, verbose; public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 20; } public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { return (direction == SwingConstants.HORIZONTAL ? visibleRect.width : visibleRect.height)*5/6; } public boolean getScrollableTracksViewportWidth() { return false; } public boolean getScrollableTracksViewportHeight() { return false; } public void paint(Graphics g) { //if (verbose) _print("JFastLogView_noWrap painting"); int w = getWidth(), h = getHeight(); g.setColor(getBackground()); g.fillRect(0, 0, w, h); g.setColor(getForeground()); FontMetrics fm = componentFontMetrics(this); int fh = fm.getHeight(); Rectangle clip = g.getClipBounds(); int start, end; if (clip == null) { start = 0; end = l(lines); } else { start = max(0, clip.y/fh); end = min(l(lines), idiv_ceil(clip.y+clip.height, fh)); } //printVars(+start, +end); int y = fm.getAscent()+start*fh; for (int i = start; i < end; i++) { String s = get(lines, i); if (s != null) g.drawString(s, 0, y); y += fh; } //if (verbose) _print("JFastLogView_noWrap painted"); } public Dimension getPreferredSize() { FontMetrics fm = componentFontMetrics(this); if (fm == null) return new Dimension(50, 50); // not renderable yet int fh = fm.getHeight(); int w = 0; for (int i = 0; i < l(lines); i++) { String s = get(lines, i); w = max(w, fm.stringWidth(unnull(s))); // TODO: just count chars } return new Dimension(w, fh*l(lines)); } JFastLogView_noWrap() {} JFastLogView_noWrap(String text) { setText(text); } { componentPopupMenuItem(this, "Copy full text", new Runnable() { public void run() { try { copyFullText(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyFullText();"; }}); } // API // returns true if changed boolean setLines(Collection lines) { List newList = asSyncList(lines); if (eq(this.lines, newList)) return false; this.lines = newList; _revalidate(this); return true; } // returns true if changed boolean setText(String text) { endsWithNewLine = endsWithNewLine(text); return setLines(lines(text)); } void append(String text) { if (nempty(text)) setText(getText() + text); } String getText() { return lines_rtrimIf(!endsWithNewLine, cloneList(lines)); } void copyFullText() { copyTextToClipboard(getText()); } }static abstract class DynModule { // we really shouldn't have used up these variable names // (subclasses can't overload them due to how the persistence works) String name, toolTip; // module name, module tool tip in task bar PersistableThrowable _error; Map> mechLists; Map _persistenceInfo; transient Object _host; transient Map timers = newWeakHashMap(); // all kinds of resources actually; value is closer helper transient Set _resources = synchroHashSet(); transient Lock lock; // set by stem transient boolean persistOnChangedField = true; transient int changeCount; transient Object changeCountSync = new Object(); transient List onChange; transient List onTransientChange; transient boolean verboseTimers = false; transient ReliableSingleThread rstUpdate; transient Set componentFieldsToKeep; transient Map transientGeneralMap = synchroHashMap(); transient Q q; // module command queue transient List onFieldChange; // also for non-persistent fields. L transient boolean _hasPreviousBounds = false; transient StringBuffer _printLog = new StringBuffer(); transient boolean deleted = false; DynModule() { dm_initErrorHandling(); setMainDesktopPane((JDesktopPane) getCreatorOpt("desktop")); } boolean isVisible() { return isTrue(getOpt(_host, "visible")); } String moduleName() { return name; } void setModuleName(String name) { String oldName = this.name; if (!eq(name, oldName)) { setField("name", name); possiblyInternalFrameTitle(vis(), name); vmBus_send("moduleNameChange", this, oldName, name); } } void setModuleToolTip(String toolTip) { this.toolTip = toolTip; } JComponent vis() { return (JComponent) getOpt(_host, "vis"); } A ownResource(A a) { if (a != null) _resources.add(a); return a; } A ownTimer(A timer) { if (timer instanceof AutoCloseable) ownResource((AutoCloseable) timer); ownTimer(timer, "cancelTimerOrInterruptThread"); return timer; } void ownTimer(Object timer, Object closerHelper) { timers.put(timer, closerHelper); } void singleTimer(java.util.Timer timer) { stopAllTimers(); ownTimer(timer); } void stopAllTimers() { for (AutoCloseable resource : getAndClearList(_resources)) { if (verboseTimers) print("Releasing resource: " + resource); try { resource.close(); } catch (Throwable __e) { _handleException(__e); } } { final Map __0 = getAndClearMap(timers); for (Object timer : keys( __0)) { Object closerHelper = __0.get(timer); if (verboseTimers) print("Stopping timer: " + closerHelper + " / " + timer); pcallFInRealOrMyMC(this, closerHelper, timer); }} } boolean isDeleted() { return deleted; } void cleanMeUp_dynModule() { deleted = true; stopAllTimers(); } void persistMe() { synchronized(changeCountSync) { ++changeCount; } pcallFAll(onChange); callOpt(_host, "_change"); updateMe(); } void fireChangeWithoutPersisting() { pcallFAll(onChange); } void fireTransientChange() { pcallFAll(onTransientChange); } void _change() { persistMe(); } void change() { persistMe(); } void updateMe() { rstUpdate().trigger(); } void changeAndUpdate() { _change(); updateMe(); } boolean setField(String name, Object value) { AutoCloseable __5 = enter(); try { { // lock lock; // this leads to too many problems try { // some really weird classes fail on equals() (BCEL JavaClass, I'm looking at you) if (eq(get(this, name), value)) return false; } catch (Throwable __e) { _handleException(__e); } set(this, name, value); } // releasing lock before calling _change()! pcallFAll(onFieldChange, name); if (persistOnChangedField //&& !isTransientField(this, name) && !isFalse(mapGet(_persistenceInfo, name))) _change(); return true; } finally { _close(__5); }} A setFieldAndReturn(String name, A value) { setField(name, value); return value; } boolean setFields(Object... params) { boolean change = false; for (int i = 0; i < l(params); i += 2) if (setField((String) params[i], params[i+1])) change = true; return change; } void start() { _hasPreviousBounds = dm_getBounds() != null; if (hasMethod_onTypes(this, "onTopInput", String.class)) dm_onTopInput_q(new VF1() { public void get(String s) { try { call(module(), "onTopInput", s) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "call(module(), 'onTopInput, s)"; }}); } void revisualize() { call(creator(), "revisualizeModule", _host); } AutoCloseable enter() { AutoCloseable c = tempSetThreadLocal(dm_currentModule_value, new WeakReference(this)); final Object realMC = getMainClass(this); if (printToModule()) c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(_printToModuleInterceptor())); if (realMC != mc()) { if (printToModule()) c = combineAutoCloseables(c, (AutoCloseable) callOpt(realMC, "tempInterceptPrintIfNotIntercepted", _printToModuleInterceptor())); else c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(new F1() { public Boolean get(String s) { try { { call(realMC, "print", s); return false; } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret false with call(realMC, 'print, s);"; }})); c = combineAutoCloseables(c, tempSetTL(realMC_tl(), realMC)); } return c; } F1 _printToModuleInterceptor() { return new F1() { public Boolean get(String s) { try { if (print_preprocess != null) s = (String) callF(print_preprocess, s); s = fixNewLines(s); Appendable loc = _printLog; 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); return false; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (print_preprocess != null) s = (S) callF(print_preprocess, s);\r\n s = ..."; }}; } boolean printToModule() { return true; } // on by default now AutoCloseable enterAndLock() { return combineAutoCloseables(enter(), tempLock(lock)); } boolean setError(Throwable e) { setField("_error" , persistableThrowable(e)); return true; } void clearError() { setField("_error" , null); } void onChange(Runnable r) { Lock __1 = lock; lock(__1); try { if (onChange == null) onChange = synchroList(); addIfNotThere(onChange, r); } finally { unlock(__1); } } void onFieldChange(VF1 r) { Lock __2 = lock; lock(__2); try { if (onFieldChange == null) onFieldChange = synchroList(); addIfNotThere(onFieldChange, r); } finally { unlock(__2); } } void onChangeAndNow(Runnable r) { onChange(r); callF(r); } // forward to main class void onChangeAndNow(JComponent c, Object r) { onUpdateAndNow(c, r); } /*static*/ A onChange(A tc, Object r) { onUpdate(tc, r); return tc; } void update() {} void unvisualize() { zeroAllFieldsOfTypeExcept(this, Component.class, componentFieldsToKeep); } // return L (legacy) // or litobjectarray(text, Runnable, text, Runnable, ...) Object menuItems() { return null; } void enhanceFrame(Container f) { Object items = menuItems(); if (items instanceof Object[]) items = paramsToAbstractActions((Object[]) items); internalFramePopupMenuFromActions_threaded(f, (List) items); String switchableFields = (String) (callOpt(this, "switchableFields")); Set set = asLinkedHashSet(splitAtSpace(switchableFields)); Matches m = new Matches(); for (String field : allFields(this)) if (startsWith(field, "_switchableField_", m)) set.add(m.rest()); for (String field : set) { Class type = fieldType(this, field); if (eq(boolean.class, type)) dm_boolFieldMenuItem(f, field); else if (eq(int.class, type)) dm_intFieldMenuItem(f, field); else if (eq(double.class, type)) dm_doubleFieldMenuItem(f, field); else if (eq(String.class, type)) dm_stringFieldMenuItem(f, field); } } // assume this is called in start(), so no locking ReliableSingleThread rstUpdate() { if (rstUpdate == null) rstUpdate = dm_rst(this, new Runnable() { public void run() { try { AutoCloseable __6 = enter(); try { update(); } finally { _close(__6); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter(); update();"; }}); return rstUpdate; } Q q() { AutoCloseable __7 = enter(); try { if (q == null) { Lock __3 = lock; lock(__3); try { if (q == null) q = dm_startQ(); } finally { unlock(__3); } } return q; } finally { _close(__7); }} A withUpdate(A a) { rstUpdate().trigger(); return a; } DynModule module() { return this; } DynModule me() { return this; } JComponent visualize() { return dm_noVisualisation(); } String programTitle_cache; String programTitle() { if (programTitle_cache == null) programTitle_cache = snippetTitle(programID(mainClass(this))); return programTitle_cache; } // field must be non-transient void doPersist(String field) { _persistenceInfo = mapMinus(_persistenceInfo, field); } void dontPersist(String field) { _persistenceInfo = mapPlus(_persistenceInfo, "field" , false); } Appendable _actualPrintLog() { return printToModule() ? _printLog : print_log; } } static void _registerTimer(java.util.Timer timer) { _registerTimer_original(timer); dm_currentModule().ownTimer(timer); } /* TODO: thread {} should enter the module svoid _onLoad_moduleThreadInfo { _threadInfo_addMakerAndRetriever( voidfunc(Map map) { mapPut(map, dm_current := dm_currentModule()) }, voidfunc(Map map) { dm_enter((S) map.get('dm_current)) }); } */ static class Q implements AutoCloseable { String name = "Unnamed Queue"; List q = synchroLinkedList(); ReliableSingleThread rst = new ReliableSingleThread(new Runnable() { public void run() { try { _run() ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_run()"; }}); volatile boolean retired = false; Q() {} Q(String name) { this.name = name;} void add(Runnable r) { q.add(r); _trigger(); } void addInFront(Runnable r) { q.add(0, r); _trigger(); } void _trigger() { rst.name = name; rst.go(); } void add(Object r) { add(toRunnable(r)); } void _run() { Runnable r; while (licensed() && !retired && (r = syncPopFirst(q)) != null) { try { r.run(); } catch (Throwable __e) { _handleException(__e); } } } public void close() { retired = true; } // TODO: interrupt thread void done() {} // legacy function boolean isEmpty() { return q.isEmpty(); } int size() { return q.size(); } Object mutex() { return q; } // clients can synchronize on this List snapshot() { return cloneList(q); } }static class ReliableSingleThread implements Runnable { boolean _isTransient() { return true; } Object runnable; String name = "Single Thread"; boolean cancelBeforeTrigger = false; // always cancel running thread and wait for it to end before starting new operation F0 enter; // optional ownership marker, e.g. for DynModules int cancelTimeOut = 10000; boolean trigger = false; Thread thread; WeakReference threadBeingCancelled; ReliableSingleThread(Object runnable) { this.runnable = runnable;} void trigger() { go(); } synchronized void go() { if (cancelBeforeTrigger) cancel(); trigger = true; if (!running()) { AutoCloseable __1 = callF(enter); try { thread = startThread(name, new Runnable() { public void run() { try { AutoCloseable __2 = callF(enter); try { _run(); } finally { _close(__2); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp callF(enter);\r\n _run();"; }}); } finally { _close(__1); }} } public void run() { go(); } void get() { go(); } // so you can use the ! syntax synchronized boolean running() { return thread != null; } // use only if this is the last time you trigger this void triggerAndWait() { trigger(); waitUntilDone(); } void waitUntilDone() { while (running()) sleep(1); } void _run() { try { while (licensed()) { Thread oldThread; synchronized(this) { if (!trigger) { thread = null; break; } oldThread = getWeakRef(threadBeingCancelled); trigger = false; } if (oldThread != null && oldThread != currentThread()) oldThread.join(cancelTimeOut); pcallF(runnable); } } catch (Exception __e) { throw rethrow(__e); } } synchronized void cancel() { if (thread == null) return; threadBeingCancelled = new WeakReference(thread); cancelAndInterruptThread(thread); thread = null; } void cancelAndTrigger() { cancel(); trigger(); } synchronized boolean triggered() { return trigger; } void cleanMeUp() { cancel(); } ReliableSingleThread cancelBeforeTrigger() { cancelBeforeTrigger = true; return this; } } static List myInnerClasses_list=litlist( "VF1", "VF3", "VF2", "JSection", "Var", "Visitable", "mapI_It", "TokCondition", "RightAlignedLine", "GlobalID", "findCodeTokens_Matcher", "SimpleLiveValue", "CancelToCancelPoint", "ReliableSingleThread", "JFastLogView_noWrap", "DynServerAwareDiscordBot", "SingleComponentPanel", "DynModule", "Rect", "Pt", "F0", "F1", "IterableIterator", "betterCIComparator_C", "RGB", "F2", "MakesBufferedImage", "Flag", "unstructure_Receiver", "IFactStore", "IF0", "IHasGlobalID", "CloseableIterableIterator", "ExpiringMap2", "NLRulesBot", "getOpt_Map", "IF2", "Producer", "IFieldsToList", "IF1", "And", "IVF3", "structure_Data", "IVF1", "DynDiscordHopper", "IVF2", "IVar", "DynPrintLogAndEnabled", "BasicLogicRule", "MechMode", "Cache", "_MethodCache", "LineBuffer", "Matches", "structure_ClassInfo", "MechListDependentCache", "LiveValue", "Dyn_FieldWatcher", "LetterLayout", "MultiMap", "Q", "QuickException", "LongRange", "CriticalAction", "Lowest", "IResourceLoader", "Either", "DynTalkBot2", "T3", "Pair", "DynPrintLog", "FunctionNameAndPattern", "AllOnAll", "IntRange", "Cluster", "Transformable", "LinkedTreeSet", "HasGlobalID", "PhilosophyBot1", "CancelPoint", "BetterLabel", "MRUCache", "componentPopupMenu_Adapter", "DynamicObject", "PersistableThrowable", "Scored", "RGBImage", "WithTrail", "AllOnAllWithUpdates", "SimpleFactStore", "StringClustersWithIDs"); static List myInnerClasses() { return myInnerClasses_list; } static DynModule dm_currentModule() { return (DynModule) dm_current_generic(); } static void cancelTimerOrInterruptThread(Object timer) { if (timer instanceof Thread && !(timer instanceof AutoCloseable)) // AutoCloseable takes precedence interruptThread((Thread) timer); else cancelTimer(timer); } static String discordAtPlusID(long userID) { return userID == 0 ? "unknown person" : "<@" + userID + "> (" + userID + ")"; } static boolean isAbstract(Class c) { return (c.getModifiers() & Modifier.ABSTRACT) != 0; } static boolean isAbstract(Method m) { return (m.getModifiers() & Modifier.ABSTRACT) != 0; } static Set allInterfacesImplementedBy(Class c) { if (c == null) return null; HashSet set = new HashSet(); allInterfacesImplementedBy_find(c, set); return set; } 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); } static Method findMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args); } static boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } static Method findStaticMethod(Class c, String method, Object... args) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (!m.getName().equals(method)) continue; if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args)) continue; return m; } c = c.getSuperclass(); } return null; } static boolean findStaticMethod_checkArgs(Method m, Object[] args) { Class[] types = m.getParameterTypes(); if (types.length != args.length) return false; for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) return false; return true; } static List quoteAll(Collection l) { List x = new ArrayList(); for (String s : l) x.add(quote(s)); return x; } static int _hashCode(Object a) { return a == null ? 0 : a.hashCode(); } static ArrayList toList(A[] a) { return asList(a); } static ArrayList toList(int[] a) { return asList(a); } static ArrayList toList(Set s) { return asList(s); } static ArrayList toList(Iterable s) { return asList(s); } static boolean arraysEqual(Object[] a, Object[] b) { if (a.length != b.length) return false; for (int i = 0; i < a.length; i++) if (neq(a[i], b[i])) return false; return true; } static boolean hasLock(Lock lock) { return ((ReentrantLock) lock).isHeldByCurrentThread(); } static String mL_raw(String name) { return mechList_raw(name); } static boolean eqOrSame(Object a, Object b) { return a == null ? b == null : a == b || b != null && a.equals(b); } static String assertGlobalID(String s) { return assertPossibleGlobalID(s); } static BigInteger bigint(String s) { return new BigInteger(s); } static BigInteger bigint(long l) { return BigInteger.valueOf(l); } static BigInteger plus(BigInteger a, BigInteger b) { return a.add(b); } static BigInteger plus(BigInteger a, long b) { return a.add(bigint(b)); } static BigInteger mul(BigInteger a, BigInteger b) { return a.multiply(b); } static BigInteger mul(BigInteger a, long b) { return a.multiply(bigint(b)); } static String bigintToGlobalID(BigInteger value) { char[] buf = new char[16]; for (int i = 16-1; i >= 0; i--) { buf[i] = charPlus('a', mod(value, 26).intValue()); value = div(value, 26); } return str(buf); } static void remove(List l, int i) { if (l != null && i >= 0 && i < l(l)) l.remove(i); } static void remove(Collection l, A a) { if (l != null) l.remove(a); } static Set keySet(Map map) { return map == null ? new HashSet() : map.keySet(); } static Set keySet(Object map) { return keys((Map) map); } static Set keySet(MultiMap mm) { return mm.keySet(); } static A reverseGet(List l, int idx) { if (l == null || idx < 0) return null; int n = l(l); return idx < n ? l.get(n-1-idx) : null; } static File loadLibrary(String snippetID) { return loadBinarySnippet(snippetID); } static int boostHashCombine(int a, int b) { return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2)); } static A nu(Class c, Object... values) { A a = nuObject(c); setAll(a, values); return a; } 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);"; }}); } static AutoCloseable dm_vmBus_onMessage_q(final String msg, final IVF1 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);"; }}); } static AutoCloseable dm_vmBus_onMessage_q(final String msg, final IVF2 onMessage) { final DynModule m = dm_current_mandatory(); return dm_vmBus_onMessage(msg, new VF2() { public void get(A a, 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);"; }}); } static AutoCloseable dm_vmBus_onMessage_q(final String msg, final IVF3 onMessage) { DynModule m = dm_current_mandatory(); return dm_vmBus_onMessage(msg, new VF3() { public void get(A a, B b, C c) { try { m.q().add(new Runnable() { public void run() { try { callF(onMessage, a, b, c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, a, b, c);"; }}); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "switch to m.q();\r\n callF(onMessage, a, b, c);"; }}); } 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);"; }}); } static AutoCloseable dm_vmBus_onMessage_q(final String msg, final VF3 onMessage) { final DynModule m = dm_current_mandatory(); return dm_vmBus_onMessage(msg, new VF3() { public void get(final A a, final B b, final C c) { try { m.q().add(new Runnable() { public void run() { try { callF(onMessage, a, b, c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, a, b, c);"; }}); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "switch to m.q();\r\n callF(onMessage, a, b, c);"; }}); } 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);"; }}); } static long getLong(Object o, String field) { return toLong(getOpt(o, field)); } static long getLong(String field, Object o) { return getLong(o, field); } static String dropPrefixICTrim_orNull(String prefix, String s) { return swic(s, prefix) ? trim(s.substring(l(prefix))) : null; } static List replace(List l, A a, A b) { for (int i = 0; i < l(l); i++) if (eq(l.get(i), a)) l.set(i, b); return l; } static List replace(A a, A b, List l) { return replace(l, a, b); } static String replace(String s, String a, String b) { return s == null ? null : a == null || b == null ? s : s.replace(a, b); } static String replace(String s, char a, char b) { return s == null ? null : s.replace(a, b); } static String dropPunctuation3_withAGIBlue(boolean useAGIBlue, String s) { return useAGIBlue ? dropPunctuation3_withAGIBlue(s) : dropPunctuation3(s); } 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 __1 = agiBlue_lookupInSlice_pcall("xwxxvxozhdlwsxzj", s, "dropPunctuation"); if (!empty(__1)) return __1; } y = dropPunctuation3(s); agiBlue_postInSlice_pcall("xwxxvxozhdlwsxzj", s, "dropPunctuation", y); return y; } static String simpleSpaces_noTok(String s) { return s == null ? null : s.replaceAll("\\s+", " "); } static boolean eqicOneOf(String s, String... l) { for (String x : l) if (eqic(s, x)) return true; return false; } static String nextGenBotsDiscordInvite() { return "https://discord.gg/SEAjPqk"; } static String snippetLink(String id) { return empty(id) ? id : "http://code.botcompany.de/" + parseSnippetID(id); } 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; } static boolean setAdd(Collection c, A a) { if (c == null || c.contains(a)) return false; c.add(a); return true; } static long parseFirstLong(String s) { return parseLong(jextract("", s)); } static boolean containsDiscordToken(String s) { return regexpFind(discordTokenRegexp(), s); } static String jda_selfUserName(JDA jda) { return jda_selfUser(jda).getName(); } static String ymd_minus_hms() { return ymd() + "-" + hms(); } static File createZipFileWithSingleTextFile(File zipFile, String name, String text) { ZipOutputStream outZip = newZipOutputStream(zipFile); try { zip_addTextFile(outZip, name, text); return zipFile; } finally { _close(outZip); }} static String appendSpaceIfEndsWithLetter(String s) { return endsWithLetter(s) ? s + " " : s; } static String quoteBorderless(Object o) { if (o == null) return "null"; return quoteBorderless(str(o)); } static String quoteBorderless(String s) { if (s == null) return "null"; StringBuilder out = new StringBuilder((int) (l(s)*1.5)); quoteBorderless_impl(s, out); return out.toString(); } static void quoteBorderless_impl(String s, StringBuilder out) { int l = s.length(); for (int i = 0; i < l; i++) { char c = s.charAt(i); if (c == '\\' || c == '"') out.append('\\').append(c); else if (c == '\r') out.append("\\r"); else if (c == '\n') out.append("\\n"); else out.append(c); } } static int hashCodeFor(Object a) { return a == null ? 0 : a.hashCode(); } static boolean stdEq2(Object a, Object b) { if (a == null) return b == null; if (b == null) return false; if (a.getClass() != b.getClass()) return false; for (String field : allFields(a)) if (neq(getOpt(a, field), getOpt(b, field))) return false; return true; } static int stdHash2(Object a) { if (a == null) return 0; return stdHash(a, toStringArray(allFields(a))); } static UnsupportedOperationException unsupportedOperation() { throw new UnsupportedOperationException(); } static String stdToString(Object o) { return standard_toString(o); } static Set syncLinkedCISet() { return synchronizedSet(linkedCISet()); } static TreeSet litciset(String... items) { TreeSet set = caseInsensitiveSet(); for (String a : items) set.add(a); return set; } static Pair splitAtFirstDoubleArrow(String s) { return splitAtFirstDoubleArrow(javaTok(s)); } static Pair splitAtFirstDoubleArrow(List tok) { int i = indexOfSubList(tok, splitAtDoubleArrow_tok()); return i < 0 ? null : pair(trimJoin(subList(tok, 0, i)), trimJoin(subList(tok, i+3))); } static List javaTokWithBrackets(String s) { return javaTokPlusBrackets(s); } static BasicLogicRule curryLHS(BasicLogicRule rule) { return curryLHS_BasicLogicRule(rule); } static boolean syncAdd(Collection c, A b) { if (c == null) return false; synchronized(c) { return c.add(b); } } static void syncAdd(List l, int idx, A b) { if (l != null) synchronized(l) { l.add(idx, b); } } static String tok_deRoundBracket(String s) { return tok_isRoundBracketed(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s; } static int countCodeTokens(String s) { return countTokens(s); } static int countCodeTokens(List tok) { return countTokens(tok); } static boolean firstTokenEqic(List tok, String t) { return eqic(get(tok, 1), t); } static boolean isCurlyBracketed(String s) { return isCurlyBraced(s); } static String getCodeToken(List tok, int i) { return get(tok, i*2+1); } static String uncurly_keepSpaces(String s) { return tok_unCurlyBracket_keepSpaces(s); } static String indentx(String s) { return indentx(indent_default, s); } static String indentx(int n, String s) { return dropSuffix(repeat(' ', n), indent(n, s)); } static String indentx(String indent, String s) { return dropSuffix(indent, indent(indent, s)); } static int countJavaTokens(String s) { return countTokens(s); } static int countJavaTokens(List tok) { return countTokens(tok); } static String javaDropAllComments(String s) { return join(javaDropAllComments(javaTok(s))); } static List javaDropAllComments(List tok) { for (int i = 0; i < l(tok); i += 2) tok.set(i, tok_javaDropCommentsFromWhitespace(tok.get(i))); return tok; } static LinkedList cloneLinkedList(Iterable l) { return l instanceof Collection ? cloneLinkedList((Collection) l) : asLinkedList(l); } static LinkedList cloneLinkedList(Collection l) { if (l == null) return new LinkedList(); synchronized(collectionMutex(l)) { return new LinkedList(l); } } static A popFirst_ping(List l) { ping(); return popFirst(l); } static A popFirst_ping(Collection l) { ping(); return popFirst(l); } static List popFirst_ping(int n, List l) { ping(); return popFirst(n, l); } static String sfu(Object o) { return structureForUser(o); } static TreeMap litcimap(Object... x) { return litCIMap(x); } static LinkedList mapToLinkedList(Iterable l, Object f) { LinkedList x = new LinkedList(); if (l != null) for (Object o : l) x.add(callF(f, o)); return x; } static LinkedList mapToLinkedList(Iterable l, IF1 f) { return mapToLinkedList(l, (Object) f); } static String replaceVars(String s, Map map) { return empty(map) ? s : join(replaceVars(javaTok(s), map)); } static List replaceVars(List tok, Map map) { if (empty(map)) return tok; tok = cloneList(tok); for (String var : keys(map)) jreplace(tok, var, map.get(var)); return tok; } static Map mapValues(Object func, Map map) { Map m = similarEmptyMap(map); for (Object key : keys(map)) m.put(key, callF(func, map.get(key))); return m; } static Map mapValues(Map map, IF1 f) { return mapValues(f, map); } static Map mapValues(IF1 f, Map map) { return mapValues((Object) f, map); } static Map mapValues(Map map, Object func) { return mapValues(func, map); } static String optRound(String s) { return roundBracketIfMoreThanOneToken(s); } static boolean isTrueOpt(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); return false; } static Map mapKeys(Object func, Map map) { Map m = similarEmptyMap(map); // TODO: this might break when key type changes through func for (Object key : keys(map)) m.put(callF(func, key), map.get(key)); return m; } static Map mapKeys(Map map, Object func) { return mapKeys(func, map); } static Map mapKeys(Map map, IF1 func) { return mapKeys(map, (Object) func); } static Map mapKeys(IF1 func, Map map) { return mapKeys(map, func); } static A lookupOrKeep(Map map, A key) { return map != null && map.containsKey(key) ? map.get(key) : key; } static List tok_splitAtAmpersand(String s) { return splitAtTokens(javaTokWithAllBrackets_cached(s), "&"); } static String[] dropFirst(int n, String[] a) { return drop(n, a); } static String[] dropFirst(String[] a) { return drop(1, a); } static Object[] dropFirst(Object[] a) { return drop(1, a); } static List dropFirst(List l) { return dropFirst(1, l); } static List dropFirst(int n, Iterable i) { return dropFirst(n, toList(i)); } static List dropFirst(Iterable i) { return dropFirst(toList(i)); } static List dropFirst(int n, List l) { return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size())); } static List dropFirst(List l, int n) { return dropFirst(n, l); } static String dropFirst(int n, String s) { return substring(s, n); } static String dropFirst(String s, int n) { return substring(s, n); } static String dropFirst(String s) { return substring(s, 1); } static String tok_deRoundOrCurlyBracket(String s) { return isCurlyBraced(s) || tok_isRoundBracketed(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s; } static void removeFromMapWhere(Map map, IF2 pred) { if (map == null) return; Iterator> i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = i.next(); if (pred.get(e.getKey(), e.getValue())) i.remove(); } } static Map gazelle_deepZip_keepBrackets(String inputA, String inputB, Object... __) { Map map = gazelle_zip_keepBrackets(inputA, inputB); if (map == null) return null; Map map2 = similarEmptyMap(map); for (String a : keys( map)) { String b = map.get(a); boolean iba = tok_isRoundOrCurlyBracketed(a), ibb = tok_isRoundOrCurlyBracketed(b); if (iba && ibb) { String aa = tok_deRoundOrCurlyBracket(a); String bb = tok_deRoundOrCurlyBracket(b); Map subMap = gazelle_deepZip_keepBrackets(aa, bb, __); if (subMap == null) return null; if (!putAllStrictlyIC(map2, subMap)) return null; } else if (eqic_roundBracketed(a, b)) { // OK, match } else if (!strictPutIC(map2, a, b)) return null; } return map2; } static boolean all(Object pred, Iterable l) { if (l != null) for (Object o : l) if (!isTrue(callF(pred, o))) return false; return true; } static boolean all(Iterable l, IF1 f) { if (l != null) for (A a : l) if (!f.get(a)) return false; return true; } static boolean all(IF1 f, Iterable l) { return all(l, f); } static boolean isDollarVar(String s) { // Possible BREAKING CHANGE (although probably OK): now also accepting $1 etc. return startsWith(s, '$') && l(s) > 1; // OLD: ret startsWith(s, '$') && isJavaIdentifierAfter(s, 1); } static String replaceCodeTokensUsingMap(String s, Map map) { return join(replaceCodeTokensUsingMap(javaTok(s), map)); } static List replaceCodeTokensUsingMap(List tok, Map map) { List out = emptyList(tok); for (int i = 0; i < l(tok); i++) { out.add(odd(i) ? lookupOrKeep(map, tok.get(i)) : tok.get(i)); } return out; } static String replaceCodeTokensUsingMap(Map map, String s) { return replaceCodeTokensUsingMap(s, map); } // meta-transform function that understands Transformable and List // if f returns null, go through structure static Object transform_understandsTransformableAndList(IF1 f, Object o) { if (o == null) return null; ping(); { Object __1= f.get(o); if (__1 != null) return __1; } IF1 myself = x -> transform_understandsTransformableAndList(f, x); if (o instanceof Transformable) return ((Transformable) o).transformUsing(myself); if (o instanceof List) return map(myself, ((List) o)); throw fail("Don't know how to transform: " + className(o)); } static void think(String thought) { miniChat(thought); } static List getAndClearList(Collection l) { if (l == null) return emptyList(); synchronized(collectionMutex(l)) { List out = cloneList(l); l.clear(); return out; } } static List callFAll(Collection l, Object... args) { return callF_all(l, args); } static A pnlWithHeading(String heading, A l) { printAsciiHeading(heading); return pnl(l); } static String tok_dropRoundBrackets(String s) { return join(tok_dropRoundBrackets(javaTok(s))); } static List tok_dropRoundBrackets(List tok) { for (int i = 1; i < l(tok); i+= 2) { while (eqGetOneOf(tok, i, "(", ")")) { tokAppend(tok, i-1, tok.get(i+1)); removeSubList(tok, i, i+2); } } return tok; } static A pnlWithHeadingIfNempty(String heading, A l) { if (nempty(l)) pnlWithHeading(heading, l); return l; } static String properUnquote(String s) { return isProperlyQuoted(s) ? unquote(s) : s; } static A $x(Map map) { return mapGet(map, "$x"); } static A $y(Map map) { return mapGet(map, "$y"); } static String withoutLeadingLinesEmptyAfterTrim_autoUnindent(String s) { return autoUnindent(withoutLeadingLinesEmptyAfterTrim(s)); } static String tok_deRoundOrCurlyBracket_keepFirstSpacing(String s) { return isCurlyBraced(s) || tok_isRoundBracketed(s) ? join(dropFirstTwoAndLastThree(javaTok(s))) : s; } static > C assertContains(C c, A y) { return assertContains(null, c, y); } static > C assertContains(String msg, C c, A y) { if (!contains(c, y)) throw fail((msg != null ? msg + ": " : "") + y + " not contained in " + c); return c; } static B firstValue(Map map) { return first(values(map)); } static > C assertDoesntContain(C c, A y) { return assertDoesntContain(null, c, y); } static > C assertDoesntContain(String msg, C c, A y) { if (contains(c, y)) throw fail((msg != null ? msg + ": " : "") + y + " contained in " + c); return c; } static void philosophyBot1_math(PhilosophyBot1 bot) { bot.addNativePredicate("$x >= $y", (map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) >= 0); bot.addNativePredicate("$x <= $y", (map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) <= 0); bot.addNativePredicate("$x > $y", (map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) > 0); bot.addNativePredicate("$x < $y", (map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) < 0); } static void philosophyBot1_bool(PhilosophyBot1 bot) { // native predicates now work in rule lhs too bot.addNativePredicate("true", map -> true); bot.addNativePredicate("$x = $y", map -> eqic($x(map), $y(map))); bot.addNativePredicate("$x != $y", map -> { String x = $x(map), y = $y(map); print("equality check: " + x + " / " + y); return !eqic(x, y); }); } static void philosophyBot1_orHandler(PhilosophyBot1 bot) { bot.addLogicRulePreprocessor(rule -> { if (!(rule.lhs instanceof String)) return false; List tok = bot.mainTokenize(tok_deCurlyOrRound((String) rule.lhs)); if (countCodeTokens(tok) == 3 && eq(secondCodeToken(tok), "|")) { // split into two rules print("Splitting or: " + tok); bot.addLogicRule(new PhilosophyBot1.LogicRule(firstCodeToken(tok), rule.rhs)); bot.addLogicRule(new PhilosophyBot1.LogicRule(lastCodeToken(tok), rule.rhs)); return true; } return false; }); } static void philosophyBot1_iotaHandler(PhilosophyBot1 bot) { bot.addNativePredicate("iota($x)", (map) -> iota(parseInt($x(map)))); } static A printIf(boolean b, A a) { if (b) print(a); return a; } static A printIf(boolean b, String s, A a) { if (b) print(s, a); return a; } static List tlft_honoringBrackets(String text) { return trimAll(lines_honoringBrackets(text)); } static void philosophyBot1_enableAddSimplifier_withTrails(PhilosophyBot1 bot) { bot.addFactPreprocessor(fact -> { String rule = $x(bot.matchString("add simplifier $x", fact)); if (rule == null) return false; if (bot.verbose) print("adding simplifier: " + rule); Pair p = tok_splitAtDoubleArrow_pair(rule); if (p == null) return false; philosophyBot1_addSimplificationRule_withTrails(bot, p.a, p.b, fact); return true; }); } static List antiFilter(Iterable c, Object pred) { if (pred instanceof F1) return antiFilter(c, (F1) pred); List x = new ArrayList(); if (c != null) for (Object o : c) if (!isTrue(callF(pred, o))) x.add(o); return x; } static List antiFilter(Object pred, Iterable c) { return antiFilter(c, pred); } static List antiFilter(Object pred, Object[] c) { return antiFilter(pred, wrapArrayAsList(c)); } static List antiFilter(Iterable c, F1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (!pred.get(o).booleanValue()) x.add(o); return x; } static List antiFilter(F1 pred, Iterable c) { return antiFilter(c, pred); } static List antiFilter(Iterable c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (!pred.get(o).booleanValue()) x.add(o); return x; } static List antiFilter(IF1 pred, Iterable c) { return antiFilter(c, pred); } static List words2_plusApostrophe(String s) { List l = new ArrayList(); int n = l(s); for (int i = 0; i < n; ) { int j = i; while (j < n && isLetterOrDigitOrApostrophe(s.charAt(j))) ++j; if (j > i) l.add(substring(s, i, j)); while (j < n && !isLetterOrDigitOrApostrophe(s.charAt(j))) ++j; i = j; } return l; } static TreeSet asCISet(Iterable c) { return toCaseInsensitiveSet(c); } static TreeSet asCISet(String... x) { return toCaseInsensitiveSet(x); } static Set filterCISet(Iterable c, Object pred) { Set x = ciSet(); if (c != null) for (String o : c) if (isTrue(callF(pred, o))) x.add(o); return x; } static Set filterCISet(Object pred, Iterable c) { return filterCISet(c, pred); } static Set filterCISet(Iterable c, IF1 pred) { return filterCISet(c, (Object) pred); } static Set filterCISet(IF1 pred, Iterable c) { return filterCISet(c, (Object) pred); } static List listMinusList(Collection l, Collection stuff) { if (empty(stuff) && l instanceof List) return (List) l; List l2 = cloneList(l); for (Object o : stuff) l2.remove(o); return l2; } static void withCancelPoint(VF1 r) { CancelPoint cp = newCancelPoint(); try { try { callF(r, cp); } catch (Throwable e) { e = innerException(e); if (!(e instanceof CancelToCancelPoint && ((CancelToCancelPoint) e).cp == cp)) rethrow(e); } } finally { _close(cp); }} static void withCancelPoint(IVF1 r) { CancelPoint cp = newCancelPoint(); try { try { r.get(cp); } catch (Throwable e) { e = innerException(e); if (!(e instanceof CancelToCancelPoint && ((CancelToCancelPoint) e).cp == cp)) rethrow(e); } } finally { _close(cp); }} static boolean containsDollarVars(String s) { for (String t : javaTokC(s)) if (isDollarVar(t)) return true; return false; } static RuntimeException cancelTo(CancelPoint cp) { if (cp.closed) throw fail("cancel point closed"); throw new CancelToCancelPoint(cp); } // example use: // auto open theories static void philosophyBot_autoOpenTheoriesHandler(PhilosophyBot1 bot) { bot.addFactPreprocessor(s -> { if (bot.matchString("auto open theories", s) == null) return false; bot.autoOpenTheories(); return true; }); } // transformer can return null or input on no change // will not call transformer on individual words static String gazelle_deepTransform(IF1 transformer, String input, Object... __) { if (transformer == null) return input; // call transformer on whole input, return if change String transformed = transformer.get(input); if (transformed != null && transformed != input) return transformed; // transformer didn't do anything, tokenize & go through parts Object tokenizer = optPar("tokenizer",__, "javaTokWithBrackets"); List tok = callTokenizer(tokenizer, input); boolean changes = false; for (int i = 1; i < l(tok); i += 2) { ping(); String t = tok.get(i); if (tok_isRoundOrCurlyBracketed(t)) { String unBracketed = tok_deRoundOrCurlyBracket(t); transformed = gazelle_deepTransform(transformer, unBracketed, __); if (transformed != unBracketed) { if (!changes) tok = cloneList(tok); // in case a caching tokenizer was used // enclose in brackets & replace tok.set(i, startsWith(t, "(") ? roundOpt(transformed) : curlyOpt(transformed)); changes = true; } } } return changes ? join(tok) : input; } static A firstTransformersResult(List> transformers, A a) { for (IF1 f : unnull(transformers)) if (f != null) { A b = f.get(a); if (b != null && b != a) return b; } return a; } // transformer can return null or input on no change // will not call transformer on individual words // returns null if no change static WithTrail gazelle_deepTransform_withTrail(IF1> transformer, String input, Object... __) { if (transformer == null) return null; // call transformer on whole input, return if change WithTrail transformed = transformer.get(input); if (transformed != null) return transformed; // transformer didn't do anything, tokenize & go through parts Object tokenizer = optPar("tokenizer",__, "javaTokWithBrackets"); List tok = callTokenizer(tokenizer, input); List trails = new ArrayList(); boolean changes = false; for (int i = 1; i < l(tok); i += 2) { ping(); String t = tok.get(i); if (tok_isRoundOrCurlyBracketed(t)) { String unBracketed = tok_deRoundOrCurlyBracket(t); transformed = gazelle_deepTransform_withTrail(transformer, unBracketed, __); if (transformed != null) { if (!changes) tok = cloneList(tok); // in case a caching tokenizer was used // enclose in brackets & replace tok.set(i, startsWith(t, "(") ? roundOpt(transformed.get()) : curlyOpt(transformed.get())); trails.add(transformed.trail); changes = true; } } } return changes ? new WithTrail(litmap("op" , "gazelle_deepTransform_withTrail", "input", input, "trails", trails), join(tok)) : null; } static WithTrail firstTransformersResult_trailEnabled(List>> transformers, A a) { for (IF1> f : unnull(transformers)) if (f != null) { WithTrail b = f.get(a); if (b != null) return b; } return null; } static void printAsciiHeading(String text) { print(asciiHeading2(text)); } static A printUnlessNull(A a) { if (a != null) print(a); return a; } static A printUnlessNull(String s, A a) { if (a != null) print(s, a); return a; } static Set instancesOfAsSet(Iterable i, Class c) { return asSet(instancesOf(i, c)); } static Set instancesOfAsSet(Class c, Iterable i) { return instancesOfAsSet(i, c); } static Set setIntersection(Collection a, Collection b) { Set set = similarEmptySet(a); if (nempty(a) && nempty(b)) { Set bSet = asSet(b); for (A x : a) if (bSet.contains(x)) set.add(x); } return set; } static List stringsOnly(Iterable it) { List out = new ArrayList(); for (Object o : unnull(it)) if (o instanceof String) out.add(((String) o)); return out; } // returns visited objects // visitor may be null, then it's just about returning the set static Set philosophyBot1_visitTrailsTree_gen(Object engine, IVF1 visitor, Object startingPoint) { Set seen = new HashSet(); philosophyBot1_visitTrailsTree_gen(engine, seen, visitor, startingPoint); return seen; } static void philosophyBot1_visitTrailsTree_gen(Object engine, Set seen, IVF1 visitor, Object startingPoint) { if (startingPoint == null) return; if (!seen.add(startingPoint)) return; if (visitor != null) visitor.get(startingPoint); if (startingPoint instanceof Iterable) for (Object o : ((Iterable) startingPoint)) philosophyBot1_visitTrailsTree_gen(engine, seen, visitor, o); else if (startingPoint instanceof Map) for (Object o : values(((Map) startingPoint))) philosophyBot1_visitTrailsTree_gen(engine, seen, visitor, o); else philosophyBot1_visitTrailsTree_gen(engine, seen, visitor, rcall("getTrail",engine, startingPoint)); } static LinkedHashMap cloneLinkedHashMap(Map map) { return map == null ? new LinkedHashMap() : new LinkedHashMap(map); } static BufferedImage toBufferedImage(Object o) { return toBufferedImageOpt(o); } static boolean inRange(int x, int n) { return x >= 0 && x < n; } static boolean inRange(int x, int a, int b) { return x >= a && x < b; } static int limitToUByte(int i) { return max(0, min(255, i)); } static List syncList() { return synchroList(); } static List syncList(List l) { return synchroList(l); } static boolean any(Object pred, Iterable l) { if (l != null) for (A a : l) if (isTrue(callF(pred, a))) return true; return false; } static boolean any(IF1 pred, Iterable l) { return any((Object) pred, l); } static boolean any(Iterable l, IF1 pred) { return any(pred, l); } static GlobalID aGlobalIDObject() { return aGlobalIDObj(); } static void add(BitSet bs, int i) { bs.set(i); } static boolean add(Collection c, A a) { return c != null && c.add(a); } static void add(Container c, Component x) { addToContainer(c, x); } static int intSum(Collection c, String field) { int sum = 0; for (Object o : unnull(c)) sum += toInt(getOpt(o, field)); return sum; } static int intSum(Iterable l) { int sum = 0; for (Integer i : unnull(l)) if (i != null) sum += i; return sum; } static void addPair(Collection> c, A a, B b) { if (c != null) c.add(pair(a, b)); } static IntRange intRange_last(List l) { int n = l(l); return intRange(n-1, n); } static IntRange intRange(int start, int end) { return new IntRange(start, end); } static IterableIterator> outerProduct_pairs(Collection lA, Collection lB) { return outerProductPairs(lA, lB); } static IterableIterator> outerProduct_pairs(Pair, ? extends Collection> p) { return outerProduct_pairs(p.a, p.b); } static ArrayList clonedList(Iterable l) { return cloneList(l); } static ArrayList clonedList(Collection l) { return cloneList(l); } static Set linkedCISet() { return new LinkedTreeSet(ciSet()); } static String curly(String s) { return optionalCurlyBrace(s); } static String joinWithSlash(Iterable l) { return join("/", l); } static int asInt(Object o) { return toInt(o); } static int iround(double d) { return (int) Math.round(d); } static int iround(Number n) { return iround(toDouble(n)); } static boolean dm_isMe(Object mod) { return dm_getModule(mod) == dm_current_mandatory_generic(); } static boolean set_trueIfChanged(Object o, String field, Object value) { if (eq(get(o, field), value)) return false; set(o, field, value); return true; } static List nempties(Collection c) { return filterNempty(c); } static A pairA(Pair p) { return p == null ? null : p.a; } static Pair syncGetOrCreate2(Map map, A key, Class c) { try { synchronized(map) { B b = map.get(key); if (b == null) { map.put(key, b = c.newInstance()); return pair(b, true); } return pair(b, false); } } catch (Exception __e) { throw rethrow(__e); } } static Pair syncGetOrCreate2(Class c, Map map, A key) { return syncGetOrCreate2(map, key, c); } static Pair syncGetOrCreate2(Map map, A key, F0 f) { try { synchronized(map) { B b = map.get(key); if (b == null) { map.put(key, b = callF(f)); return pair(b, true); } return pair(b, false); } } catch (Exception __e) { throw rethrow(__e); } } static Pair syncGetOrCreate2(Map map, A key, IF0 f) { try { synchronized(map) { B b = map.get(key); if (b == null) { map.put(key, b = f.get()); return pair(b, true); } return pair(b, false); } } catch (Exception __e) { throw rethrow(__e); } } static int countValuesWhere_sync(Map map, Object... data) { if (map == null) return 0; synchronized(map) { return countWhere(values(map), data); } } static A keyForValue_sync(B value, Map map) { return keyForValue_sync(map, value); } static A keyForValue_sync(Map map, B value) { if (map == null || value == null) return null; synchronized(map) { return keyForValue(map, value); } } static LongRange longRange_one(long start) { return new LongRange(start, start+1); } static LongRange longRange(long start, long end) { return new LongRange(start, end); } static void removeValue(Map map, B value) { if (map == null) return; Iterator> i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = i.next(); if (eq(e.getValue(), value)) i.remove(); } } static SortedMap subMap_longRange(SortedMap map, LongRange range) { return subMap(map, range.start, range.end); } static A set(A o, String field, Object value) { if (o == null) return null; if (o instanceof Class) set((Class) o, field, value); else try { Field f = set_findField(o.getClass(), field); makeAccessible(f); smartSet(f, o, value); } catch (Exception e) { throw new RuntimeException(e); } return o; } static void set(Class c, String field, Object value) { if (c == null) return; try { Field f = set_findStaticField(c, field); makeAccessible(f); smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } static Field set_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } static Field set_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } static long sysNow() { ping(); return System.nanoTime()/1000000; } static int hashOfLong(long l) { return Long.hashCode(l); } static int length(Object[] array) { return array == null ? 0 : array.length; } static int length(List list) { return list == null ? 0 : list.size(); } static int length(String s) { return s == null ? 0 : s.length(); } static void internalFramePopupMenuItem(Container f, final String name, final Object action) { internalFrameTitlePopupMenuItem(((JInternalFrame) f), name, action); } static Runnable runnableThread(final Runnable r) { return new Runnable() { public void run() { try { startThread(r) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "startThread(r)"; }}; } static void minFrameSize(Component c, int w, int h) { minimalFrameSize(c, w, h); } static String getString(Map map, Object key) { return map == null ? null : (String) map.get(key); } static String getString(List l, int idx) { return (String) get(l, idx); } 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)); } static String getString(String key, Object o) { return getString(o, (Object) key); } static Object dm_rcall(String method, Object moduleOrID, Object... args) { return dm_call(moduleOrID, method, args); } static long rcall_long(String method, Object o, Object... args) { return toLong(rcall(method, o, args)); } static String lstr(Map map) { return str(l(map)); } static String lstr(Collection c) { return str(l(c)); } static String lstr(String s) { return str(l(s)); } static List dm_activeDiscordTokens() { return concatLists((List>) vmBus_queryAll("activeDiscordTokens")); } static String myPublicIP() { return myFirewallIP(); } static List extractPossibleDiscordTokens(String s) { return regexpAll(discordTokenRegexp(), s); } 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; } static String dm_showNewModuleWithParams(String moduleLibID, Object... params) { String moduleID = dm_makeNewModuleWithParams(moduleLibID, params); dm_showModule(moduleID); return moduleID; } static String dm_moduleLibID() { return programID() + "/" + shortClassName(dm_current_mandatory_generic()); } 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; } static String discordAtExclam(long userID) { return userID == 0 ? "unknown person" : "<@!" + userID + ">"; } static void dm_watchField(String field, Runnable onChange) { new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange); } static void dm_reloadOnFieldChange(String... fields) { for (String field : unnull(fields)) dm_onFieldChange(field, new Runnable() { public void run() { try { dm_reloadModule(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "dm_reloadModule();"; }}); } static double elapsedMinutes_timestamp(long time) { return toMinutes(now()-time); } static void containerAddFirst(final Container c, final Component... l) { { swing(new Runnable() { public void run() { try { for (int i = 0; i < l(l); i++) c.add(l[i], i); revalidate(c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "for (int i = 0; i < l(l); i++)\r\n c.add(l[i], i);\r\n revalidate(c);"; }}); } } // action can be Runnable or a function name static JButton jThreadedButton(final String text, final Object action) { return swing(new F0() { public JButton get() { try { String text2 = dropPrefix("[disabled] ", text); final JButton btn = new JButton(text2); if (l(text2) < l(text)) btn.setEnabled(false); btn.setToolTipText(btn.getText()); if (action != null) btn.addActionListener(actionListenerInNewThread(action, btn)); return btn; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "S text2 = dropPrefix(\"[disabled] \", text);\r\n final JButton btn = new JButt..."; }}); } static void dm_stringFieldDialog(final String field, final Object... __) { final DynModule m = dm_current_mandatory(); final String humanized = humanizeFormLabel(field); final JTextField tf = jtextfield(get(m, field)); showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() { public void run() { try { m.setField(field, gtt(tf)); callF(optPar(__, "onSet")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, gtt(tf));\r\n callF(optPar(__, \"onSet\"));"; }}); } 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);"; }}); } } // menuParams: text, Runnable, ... // also: position := 'left/'center/'right static JButton jPopDownButton_noText(final Object... menuParams) { return toolTip("Additional commands", jPopDownButton("", menuParams)); } static void dm_exportStructureToTextFileDialog(DynModule mod) { inputText("Text file to save data in (" + dm_moduleName(mod) + ")", f2s(dm_structureExportDefaultFile(mod)), new VF1() { public void get(String path) { try { saveTextFileWithInfoBox(newFile(path), javaTokWordWrap(dm_freshModuleStructureWithoutError(mod))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "saveTextFileWithInfoBox(newFile(path),\r\n javaTokWordWrap(dm_freshModul..."; }}); } static void dm_importStructureFromTextFileDialog(DynModule mod) { File f = showFileChooserWithDefaultDir("Module data to restore", javaxBackupDir()); if (fileExists(f)) { infoBox("Replacing module with " + f2s(f)); dm_replaceModuleWithStructure(mod, loadTextFile(f)); } } 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; } static A setEnabled(boolean enable, A c) { return setEnabled(c, enable); } static void dm_reload() { dm_reloadMe(); } static JPanel jSection(Component c) { return jSection("", c); } static JPanel jSection(final String title, final Component c) { return swing(new F0() { public JPanel get() { try { Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED); border = BorderFactory.createTitledBorder(border, title); JSection panel = new JSection(c); panel.setBorder(border); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n bo..."; }}); } static JPanel jSection(String title) { return jSection(title, jpanel()); } static JScrollPane jscroll_copyBackground(Component c) { return setScrollPaneBackground(getBackground(c), jscroll(c)); } static JFastLogView_noWrap jFastLogView_noWrap() { return jFastLogView_noWrap(""); } static JFastLogView_noWrap jFastLogView_noWrap(String text) { return withTypeWriterFont(swingNu(JFastLogView_noWrap.class, text)); } static String getPrintLog() { return str(print_log); } static A componentPopupMenuItem(A c, final String name, final Object action) { componentPopupMenu(c, new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, name, action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, name, action);"; }}); return c; } static void componentPopupMenuItem(JComponent c, final JMenuItem menuItem) { componentPopupMenu(c, new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, menuItem); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, menuItem);"; }}); } static void dm_clearModulePrintLog() { clearStringBuffer_gen(dm_current_mandatory()._actualPrintLog()); } static A awtEvery(A component, long delay, Object r) { swingEvery(component, delay, r); return component; } static A awtEvery(A component, long delay, long firstDelay, Object r) { swingEvery(component, delay, firstDelay, r); return component; } static void awtEvery(RootPaneContainer frame, long delay, Object r) { swingEvery(frame, delay, r); } static A awtEvery(A component, double delaySeconds, Object r) { return awtEvery(component, toMS(delaySeconds), r); } static Object swing(Object f) { return swingAndWait(f); } static A swing(F0 f) { return (A) swingAndWait(f); } static A swing(IF0 f) { return (A) swingAndWait(f); } static boolean scrollAllTheWayDown_bruteForce = true; static void scrollAllTheWayDown(final JComponent c) { if (c != null) { swing(new Runnable() { public void run() { try { int h = c.getHeight()-1; if (scrollAllTheWayDown_bruteForce) h = max(h, 100000); c.scrollRectToVisible(new Rectangle(0, h, 1, 1)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "int h = c.getHeight()-1;\r\n if (scrollAllTheWayDown_bruteForce) h = max(h, ..."; }}); } } // independent timer static void awtLater(int delay, final Object r) { swingLater(delay, r); } static void awtLater(Object r) { swingLater(r); } // dependent timer (runs only when component is visible) static void awtLater(JComponent component, int delay, Object r) { installTimer(component, r, delay, delay, false); } static void awtLater(JFrame frame, int delay, Object r) { awtLater(frame.getRootPane(), delay, r); } static StringBuffer liveLocalPrintLog_realMC(Object o) { Object realMC = getMainClass(o); if (realMC != mc()) return (StringBuffer) getOpt(realMC, "local_log"); return liveLocalPrintLog(); } static Dimension getPreferredSize(final Component c) { return c == null ? null : swing(new F0() { public Dimension get() { try { return c.getPreferredSize(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getPreferredSize();"; }}); } static int getWidth(Component c) { return c == null ? 0 : (int) swingCall(c, "getWidth"); } static int getHeight(Component c) { return c == null ? 0 : (int) swingCall(c, "getHeight"); } static Color getBackground(final Component c) { return c == null ? null : swing(new F0() { public Color get() { try { return c.getBackground(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getBackground();"; }}); } static FontMetrics componentFontMetrics(JComponent c) { Font font = getFont(c); return font == null ? null : swing(new F0() { public FontMetrics get() { try { return c.getFontMetrics(font); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getFontMetrics(font);"; }}); } static int idiv_ceil(int a, int b) { return (a+b-1)/b; } static int idiv_ceil(long a, long b) { return toInt_checked((a+b-1)/b); } static boolean setText_opt = true; // optimize by calling getText first static A setText(A c, Object text) { setText((JComponent) c, text); return c; } static A setText(final A c, Object text) { // only for editable combo boxes at this point 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; } static void setText(JLabel c, Object text) { setText((JComponent) c, text); } static JButton setText(JButton c, Object text) { setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text))); return c; } 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; } static List asSyncList(Iterable l) { return asSynchroList(l); } static A _revalidate(A c) { return revalidate(c); } static void _revalidate(JFrame f) { revalidate(f); } static void _revalidate(JInternalFrame f) { revalidate(f); } static boolean endsWithNewLine(String s) { return endsWith(s, "\n"); } static String getText(final AbstractButton c) { return c == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getText();"; }}); } static String getText(final JTextComponent c) { return c == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getText();"; }}); } static String getText(final JLabel l) { return l == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return l.getText(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret l.getText();"; }}); } // returns the contents of text field for editable combo box static String getText(final JComboBox cb) { if (cb == null) return null; if (isEditableComboBox(cb)) return unnull((String) cb.getEditor().getItem()); else return str(cb.getSelectedItem()); } static String lines_rtrimIf(boolean rtrim, List lines) { return rtrim ? lines_rtrim(lines) : lines(lines); } static String copyTextToClipboard(Object _text) { String text = str(_text); StringSelection selection = new StringSelection(text); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection); vmBus_send("newClipboardContents", text); return text; } static Flag dm_initErrorHandling_flag = new Flag(); static void dm_initErrorHandling() { raiseFlagAndDo(dm_initErrorHandling_flag, new Runnable() { public void run() { try { _handleException_addHandler("dm_initErrorHandling_handler"); assertNull(_onRegisterThread); _onRegisterThread = new VF1() { public void get(Thread t) { try { DynModule m = dm_currentModule(); if (m == null) printStackTrace("New thread made outside of a module"); else m.ownTimer(t); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "DynModule m = dm_currentModule();\r\n if (m == null) printStackTrace(\"New ..."; }}; _threadInfo_makers.add(new VF1() { public void get(Map map) { try { mapPut(map, "dm_currentModule_value", dm_currentModule()) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "mapPut(map, 'dm_currentModule_value, dm_currentModule())"; }}); _threadInheritInfo_retrievers.add(new VF1() { public void get(Map map) { try { Object mod = map.get("dm_currentModule_value"); if (mod instanceof DynModule) dm_currentModule_value.set(new WeakReference((DynModule) mod)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O mod = map.get('dm_currentModule_value);\r\n if (mod instanceof DynModule..."; }}); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_handleException_addHandler(f dm_initErrorHandling_handler);\r\n \r\n asser..."; }}); } static void dm_initErrorHandling_handler(Throwable e) { DynModule m = dm_currentModule(); if (m == null) print("Weird: Error outside of module"); else m.setField("_error" , persistableThrowable(e)); } static void setMainDesktopPane(JDesktopPane desktop) { mainDesktopPane_value = desktop; } static A getCreatorOpt(String field) { return (A) getOpt(creator(), field); } static A possiblyInternalFrameTitle(A c, String title) { JInternalFrame f = getInternalFrame(c); if (f != null) internalFrameTitle(f, title); else frameTitle(getFrame(c), title); return c; } static String possiblyInternalFrameTitle(Component c) { JInternalFrame f = getInternalFrame(c); return f != null ? internalFrameTitle(f) : frameTitle(getFrame(c)); } static void ownResource(AutoCloseable c) { _registerAutoCloseable(c); } static Map getAndClearMap(Map map) { if (map == null) return emptyMap(); synchronized(collectionMutex(map)) { Map out = cloneMap(map); map.clear(); return out; } } static Object pcallFInRealOrMyMC(final Object realm, final Object f, final Object... args) { try { return callFInRealOrMyMC(realm, f, args); } catch (Throwable __e) { _handleException(__e); } return null; } static A pcallFInRealOrMyMC(Object realm, F0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { return null; } } static B pcallFInRealOrMyMC(Object realm, F1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { return null; } } static Rect dm_getBounds(Object module) { return shallowCloneToClass(Rect.class,call(dm_getStem(module), "getFrameRect")); } static Rect dm_getBounds() { return dm_getBounds(dm_current_generic()); } static boolean hasMethod_onTypes(Object o, String method, Class... argTypes) { return findMethod_precise_onTypes(o, method, argTypes) != null; } static void dm_onTopInput_q(final VF1 r) { final DynModule m = dm_current_mandatory(); dm_onTopInput(new VF1() { public void get(final String s) { try { m.q().add(new Runnable() { public void run() { try { callF(r, s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(r, s);"; }}); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "switch to m.q();\r\n callF(r, s);"; }}); } static AutoCloseable combineAutoCloseables(final AutoCloseable a, final AutoCloseable b) { return a == null ? b : b == null ? a : new AutoCloseable() { public String toString() { return "a.close(); b.close();"; } public void close() throws Exception { a.close(); b.close(); }}; } static AutoCloseable combineAutoCloseables(AutoCloseable a, AutoCloseable b, AutoCloseable c, AutoCloseable... more) { return combineAutoCloseables(concatLists(ll(a, b, c), asList(more))); } 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); } static ThreadLocal realMC_tl_tl = new ThreadLocal(); static ThreadLocal realMC_tl() { return realMC_tl_tl; } static AutoCloseable tempLock(final Lock lock) { if (lock == null) return null; lock(lock); return new AutoCloseable() { public String toString() { return "unlock(lock);"; } public void close() throws Exception { unlock(lock); }}; } static boolean addIfNotThere(Collection c, A a) { return setAdd(c, a); } static 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; } 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; } static void onChange(JTextComponent tc, Object r) { onUpdate(tc, r); } 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; } static JComboBox onChange(Object r, JComboBox cb) { return onChange(cb, r); } 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; } // action = runnable or method name static void onUpdateAndNow(JComponent c, final Object r) { onUpdate(c, r); callF(r); } static void onUpdateAndNow(List l, Object r) { for (JComponent c : l) onUpdate(c, r); callF(r); } // action = runnable or method name static void onUpdate(JComponent c, final Object r) { if (c instanceof JTextComponent) ((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { call(r); } public void removeUpdate(DocumentEvent e) { call(r); } public void changedUpdate(DocumentEvent e) { call(r); } }); else if (c instanceof ItemSelectable) // JCheckBox and others ((ItemSelectable) c).addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { call(r); } }); else print("Warning: onUpdate doesn't know " + getClassName(c)); } static void onUpdate(List l, Object r) { for (JComponent c : l) onUpdate(c, r); } static void zeroAllFieldsOfTypeExcept(Object o, Class type, String... exceptions) { zeroAllFieldsOfTypeExcept(o, type, asSet(exceptions)); } static void zeroAllFieldsOfTypeExcept(Object o, Class type, Collection exceptions) { Set set = asSet(exceptions); for (String field : allFields(o)) if (!set.contains(field) && instanceOf(getOpt(o, field), type)) set(o, field, null); } static List paramsToAbstractActions(Object... params) { List l = new ArrayList(); for (int i = 0; i+1 < l(params); i += 2) { String text = (String) (params[i]); Runnable action = (Runnable) (params[i+1]); if (nempty(text)) l.add(abstractAction(text, action)); } return l; } static void internalFramePopupMenuFromActions_threaded(Container f, List actions) { if (!(f instanceof JInternalFrame)) return; for (final AbstractAction a : unnull(actions)) if (a != null) internalFramePopupMenuItem(((JInternalFrame) f), str(a.getValue(Action.NAME)), runnableThread(new Runnable() { public void run() { try { callAction(a) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callAction(a)"; }})); } static LinkedHashSet asLinkedHashSet(A[] array) { LinkedHashSet set = new LinkedHashSet(); for (A o : array) if (o != null) set.add(o); return set; } static LinkedHashSet asLinkedHashSet(Collection l) { if (l instanceof LinkedHashSet) return (LinkedHashSet) l; LinkedHashSet set = new LinkedHashSet(); for (A o : l) if (o != null) set.add(o); return set; } static List splitAtSpace(String s) { return empty(s) ? emptyList() : asList(s.split("\\s+")); } static Set allFields(Object o) { TreeSet fields = new TreeSet(); Class _c = _getClass(o); do { for (Field f : _c.getDeclaredFields()) fields.add(f.getName()); _c = _c.getSuperclass(); } while (_c != null); return fields; } static Class fieldType(Object o, String field) { Field f = getField(o, field); return f == null ? null : f.getType(); } static void dm_boolFieldMenuItem(Container frame, final String field, final Object... __) { final DynModule m = dm_current_mandatory(); final String humanized = humanizeFormLabel(field); internalFrameTitlePopupMenu(((JInternalFrame) frame), new VF1() { public void get(JPopupMenu menu) { try { menu.add(jCheckBoxMenuItem(humanized, (boolean) _get(m, field), new VF1() { public void get(Boolean b) { try { m.setField(field, b); callF(optPar(__, "onSet")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, b);\r\n callF(optPar(_, 'onSet));"; }})); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "menu.add(jCheckBoxMenuItem(humanized, (bool) _get(m, field), voidfunc(bool b)..."; }}); } static void dm_intFieldMenuItem(Container frame, final String field, final Object... __) { final DynModule m = dm_current_mandatory(); final String humanized = humanizeFormLabel(field); internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() { public void run() { try { final JTextField tf = jtextfield(get(m, field)); showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() { public void run() { try { m.setField(field, parseInt(gtt(tf))); callF(optPar(__, "onSet")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, parseInt(gtt(tf)));\r\n callF(optPar(__, \"onSet\"));"; }}); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tf = jtextfield(get(m, field));\r\n showFormTitled(or2(stri..."; }}); } static void dm_doubleFieldMenuItem(Container frame, final String field, final Object... __) { final DynModule m = dm_current_mandatory(); internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() { public void run() { try { AutoCloseable __1 = m.enter(); try { dm_doubleFieldSetterDialog(field, __); } finally { _close(__1); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n dm_doubleFieldSetterDialog(field, __);"; }}); } static void dm_stringFieldMenuItem(Container frame, final String field, final Object... __) { final DynModule m = dm_current_mandatory(); internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() { public void run() { try { AutoCloseable __1 = m.enter(); try { dm_stringFieldDialog(field, __); } finally { _close(__1); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n dm_stringFieldDialog(field, __);"; }}); } static ReliableSingleThread dm_rst(Runnable r) { return dm_rst(dm_current_mandatory(), r); } static ReliableSingleThread dm_rst(DynModule mod, Runnable r) { return dm_rst(mod, new ReliableSingleThread(r)); } static ReliableSingleThread dm_rst(DynModule mod, ReliableSingleThread rst) { rst.enter = dm_rEnter(mod); return rst; } static Q dm_startQ() { return dm_ownQ(startQ()); } static Q dm_startQ(String name) { return dm_ownQ(startQ(name)); } static JComponent dm_noVisualisation() { return setToolTip("Module has no visualization", jimage("#1101480")); } static String snippetTitle(String id) { return getSnippetTitle(id); } static String snippetTitle(long id) { return getSnippetTitle(id); } static Class mainClass() { return getMainClass(); } static Class mainClass(Object o) { return getMainClass(o); } static Map mapMinus(Map map, Object... keys) { if (empty(keys)) return map; Map m2 = cloneMap(map); for (Object key : keys) m2.remove(key); return m2; } static Set _registerTimer_list = newWeakHashSet(); static void _registerTimer_original(java.util.Timer timer) { _registerTimer_list.add(timer); } static void cleanMeUp__registerTimer() { cancelTimers(getAndClearList(_registerTimer_list)); } static Class _run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } static A syncPopFirst(List l) { if (empty(l)) return null; synchronized(l) { A a = first(l); l.remove(0); return a; } } static void cancelAndInterruptThread(Thread t) { if (t == null) return; cancelThread(t); t.interrupt(); } static Object _onAWTEnter_f; static AutoCloseable _onAWTEnter() { return (AutoCloseable) callF(_onAWTEnter_f); } static JDesktopPane mainDesktopPane_value; static JDesktopPane mainDesktopPane() { return mainDesktopPane_value; } static void interruptThread(Thread t) { if (t == null) return; t.interrupt(); URLConnection c = (URLConnection) (vm_generalSubMap("URLConnection per thread").get(t)); if (c != null) { try { print("Closing URLConnection of interrupted thread."); call(c, "disconnect"); } catch (Throwable __e) { _handleException(__e); }} } static void cancelTimer(javax.swing.Timer timer) { if (timer != null) timer.stop(); } static void cancelTimer(java.util.Timer timer) { if (timer != null) timer.cancel(); } static void cancelTimer(Object o) { if (o instanceof java.util.Timer) cancelTimer((java.util.Timer) o); else if (o instanceof javax.swing.Timer) cancelTimer((javax.swing.Timer) o); else if (o instanceof AutoCloseable) { try { ((AutoCloseable) o).close(); } catch (Throwable __e) { _handleException(__e); }} } static Method findMethod_cached(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { _MethodCache cache = callOpt_getCache(((Class) o)); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false)) return m; return null; } else { _MethodCache cache = callOpt_getCache(o.getClass()); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) if (findMethod_checkArgs(m, args, false)) return m; return null; } } catch (Exception __e) { throw rethrow(__e); } } static ExpiringMap2 mechList_raw_cache = new ExpiringMap2(10000).setMap(ciMap()); static Lock mechList_raw_lock = lock(); // timeout for loading static int mechList_raw_timeout = 60000; static String mechList_raw(String name) { try { Lock __0 = mechList_raw_lock; lock(__0); try { if (empty(name)) return ""; // get from cache String src = mechList_raw_cache.get(name); if (src != null) return src; // load & put in cache - TODO: make postPage honor this //temp tempSetThreadLocal(loadPage_forcedTimeout_byThread, mechList_raw_timeout); src = mechList_raw_fresh(name); if (src != null) mechList_raw_cache.put(name, src); return src; } finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } } static VF2 mechList_raw_listener = new VF2() { public void get(String msg, Object arg) { try { if (eq(msg, "mechChange") && arg instanceof String) { //print("Got change notification: " + arg); mechList_raw_cache.remove((String) arg); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(msg, 'mechChange) && arg instanceof S) {\r\n //print(\"Got change noti..."; }}; static void _onLoad_mechList_raw() { add(vm_busListeners_live(), mechList_raw_listener); } static void cleanMeUp_mechList_raw() { remove(vm_busListeners_live(), mechList_raw_listener); } static String assertPossibleGlobalID(String s) { if (!possibleGlobalID(s)) throw fail("Not an acceptable global ID: " + s); return s; } static char charPlus(char a, int b) { return (char) (((int) a) + b); } // better modulo that gives positive numbers always static int mod(int n, int m) { return (n % m + m) % m; } static long mod(long n, long m) { return (n % m + m) % m; } static BigInteger mod(BigInteger n, int m) { return n.mod(bigint(m)); } static double mod(double n, double m) { return (n % m + m) % m; } static String div(Object contents, Object... params) { return hfulltag("div", contents, params); } static BigInteger div(BigInteger a, BigInteger b) { return a.divide(b); } static BigInteger div(BigInteger a, int b) { return a.divide(bigint(b)); } 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); } } static A setAll(A o, Map fields) { if (fields == null) return o; for (String field : keys(fields)) set(o, field, fields.get(field)); return o; } static A setAll(A o, Object... values) { //values = expandParams(c.getClass(), values); failIfOddCount(values); for (int i = 0; i+1 < l(values); i += 2) { String field = (String) values[i]; Object value = values[i+1]; set(o, field, value); } return o; } static DynModule dm_current_mandatory() { return assertNotNull("No module set!", dm_currentModule()); } static AutoCloseable dm_vmBus_onMessage(final String msg, final VF1 onMessage) { return dm_ownResource(vmBus_onMessage(msg, onMessage)); } static AutoCloseable dm_vmBus_onMessage(final String msg, final IVF1 onMessage) { return dm_ownResource(vmBus_onMessage(msg, ivf1ToVF1(onMessage))); } static AutoCloseable dm_vmBus_onMessage(final String msg, final IVF2 onMessage) { return dm_ownResource(vmBus_onMessage(msg, ivf2ToVF2(onMessage))); } static AutoCloseable dm_vmBus_onMessage(String msg, final VF2 onMessage) { return dm_ownResource(vmBus_onMessage(msg, onMessage)); } static AutoCloseable dm_vmBus_onMessage(String msg, final VF3 onMessage) { return dm_ownResource(vmBus_onMessage(msg, onMessage)); } static AutoCloseable dm_vmBus_onMessage(String msg, Runnable onMessage) { return dm_ownResource(vmBus_onMessage(msg, onMessage)); } static List dropPunctuation3_keep = ll("*", "<", ">"); static Map dropPunctuation3_cache = defaultSizeMRUCache(); 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)) { // merge spacing and make sure it's not completely empty tok.set(i-1, or2(tok.get(i-1) + tok.get(i+1), " ")); tok.remove(i); tok.remove(i); i -= 2; } } return tok; } static String dropPunctuation3(String s) { return getOrCreate_f0(dropPunctuation3_cache, s, () -> join(dropPunctuation3(javaTokNoQuotes(s)))); } static boolean agiBlue_validPageName(String s) { s = trim(s); return nempty(s) && !containsNewLine(s); } static String agiBlue_lookupInSlice_pcall(String sliceID, String q, String... keys) { try { return agiBlue_lookupInSlice(sliceID, q, keys); } catch (Throwable __e) { return null; } } 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; } } static boolean regexpFind(String pat, String s) { return regexpFinds(pat, s); } static String discordTokenRegexp() { return "[MN][A-Za-z\\d]{23}\\.[\\w-]{6}\\.[\\w-]{27}"; } static SelfUser jda_selfUser(JDA jda) { return jda.getSelfUser(); } static String ymd() { return ymd(now()); } static String ymd(long now) { return year(now) + formatInt(month(now), 2) + formatInt(dayOfMonth(now), 2); } static String ymd(long now, TimeZone tz) { return year(now, tz) + formatInt(month(now, tz), 2) + formatInt(dayOfMonth(now, tz), 2); } static String hms() { return hms(now()); } static String hms(long time) { return new SimpleDateFormat("HHmmss").format(time); } static ZipOutputStream newZipOutputStream(String path) { return newZipOutputStream(new File(path)); } static ZipOutputStream newZipOutputStream(File zip) { try { return new ZipOutputStream(newFileOutputStream(zip)); } catch (Exception __e) { throw rethrow(__e); } } static void zip_addTextFile(ZipOutputStream outZip, String name, String text) { try { if (text == null) return; outZip.putNextEntry(new ZipEntry(name)); byte[] utf8 = toUtf8(text); outZip.write(utf8, 0, l(utf8)); } catch (Exception __e) { throw rethrow(__e); } } static int stdHash(Object a, String... fields) { if (a == null) return 0; int hash = getClassName(a).hashCode(); for (String field : fields) hash = boostHashCombine(hash, hashCode(getOpt(a, field))); return hash; } static String standard_toString(Object o) { if (o == null) return "null"; String name = shortClassName(o); Set fields = fieldNames(o); if (empty(fields)) return name; return name + "(" + joinWithComma(mapNonNulls(fields, field -> { Object value = get(o, field); if (value == null) return null; return field + "=" + str(value); })) + ")"; } static TreeSet treeSet() { return new TreeSet(); } static List splitAtDoubleArrow_tok; static List splitAtDoubleArrow_tok() { // initialize on demand to allow use in static initializers if (splitAtDoubleArrow_tok == null) splitAtDoubleArrow_tok = ll("=", "", ">"); return splitAtDoubleArrow_tok; } static List javaTokPlusBrackets(String s) { return tok_combineRoundOrCurlyBrackets_keep(javaTok(s)); } static BasicLogicRule curryLHS_BasicLogicRule(BasicLogicRule rule) { if (rule == null) return null; while (licensed()) { Object lhs = rule.lhs; if (lhs instanceof And) { Object a = ((And) lhs).a; Object b = ((And) lhs).b; BasicLogicRule r = rule; rule = new BasicLogicRule(a, curryLHS(new BasicLogicRule(b, rule.rhs))); rule.trail = r.trail; } else break; } return rule; } static boolean tok_isRoundBracketed(String s) { List tok = tok_combineRoundBrackets_keep(javaTok(s)); return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "(", ")"); } static List dropFirstThreeAndLastThree(List l) { return dropFirstAndLast(3, l); } static int countTokens(String s) { return l(javaTokC(s)); } static int countTokens(List tok) { return l(tok)/2; } static boolean isCurlyBraced(String s) { List tok = tok_combineCurlyBrackets_keep(javaTok(s)); return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}"); } static String tok_unCurlyBracket_keepSpaces(String s) { return isCurlyBraced(s) ? join(dropFirstTwoAndLastTwo(javaTok(s))) : s; } static int indent_default = 2; static String indent(int indent) { return repeat(' ', indent); } static String indent(int indent, String s) { return indent(repeat(' ', indent), s); } static String indent(String indent, String s) { return indent + s.replace("\n", "\n" + indent); } static String indent(String s) { return indent(indent_default, s); } static List indent(String indent, List lines) { List l = new ArrayList(); if (lines != null) for (String s : lines) l.add(indent + s); return l; } static String tok_javaDropCommentsFromWhitespace(String s) { int l = l(s), j = 0; StringBuilder buf = new StringBuilder(); while (j < l) { char c = s.charAt(j); char d = j+1 >= l ? '\0' : s.charAt(j+1); 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 { buf.append(c); ++j; } } return str(buf); } static TreeMap litCIMap(Object... x) { TreeMap map = caseInsensitiveMap(); litmap_impl(map, x); return map; } static Map similarEmptyMap(Map m) { if (m instanceof TreeMap) return new TreeMap(((TreeMap) m).comparator()); if (m instanceof LinkedHashMap) return new LinkedHashMap(); // default to a hash map return new HashMap(); } static String roundBracketIfMoreThanOneToken(String s) { return !tok_isRoundBracketed(s) && numberOfJavaTokens(s) > 1 ? roundBracket(s) : s; } static Map> javaTokWithAllBrackets_cached_cache = synchronizedMRUCache(defaultTokenizerCacheSize()); static List javaTokWithAllBrackets_cached(String s) { List tok = javaTokWithAllBrackets_cached_cache.get(s); if (tok == null) javaTokWithAllBrackets_cached_cache.put(s, tok = javaTokWithAllBrackets(s)); return tok; } static String[] drop(int n, String[] a) { n = Math.min(n, a.length); String[] b = new String[a.length-n]; System.arraycopy(a, n, b, 0, b.length); return b; } static Object[] drop(int n, Object[] a) { n = Math.min(n, a.length); Object[] b = new Object[a.length-n]; System.arraycopy(a, n, b, 0, b.length); return b; } static Map gazelle_zip_keepBrackets(String inputA, String inputB, Object... __) { Object tokenizer = optPar("tokenizer",__, "javaTokWithBrackets"); return gazelle_zipTwoTokenizationsToMap_keepBrackets( callTokenizer(tokenizer, inputA), callTokenizer(tokenizer, inputB)); } static boolean tok_isRoundOrCurlyBracketed(String s) { return isCurlyBraced(s) || tok_isRoundBracketed(s); } static boolean putAllStrictlyIC(Map map, Map adding) { return addMapToMapWithoutOverwritingIC(map, adding); } static boolean eqic_roundBracketed(String a, String b) { return eqic_roundBracketed_oneWay(a, b) || eqic_roundBracketed_oneWay(b, a); } static boolean eqic_roundBracketed_oneWay(String a, String b) { return l(a) == l(b)+2 && eqic(a, "(" + b + ")"); } static boolean strictPutIC(Map map, A key, String value) { if (!(map != null && key != null && value != null)) return true; String old = map.get(key); if (old == null) { map.put(key, value); return true; } return eqic(old, value); } static void miniChat(String text) { String slackTS = getSlackTS(); if (slackTS == null) { print("Skipping mini-chat post (not on slack): " + quote(text)); return; } Object mcBot = getBot("#1002433"); call(mcBot, "addToMiniChat", "dc" + slackTS, getProgramID(), text); } static List callF_all(Collection l, Object... args) { return map(l, f -> callF(f, args)); } static boolean eqGetOneOf(List l, int i, A... options) { return eqOneOf(get(l, i), options); } static void tokAppend(List tok, int i, String s) { tok.set(i, tok.get(i)+s); } static String autoUnindent(String s) { int n = getIndent(s); if (n == 0) return s; List l = toLines(s); for (int i = 0; i < l(l); i++) l.set(i, substring(l.get(i), n)); return fromLines(l); } static String withoutLeadingLinesEmptyAfterTrim(String s) { int lineStart = 0; while (licensed()) { int i = lineStart; while (isSpaceOrTab(charAt(s, i))) ++i; if (!isNewLine(charAt(s, i))) break; while (isNewLine(charAt(s, i))) ++i; lineStart = i; } return substring(s, lineStart); } static List dropFirstTwoAndLastThree(List l) { return dropFirstAndLast(2, 3, l); } static String tok_deCurlyOrRound(String s) { return tok_deRoundOrCurlyBracket(s); } static String secondCodeToken(List tok) { return get(tok, 3); } static String firstCodeToken(String s) { return firstJavaToken(s); } static String firstCodeToken(List tok) { return get(tok, 1); } static String lastCodeToken(String s) { return lastJavaToken(s); } static String lastCodeToken(List tok) { return get(tok, l(tok)-2); } static IterableIterator iota(final int n) { return new IterableIterator() { int i = 0; public boolean hasNext() { return i < n; } public Integer next() { return ++i; } }; } static List trimAll(Collection l) { List l2 = new ArrayList(); if (l != null) for (String s : l) l2.add(trim(s)); return l2; } /* input e.g.: if (a and b) bla; This will yield ("if (a\n and b)", " bla;") Note: doesn't support multi-line strings */ static List lines_honoringBrackets(String text) { List lines = lines(text); List out = new ArrayList(); int bracketLevel = 0; // how many open brackets int start = 0; // line where current block starts for (int i = 0; i < l(lines); i++) { List tok = javaTok(lines.get(i)); for (int j = 1; j < l(tok); j += 2) { String t = tok.get(j); if (eqOneOf(t, "(", "{", "[")) ++bracketLevel; else if (eqOneOf(t, ")", "}", "]")) --bracketLevel; } if (bracketLevel == 0) { out.add(lines_rtrim(subList(lines, start, i+1))); start = i+1; } } addIfNempty(out, lines_rtrim(subList(lines, start))); return out; } static Pair tok_splitAtDoubleArrow_pair(String s) { return splitAtDoubleArrow_pair(s); } static Pair tok_splitAtDoubleArrow_pair(List tok) { return splitAtDoubleArrow_pair(tok); } // e.g. in = "very $x", out = "$x" static void philosophyBot1_addSimplificationRule_withTrails(PhilosophyBot1 bot, String ruleIn, String ruleOut, String originalFact) { Set> replacements = (Set>) (bot.getExtension("simplification rules")); if (replacements == null) { // first time, register extension and set up transformer bot.addExtension("simplification rules", replacements = new HashSet()); Set> _replacements = replacements; bot.addTrailEnabledDeepTransformer(s -> { for (T3 p : _replacements) { String out = simpleRewriteWithDollarVars(p.a, p.b, s); if (out != null) return new WithTrail(litorderedmap("op" , "simplification rule", "p", p, "s", s, "out", out, "originalFact" , p.c), out); } return null; }); } // after that, just add new replacement pair to the list replacements.add(t3(ruleIn, ruleOut, originalFact)); } static List wrapArrayAsList(A[] a) { return a == null ? null : Arrays.asList(a); } static boolean isLetterOrDigitOrApostrophe(char c) { return Character.isLetterOrDigit(c) || c == '\''; } static TreeSet toCaseInsensitiveSet(Iterable c) { if (isCISet(c)) return (TreeSet) c; TreeSet set = caseInsensitiveSet(); addAll(set, c); return set; } static TreeSet toCaseInsensitiveSet(String... x) { TreeSet set = caseInsensitiveSet(); addAll(set, x); return set; } static CancelPoint newCancelPoint() { return new CancelPoint(); } static List callTokenizer(Object tokenizer, String s) { return (List) callF(tokenizer, s); } static String roundOpt(String s) { return roundBracketIfMoreThanOneToken(s); } static String curlyOpt(String s) { return curlyBraceOptIfMoreThanOneToken(s); } static String asciiHeading2(String title) { return asciiHeading(title) + "\n"; } static Set asSet(Object[] array) { HashSet set = new HashSet(); for (Object o : array) if (o != null) set.add(o); return set; } static Set asSet(String[] array) { TreeSet set = new TreeSet(); for (String o : array) if (o != null) set.add(o); return set; } static Set asSet(Iterable l) { if (l instanceof Set) return (Set) l; HashSet set = new HashSet(); for (A o : unnull(l)) if (o != null) set.add(o); return set; } static List instancesOf(Iterable i, Class c) { return collectInstances(i, c); } static List instancesOf(Class c, Iterable i) { return collectInstances(c, i); } static Set similarEmptySet(Iterable m) { if (m instanceof TreeSet) return new TreeSet(((TreeSet) m).comparator()); if (m instanceof LinkedHashSet) return new LinkedHashSet(); return new HashSet(); } static Set similarEmptySet(Map m) { if (m instanceof TreeMap) return new TreeSet(((TreeMap) m).comparator()); if (m instanceof LinkedHashMap) return new LinkedHashSet(); return new HashSet(); } static BufferedImage toBufferedImageOpt(Object o) { if (o instanceof BufferedImage) return (BufferedImage) o; if (o instanceof MakesBufferedImage) return ((MakesBufferedImage) o).getBufferedImage(); if (o instanceof File) if (isImageFile(((File) o))) return loadImage2(((File) o)); String c = getClassName(o); // Keep this because it also works on imported objects if (eqOneOf(c, "main$BWImage", "main$RGBImage")) return (BufferedImage) call(o, "getBufferedImage"); if (eq(c, "main$PNGFile")) return (BufferedImage) call(o, "getImage"); return null; } static IterableIterator> outerProductPairs(Collection lA, Collection lB) { return nestedIterator(lA, new F1>>() { public Iterator> get(A a) { try { return mapI(lB, b -> pair(a, b)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "mapI(lB, b -> pair(a, b))"; }}); } static IterableIterator> outerProductPairs(Collection lA) { return outerProductPairs(lA, lA); } static String optionalCurlyBrace(String s) { return isCurlyBraced(s) ? s : curlyBrace(s); } static double toDouble(Object o) { if (o instanceof Number) return ((Number) o).doubleValue(); if (o instanceof BigInteger) return ((BigInteger) o).doubleValue(); if (o instanceof String) return parseDouble(((String) o)); if (o == null) return 0.0; throw fail(o); } static List filterNempty(Collection c) { List l = new ArrayList(); for (String x : unnull(c)) if (nempty(x)) l.add(x); return l; } static int countWhere(Collection c, Object... data) { int n = 0; if (c != null) for (Object x : c) if (checkFields(x, data)) ++n; return n; } static A keyForValue(B value, Map map) { return reverseLookup(value, map); } static A keyForValue(Map map, B value) { return reverseLookup(map, value); } // fromKey = inclusive, toKey = exclusive static SortedMap subMap(SortedMap map, A fromKey, A toKey) { return map == null ? null : map.subMap(fromKey, toKey); } static void internalFrameTitlePopupMenuItem(JInternalFrame f, final String name, final Object action) { internalFrameTitlePopupMenu(f, new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, name, action) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, name, action)"; }}); } static void minimalFrameSize(Component c, int w, int h) { Container f = getPIFrame(c); if (f != null) setSize(f, max(w, getWidth(f)), max(h, getHeight(f))); } static String myFirewallIP() { return assertIPv4(loadPage(tb_mainServer() + "/tb-int/my-ip.php")); } 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; } static boolean addIfNotNull(Collection l, A a) { return a != null && l != null & l.add(a); } 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);"; }}); } static void dm_showModule(Object module) { Object stem = dm_getStem(module); if (stem != null/* && !dm_moduleIsPoppedOut(stem)*/) dm_callOS("showModule", stem); } static void dm_showModule() { dm_showModule(dm_current_mandatory_generic()); } 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; } static void dm_onFieldChange(String field, Runnable onChange) { dm_watchField(field, onChange); } static double toMinutes(long ms) { return ms/60000.0; } static A revalidate(final A c) { if (c == null || !c.isShowing()) return c; { swing(new Runnable() { public void run() { try { // magic combo to actually relayout and repaint c.revalidate(); c.repaint(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// magic combo to actually relayout and repaint\r\n c.revalidate();\r\n c.r..."; }}); } return c; } static void revalidate(JFrame f) { revalidate((Component) f); } static void revalidate(JInternalFrame f) { revalidate((Component) f); } static ActionListener actionListenerInNewThread(final Object runnable) { return actionListenerInNewThread(runnable, null); } static ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) { if (runnable instanceof ActionListener) return (ActionListener) runnable; return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { startThread("Action Listener", new Runnable() { public void run() { try { AutoCloseable __1 = holdInstance(instanceToHold); try { callF(runnable); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __1 = holdInstance(instanceToHold); try {\r\n callF(runnable..."; }}); } catch (Throwable __e) { messageBox(__e); }}}; } static Map humanizeFormLabel_replacements = litmap("id" , "ID", "md5" , "MD5"); static String humanizeFormLabel(String s) { if (containsSpace(s)) return s; return firstToUpper( joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID") ); } static JTextField jtextfield() { return jTextField(); } static JTextField jtextfield(String text) { return jTextField(text); } static JTextField jtextfield(Object o) { return jTextField(o); } static int showForm_defaultGap = 4; static int showForm_gapBetweenColumns = 10; static JPanel showFormTitled(final String title, final Object... _parts) { JDesktopPane desktop = mainDesktopPane(); if (desktop != null) return showInternalFrameFormTitled(desktop, title, _parts); return swing(new F0() { public JPanel get() { try { final Var frame = new Var(); JPanel panel = showForm_makePanel(false, _parts); frame.set(showForm_makeFrame(title, panel)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new Var frame;\r\n JPanel panel = showForm_makePanel(false, _p..."; }}); } static JPanel showForm_makePanel(Boolean internalFrame, Object... _parts) { List out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts)); return vstackWithSpacing(out, showForm_defaultGap); } static String stringOptPar(Object[] params, String name) { return (String) optPar(params, name); } static String gtt(JTextComponent c) { return getTextTrim(c); } static String gtt(JComboBox cb) { return getTextTrim(cb); } static A toolTip(A c, final Object toolTip) { return setToolTipText(c, toolTip); } static A toolTip(Object toolTip, A c) { return setToolTipText(toolTip, c); } // menuParams: text, Runnable, ... // also: position := 'left/'center/'right static JButton jPopDownButton(String text, final Object... menuParams) { return jbutton((empty(text) ? "" : text + " ") + unicode_downPointingTriangle(), new Runnable() { public void run() { try { JPopupMenu menu = new JPopupMenu(); int emptyCount = menu.getComponentCount(); String position = (String) (optPar_ignoreOddLength("position",menuParams)); // TODO: this fails when you include a separator without a following null fillJPopupMenu(menu, paramsWithout(menuParams, "position")); if (menu.getComponentCount() != emptyCount) { JButton btn = heldInstance(JButton.class); int x = 0; if (eq(position, "center")) x = (btn.getWidth()-getPreferredWidth(menu))/2; else if (eq(position, "right")) x = btn.getWidth()-getPreferredWidth(menu); menu.show(btn, x, btn.getHeight()); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new JPopupMenu menu;\r\n int emptyCount = menu.getComponentCount();\r\n Str..."; }}); } static void inputText(final String msg, final Object action) { inputText(msg, "", action); } // action: voidfunc(S) static void inputText(final String msg, final String defaultText, final Object action) { final Object threadInfo = _threadInfo(); swingLater(new Runnable() { public void run() { try { final JTextField tf = jtextfield(defaultText); String title = joinStrings(" | ", msg, programName()); JComponent form = showFormTitled(title, unnull(msg), tf, new Runnable() { public void run() { try { vmBus_send("inputtingText_OK", threadInfo, msg, tf); callF_thread(action, getTextTrim(tf)) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "vmBus_send(\"inputtingText_OK\", threadInfo, msg, tf);\r\n callF_thread(ac..."; }}); renameSubmitButton(form, "OK"); vmBus_send("inputtingText", threadInfo, msg, tf); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tf = jtextfield(defaultText);\r\n String title = joinString..."; }}); } static void inputText(String msg, String defaultText, IVF1 action) { inputText(msg, defaultText, (Object) action); } static void inputText(String msg, IVF1 action) { inputText(msg, (Object) action); } static String dm_moduleName() { return dm_moduleName(assertNotNull(dm_current_generic())); } static String dm_moduleName(Object module) { return (String) callOpt(dm_getStem(module), "moduleName"); } static File dm_structureExportDefaultFile(DynModule mod) { return javaxBackupDir("module-" + shortClassName(mod) + "-" + ymdMinusHms() + ".txt"); } static File saveTextFileWithInfoBox(File f, String text) { saveTextFile(f, text); fileSavedInfoBox(f); return f; } static String javaTokWordWrap(String s) { return javaTokWordWrap(120, s); } // TODO: complete trimming static String javaTokWordWrap(int cols, String s) { int col = 0; List tok = javaTok(s); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && col >= cols && !containsNewLine(t)) tok.set(i, t = rtrimSpaces(t) + "\n"); int idx = t.lastIndexOf('\n'); if (idx >= 0) col = l(t)-(idx+1); else col += l(t); } return join(tok); } static String dm_freshModuleStructureWithoutError(Object module) { dm_clearError(module); return dm_freshModuleStructure(module); } static File showFileChooserWithDefaultDir(String title, File defaultDir) { JFileChooser fc = new JFileChooser(); fc.setDialogTitle(title); fc.setCurrentDirectory(defaultDir); return execFileChooser(fc); } static File javaxBackupDir_dir; // can be set to work on different base dir static File javaxBackupDir() { return javaxBackupDir_dir != null ? javaxBackupDir_dir : new File(userHome(), "JavaX-Backup"); } static File javaxBackupDir(String sub) { return newFile(javaxBackupDir(), sub); } static JWindow infoBox(String text) { return infoMessage(text); } static JWindow infoBox(String text, double seconds) { return infoMessage(text, seconds); } static JWindow infoBox(Throwable e) { return infoMessage(e); } static void dm_replaceModuleWithStructure(Object mod, String struct) { setAll(dm_getStem(mod), "contentsDirty" , false, "oStruct" , struct); dm_reloadModule(mod); } static void dm_reloadMe() { dm_reloadModule(dm_currentModule()); } static JPanel jpanel(LayoutManager layout) { return swingNu(JPanel.class, layout); } static JPanel jpanel() { return swingNu(JPanel.class); } static JScrollPane setScrollPaneBackground(Color c, JScrollPane sp) { if (sp != null && c != null) { swing(new Runnable() { public void run() { try { sp.getViewport().setBackground(c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "sp.getViewport().setBackground(c);"; }}); } return sp; } 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);"; }}); } static A withTypeWriterFont(A c) { return setFont(c, typeWriterFont()); } static A swingNu(final Class c, final Object... args) { return swingConstruct(c, args); } static ThreadLocal componentPopupMenu_mouseEvent; static void componentPopupMenu_init() { { swing(new Runnable() { public void run() { try { if (componentPopupMenu_mouseEvent == null) componentPopupMenu_mouseEvent = (ThreadLocal) vm_generalMap_get("mouseEvent"); if (componentPopupMenu_mouseEvent == null) vm_generalMap_put("componentPopupMenu_mouseEvent" , componentPopupMenu_mouseEvent = new ThreadLocal()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (componentPopupMenu_mouseEvent == null)\r\n componentPopupMenu_mouseEve..."; }}); } } // menuMaker = voidfunc(JPopupMenu) static void componentPopupMenu(final JComponent component, final Object menuMaker) { if (component == null || menuMaker == null) return; { swing(new Runnable() { public void run() { try { Object adapter = componentPopupMenu_initForComponent(component); ((List) _get(adapter, "maker")).add(menuMaker); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object adapter = componentPopupMenu_initForComponent(component);\r\n ((List)..."; }}); } } static Object componentPopupMenu_initForComponent(final JComponent component) { return component == null ? null : swing(new F0() { public Object get() { try { componentPopupMenu_init(); Object adapter = findComponentPopupMenuListener_gen(component); if (adapter == null) { componentPopupMenu_Adapter a = new componentPopupMenu_Adapter(); component.addMouseListener(a); adapter = a; } return adapter; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "componentPopupMenu_init();\r\n O adapter = findComponentPopupMenuListener_ge..."; }}); } static class componentPopupMenu_Adapter extends MouseAdapter { List maker = new ArrayList(); boolean internalFrameLeftButtonMagic = false; Point pressedAt; public void mousePressed(MouseEvent e) { displayMenu(e); pressedAt = internalFrameLeftButtonMagic && e.getClickCount() == 1 && internalFrameActive(e.getComponent()) ? e.getLocationOnScreen() : null; } public void mouseReleased(MouseEvent e) { // TODO: show a little less often on left mouse click if (internalFrameLeftButtonMagic && eq(pressedAt, e.getLocationOnScreen())) displayMenu2(e); else displayMenu(e); } void displayMenu(MouseEvent e) { if (e.getSource() instanceof JInternalFrame) return; if (e.isPopupTrigger()) displayMenu2(e); } void displayMenu2(MouseEvent e) { JPopupMenu menu = new JPopupMenu(); int emptyCount = menu.getComponentCount(); AutoCloseable __1 = tempSetTL(componentPopupMenu_mouseEvent, e); try { for (Object menuMaker : maker) pcallF(menuMaker, menu); vmBus_send("showingPopupMenu", e.getComponent(), menu); // show menu if any items in it if (menu.getComponentCount() != emptyCount) menu.show(e.getComponent(), e.getX(), e.getY()); } finally { _close(__1); }} } static void addMenuItem(JPopupMenu menu, String text, Object action) { menu.add(jmenuItem(text, action)); } static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) { menu.add(menuItem); } static void addMenuItem(JMenu menu, String text, Object action) { menu.add(jmenuItem(text, action)); } static void addMenuItem(Menu menu, String text, Object action) { menu.add(menuItem(text, action)); } static void addMenuItem(JMenu menu, JMenuItem menuItem) { menu.add(menuItem); } static void clearStringBuffer_gen(Object buf) { if (buf != null) { call(buf, "setLength", 0); call(buf, "trimToSize"); } } static void swingEvery(JComponent component, long delay, Object r) { installTimer(component, delay, r); } static void swingEvery(JComponent component, long delay, long firstDelay, Object r) { installTimer(component, r, delay, firstDelay); } static void swingEvery(RootPaneContainer frame, long delay, Object r) { installTimer(frame, delay, r); } static void swingEvery(RootPaneContainer frame, long delay, long firstDelay, Object r) { installTimer(frame, delay, firstDelay, r); } static long toMS(double seconds) { return (long) (seconds*1000); } static void swingAndWait(Runnable r) { try { if (isAWTThread()) r.run(); else EventQueue.invokeAndWait(addThreadInfoToRunnable(r)); } catch (Exception __e) { throw rethrow(__e); } } static Object swingAndWait(final Object f) { if (isAWTThread()) return callF(f); else { final Var result = new Var(); swingAndWait(new Runnable() { public void run() { try { result.set(callF(f)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; }}); return result.get(); } } static void swingLater(long delay, final Object r) { javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r))); timer.setRepeats(false); timer.start(); } static void swingLater(Object r) { SwingUtilities.invokeLater(toRunnable(r)); } // first delay = delay static Timer installTimer(JComponent component, Object r, long delay) { return installTimer(component, r, delay, delay); } // first delay = delay static Timer installTimer(RootPaneContainer frame, long delay, Object r) { return installTimer(frame.getRootPane(), r, delay, delay); } // first delay = delay static Timer installTimer(JComponent component, long delay, Object r) { return installTimer(component, r, delay, delay); } static Timer installTimer(JComponent component, long delay, long firstDelay, Object r) { return installTimer(component, r, delay, firstDelay); } static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) { return installTimer(component, r, delay, firstDelay, true); } static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) { if (component == null) return null; return (Timer) swingAndWait(new F0() { public Object get() { try { final Var timer = new Var(); timer.set(new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { AutoCloseable __1 = tempActivity(r); try { try { if (!allPaused()) if (isFalse(callF(r))) cancelTimer(timer.get()); } catch (Throwable __e) { _handleException(__e); } } finally { _close(__1); }} catch (Throwable __e) { messageBox(__e); }}})); timer.get().setInitialDelay(toInt(firstDelay)); timer.get().setRepeats(repeats); bindTimerToComponent(timer.get(), component); return timer.get(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new Var timer;\r\n timer.set(new Timer(toInt(delay), actionList..."; }}); } static Timer installTimer(RootPaneContainer frame, long delay, long firstDelay, Object r) { return installTimer(frame.getRootPane(), delay, firstDelay, r); } static StringBuffer liveLocalPrintLog() { return local_log; } static Object swingCall(final Object o, final String method, final Object... args) { return swing(new F0() { public Object get() { try { return call(o, method, args); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret call(o, method, args);"; }}); } static Font getFont(JComponent c) { return c == null ? null : swing(new F0() { public Font get() { try { return c.getFont(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getFont();"; }}); } static int toInt_checked(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } static String strUnnull(Object o) { return o == null ? "" : str(o); } 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); } static List asSynchroList(Iterable l) { return syncList(cloneList(l)); } 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();"; }}); } static void raiseFlagAndDo(Flag flag, Runnable r) { if (flag.raise()) callF(r); } static void _handleException_addHandler(Object handler) { addIfNotThere(_handleException_onException, handler); } static A assertNull(A a) { assertTrue(a == null); return a; } static A assertNull(String msg, A a) { assertTrue(msg, a == null); return a; } static JInternalFrame getInternalFrame(final Object _o) { return _o == null ? null : swing(new F0() { public JInternalFrame get() { try { Object o = _o; if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof JInternalFrame) return (JInternalFrame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; }}); } static A internalFrameTitle(A c, final String title) { final JInternalFrame f = getInternalFrame(c); if (f != null) { swing(new Runnable() { public void run() { try { f.setTitle(unnull(title)); toolTip(getInternalFrameTitlePaneComponent(f), title); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.setTitle(unnull(title));\r\n toolTip(getInternalFrameTitlePaneComponent(f)..."; }}); } return c; } static A internalFrameTitle(String title, A c) { return internalFrameTitle(c, title); } static String internalFrameTitle(Component c) { final JInternalFrame f = getInternalFrame(c); return f == null ? null : swing(new F0() { public String get() { try { return f.getTitle(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret f.getTitle();"; }}); } static A frameTitle(A c, String title) { return setFrameTitle(c, title); } static A frameTitle(String title, A c) { return setFrameTitle(c, title); } static String frameTitle(Component c) { return getFrameTitle(c); } static JFrame getFrame(final Object _o) { return swing(new F0() { public JFrame get() { try { Object o = _o; if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof JFrame) return (JFrame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; }}); } static Set _registerAutoCloseable_set = synchroHashSet(); static void _registerAutoCloseable(AutoCloseable c) { addIfNotNull(_registerAutoCloseable_set, c); } static void cleanMeUp__registerAutoCloseable() { closeAutoCloseables(getAndClearList(_registerAutoCloseable_set)); } static A callFInRealOrMyMC(Object realm, F0 f) { return f == null ? null : f.get(); } static B callFInRealOrMyMC(Object realm, F1 f, A a) { return f == null ? null : f.get(a); } static C callFInRealOrMyMC(Object realm, F2 f, A a, B b) { return f == null ? null : f.get(a, b); } static void callFInRealOrMyMC(Object realm, VF1 f, A a) { if (f != null) f.get(a); } static Object callFInRealOrMyMC(Object realm, Object f, Object... args) { if (f instanceof String) { Class mc = getMainClass(realm); if (hasMethod(mc, ((String) f), args)) return call(mc, ((String) f), args); } return callF(f, args); } static A shallowCloneToClass(Class c, Object o) { if (o == null) return null; A a = nuInstance(c); copyFields(o, a); return a; } static Method findMethod_precise_onTypes(Object o, String method, Class... argTypes) { try { if (o instanceof Class) { _MethodCache cache = callOpt_getCache(((Class) o)); List methods = cache.cache.get(method); Lowest best = new Lowest(); if (methods != null) for (Method m : methods) { { if (!(isStaticMethod(m))) continue; } int score = methodApplicabilityScore_onTypes(m, argTypes); if (score < Integer.MAX_VALUE) { /*if (preciseCall_debug) print("Method score: " + m + " " + score);*/ best.put(m, score); } } return best.get(); } if (o == null) return null; _MethodCache cache = callOpt_getCache(o.getClass()); List methods = cache.cache.get(method); Lowest best = new Lowest(); if (methods != null) for (Method m : methods) { int score = methodApplicabilityScore_onTypes(m, argTypes); if (score < Integer.MAX_VALUE) best.put(m, score); } return best.get(); } catch (Exception __e) { throw rethrow(__e); } } static void dm_onTopInput(final VF1 r) { final DynModule m = dm_current_mandatory(); dm_ownResource(vmBus_onMessage("topInput", new VF1() { public void get(final String s) { try { m.enter(); callF(r, s) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.enter();\r\n callF(r, s)"; }})); } static void dm_onTopInput(final Runnable r) { final DynModule m = dm_current_mandatory(); dm_ownResource(vmBus_onMessage("topInput", new VF1() { public void get(final String s) { try { m.enter(); callF(r) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.enter();\r\n callF(r)"; }})); } static A foldl(F2 f, A seed, Iterable l) { A a = seed; if (l != null) for(B b : l) a = callF(f, a, b); return a; } static 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; } 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; } static ChangeListener changeListener(final Object r) { return new ChangeListener() { public void stateChanged(ChangeEvent e) { pcallF(r); } }; } static ItemListener itemListener(final Object r) { return new ItemListener() { public void itemStateChanged(ItemEvent e) { pcallF(r); } }; } static JTextField textFieldFromComboBox(JComboBox cb) { return (JTextField) cb.getEditor().getEditorComponent(); } static JComboBox onSelectedItem(final JComboBox cb, final VF1 f) { addActionListener(cb, new Runnable() { public void run() { try { pcallF(f, selectedItem(cb)) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(f, selectedItem(cb))"; }}); return cb; } // not a very good one static boolean instanceOf(Object o, String className) { if (o == null) return false; String c = o.getClass().getName(); return eq(c, className) || eq(c, "main$" + className); } // better static boolean instanceOf(Object o, Class c) { if (c == null) return false; return c.isInstance(o); } static boolean instanceOf(Class c, Object o) { return instanceOf(o, c); } static AbstractAction abstractAction(String name, final Object runnable) { return new AbstractAction(name) { public void actionPerformed(ActionEvent evt) { pcallF(runnable); } }; } static void callAction(Action a) { if (a != null) a.actionPerformed(null); } static Field getField(Object o, String field) { if (o == null) return null; return setOpt_findField(_getClass(o), field); } // menuMaker = voidfunc(JPopupMenu) static void internalFrameTitlePopupMenu(final JInternalFrame f, final Object... params) { { swing(new Runnable() { public void run() { try { Object menuMaker; if (l(params) == 1 && !(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"))); } // Also add to the frame so we can show the items e.g. in a JFrame menu componentPopupMenu(f, menuMaker); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object menuMaker;\r\n if (l(params) == 1 && !(params[0] instanceof JMenu))\r\n..."; }}); } } // r : runnable or voidfunc(bool) static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) { final JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked); addActionListener(mi, new Runnable() { public void run() { try { callF(r, isChecked(mi)) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(r, isChecked(mi))"; }}); return mi; } static A _get(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } static Object _get(Object o, String field) { return get(o, field); } static Object _get(String field, Object o) { return get(o, field); } static A _get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } static void dm_doubleFieldSetterDialog(String field, Object... __) { final DynModule m = dm_current_mandatory(); final String humanized = humanizeFormLabel(field); final JTextField tf = jtextfield(get(m, field)); showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() { public void run() { try { m.setField(field, parseDouble(gtt(tf))); callF(optPar(__, "onSet")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, parseDouble(gtt(tf)));\r\n callF(optPar(__, \"onSet\"));"; }}); } static F0 dm_rEnter(final DynModule mod) { return mod == null ? null : new F0() { public AutoCloseable get() { try { return mod.enter(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret mod.enter();"; }}; } static Q dm_ownQ(Q q) { q.rst.enter = dm_rEnter(dm_current_mandatory()); dm_ownResource(q); return q; } static Q startQ() { return new Q(); } static Q startQ(String name) { return new Q(name); } static A setToolTip(A c, Object toolTip) { return setToolTipText(c, toolTip); } static A setToolTip(Object toolTip, A c) { return setToolTipText(c, toolTip); } static void setToolTip(TrayIcon trayIcon, String toolTip) { setTrayIconToolTip(trayIcon, toolTip); } static JLabel jimage(Image img) { return jImageLabel(img); } static JLabel jimage(String imageID) { return jImageLabel(imageID); } static Set newWeakHashSet() { return synchroWeakHashSet(); } static void cancelTimers(Collection timers) { for (Object timer : timers) cancelTimer(timer); } static void cancelThread(Thread t) { if (t == null) return; ping(); /*O mc = getWeakRef((WeakReference) vm_generalWeakSubMap("thread2mc").get(t)); ifdef cancelThread_verbose print("cancelThread: mc=" + mc); endifdef if (mc != null) { Map ping_actions = cast get(mc, 'ping_actions); synchronized(ping_actions) { ping_actions.put(t, "cancelled"); set(mc, ping_anyActions := true); } } else*/ synchronized(ping_actions) { ping_actions.put(t, "cancelled"); ping_anyActions = true; } } static String mechList_raw_fresh(String name) { return mechList_opt_raw_fresh(name); } static boolean possibleGlobalID(String s) { return l(s) == globalIDLength() && allLowerCaseCharacters(s); } static String hfulltag(String tag) { return hfulltag(tag, ""); } static String hfulltag(String tag, Object contents, Object... params) { return hopeningTag(tag, params) + str(contents) + ""; } 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); } } // If you change this, also change DiskSnippetCache_fileToLibID static File DiskSnippetCache_file(long snippetID) { return new File(getGlobalCache(), "data_" + snippetID + ".jar"); } // Data files are immutable, use centralized cache 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); } 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(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID)); print("Loading library: " + hideCredentials(url)); data = loadBinaryPage(url.openConnection()); } print("Bytes loaded: " + data.length); } catch (FileNotFoundException e) { throw new IOException("Binary snippet #" + snippetID + " not found or not public"); } return data; } static 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(tb_mainServer() + "/blobs/" + psI(snippetID))); print(e); print("Trying other server: " + hideCredentials(url)); loadBinaryPageToFile(openConnection(url), f); print("Got bytes: " + fileSize(f)); } // TODO: check if we hit the "LOADING" message if (fileSize(f) == 0) throw fail(); System.err.println("Bytes loaded: " + fileSize(f)); } catch (Throwable e) { //printStackTrace(e); errors.add(e); throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors)); } return f; } catch (Exception __e) { throw rethrow(__e); } } static void failIfOddCount(Object... list) { if (odd(l(list))) throw fail("Odd list size: " + list); } static A dm_ownResource(A resource) { dm_currentModuleMandatory().ownResource(resource); return resource; } 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()); // We're technically violating the one-synchronized-object-per-thread rule, // but it should be OK here. // TODO: remove empty sets from map 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)"; }}); } } 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));"; }}); } static AutoCloseable vmBus_onMessage(String msg, final IVF2 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));"; }}); } static AutoCloseable vmBus_onMessage(String msg, final VF3 onMessage) { return vmBus_onMessage(msg, new VF1() { public void get(Object[] o) { try { callF(onMessage, first(o), second(o), third(o)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, first(o), second(o), third(o));"; }}); } static AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) { return vmBus_onMessage(msg, runnableToVF1(onMessage)); } static VF1 ivf1ToVF1(IVF1 f) { return f == null ? null : new VF1() { public void get(A a) { try { f.get(a) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.get(a)"; }}; } static VF2 ivf2ToVF2(IVF2 f) { return f == null ? null : new VF2() { public void get(A a, B b) { try { f.get(a, b) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.get(a, b)"; }}; } static Map defaultSizeMRUCache() { return mruCache(defaultStringTransformerCacheSize()); } 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; } 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; } static List javaTokNoQuotes(String s) { return quotelessJavaTok(s); } static String agiBlue_lookupInSlice(String sliceID, String q, String... keys) { return first((List) loadJSONPage(printHidingCredentials(agiBlue_linkForPhrase(q, paramsPlus(paramsWithSameKey("get", keys), "slice" , sliceID))))); } static ThreadLocal>> agiBlue_postInSlice_queue = new ThreadLocal(); 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)); } static boolean regexpFinds(String pat, String s) { return regexp(pat, s).find(); } static boolean regexpFinds(Pattern pat, String s) { return regexp(pat, s).find(); } static int year() { return localYear(); } static int year(long now) { return localYear(now); } static int year(long now, TimeZone tz) { return parseInt(simpleDateFormat("y", tz).format(now)); } static String formatInt(int i, int digits) { return padLeft(str(i), '0', digits); } static String formatInt(long l, int digits) { return padLeft(str(l), '0', digits); } static int month() { return localMonth(); } static int month(long now) { return localMonth(now); } static int month(long now, TimeZone tz) { return parseInt(simpleDateFormat("M", tz).format(now)); } static int dayOfMonth() { return localDayOfMonth(); } static int dayOfMonth(long now) { return localDayOfMonth(now); } static int dayOfMonth(long now, TimeZone tz) { return parseInt(simpleDateFormat("d", tz).format(now)); } static int hashCode(Object a) { return a == null ? 0 : a.hashCode(); } static Set fieldNames(Object o) { return allFields(o); } static List mapNonNulls(Iterable l, Object f) { return mapNonNulls(f, l); } static List mapNonNulls(Object f, Iterable l) { List x = new ArrayList(); if (l != null) for (Object o : l) addIfNotNull(x, callF(f, o)); return x; } static List mapNonNulls(Object f, Object[] l) { List x = new ArrayList(); if (l != null) for (Object o : l) addIfNotNull(x, callF(f, o)); return x; } static List mapNonNulls(Iterable l, F1 f) { return mapNonNulls(f, l); } static List mapNonNulls(F1 f, Iterable l) { List x = new ArrayList(); if (l != null) for (Object o : l) addIfNotNull(x, callF(f, o)); return x; } static List mapNonNulls(A[] l, IF1 f) { return mapNonNulls(f, l); } static List mapNonNulls(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : l) addIfNotNull(x, f.get(o)); return x; } static List mapNonNulls(IF1 f, Iterable l) { return mapNonNulls(l, f); } static List tok_combineRoundBrackets_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 = findEndOfBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j-1; } else l.add(t); } return l; } static boolean startsWithAndEndsWith(String s, String prefix, String suffix) { return startsWith(s, prefix) && endsWith(s, suffix); } 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; } static List dropFirstTwoAndLastTwo(List l) { return dropFirstAndLast(2, l); } static int numberOfJavaTokens(String s) { return l(javaTokC(s)); } static String roundBracket(String s) { return "(" + s + ")"; } static List javaTokWithAllBrackets(String s) { return javaTokPlusBrackets2(s); } static Map gazelle_zipTwoTokenizationsToMap_keepBrackets(List tokA, List tokB) { return ciMapWithoutKeysEqualToValues(zipTwoTokenizationsToCIMap_strict(tokA, tokB)); } static boolean addMapToMapWithoutOverwritingIC(Map map, Map adding) { if (!canPutAllStrictlyIC(map, adding)) return false; { final Map __0 = unnull(adding); for (A key : keys( __0)) { String value = __0.get(key); strictPutIC(map, key, value); }} return true; } static String getSlackTS() { return (String) callOpt(getMainBot(), "getSlackTS"); } static Object getBot(String botID) { return callOpt(getMainBot(), "getBot", botID); } static int getIndent(String s) { int n = Integer.MAX_VALUE; for (String l : toLines(s)) n = min(n, getIndentOfLine(l)); return n; } static boolean isSpaceOrTab(char c) { return c == ' ' || c == '\t'; } static boolean isNewLine(char c) { return c == '\r' || c == '\n'; } static String lastJavaToken(String s) { return last(javaTokC(s)); } static Pair splitAtDoubleArrow_pair(String s) { return splitAtDoubleArrow_pair(javaTokWithBrackets(s)); } static Pair splitAtDoubleArrow_pair(List tok) { return listToPair(splitAtDoubleArrow(tok)); } static String simpleRewriteWithDollarVars(String inPat, String outPat, String s) { Map map = matchDollarVarsIC_withBrackets(inPat, s); return map == null ? null : replaceVars_optRound2(outPat, map); } static String curlyBraceOptIfMoreThanOneToken(String s) { return !isCurlyBraced(s) && moreThanOneToken(s) ? curlyBrace(s) : s; } static String asciiHeading(String title) { return "\n" + title + "\n" + rep(l(title), '-'); } static List collectInstances(Iterable i, Class c) { List l = new ArrayList(); if (i == null) return l; c = primitiveToBoxedTypeOpt(c); for (Object o : i) if (isInstance(c, o)) l.add(o); return l; } static List collectInstances(Class c, Iterable i) { return collectInstances(i, c); } static boolean isImageFile(File f) { return isImageFileName(fileName(f)); } // TODO: clean up these type signatures? static > IterableIterator nestedIterator(final Iterable c, final F1 makeInnerIterator) { return nestedIterator(iterator(c), makeInnerIterator); } static > IterableIterator nestedIterator(Collection c, final IF1 makeInnerIterator) { return nestedIterator(iterator(c), makeInnerIterator); } static > IterableIterator nestedIterator(Iterator it1, IF1 makeInnerIterator) { return nestedIterator(it1, toF1(makeInnerIterator)); } static > IterableIterator nestedIterator(final Iterator it1, final F1 makeInnerIterator) { if (it1 == null || !it1.hasNext()) return emptyIterableIterator(); return iff(new F0() { A a; Iterator innerIterator; { nextOuter(); } void nextOuter() { a = it1.next(); innerIterator = makeInnerIterator.get(a); } public Object get() { while (true) { ping(); if (innerIterator != null && innerIterator.hasNext()) return innerIterator.next(); if (!it1.hasNext()) return endMarker(); nextOuter(); } } }); } static > IterableIterator nestedIterator(IF1 makeInnerIterator, Iterator it1) { return nestedIterator(it1, makeInnerIterator); } static > IterableIterator nestedIterator(IF1 makeInnerIterator, Collection l) { return nestedIterator(l, makeInnerIterator); } static class mapI_It extends IterableIterator { Object f; Iterator i; mapI_It() {} mapI_It(Object f, Iterator i) { this.i = i; this.f = f;} public boolean hasNext() { return i.hasNext(); } public Object next() { return callF(f, i.next()); } public String toString() { return formatFunctionCall("mapI", f, i); } } // apply a function to an iterator static IterableIterator mapI(final Object f, final Iterator i) { return new mapI_It(f, i); } static IterableIterator mapI(IterableIterator i, Object f) { return mapI((Iterator) i, f); } static IterableIterator mapI(Object f, IterableIterator i) { return mapI((Iterator) i, f); } static IterableIterator mapI(Iterator i, Object f) { return mapI(f, i); } static IterableIterator mapI(Iterable i, IF1 f) { return mapI(i, (Object) f); } static IterableIterator mapI(Iterator i, IF1 f) { return mapI(f, i); } static IterableIterator mapI(IterableIterator i, IF1 f) { return mapI((Iterator) i, f); } static IterableIterator mapI(IF1 f, Iterable i) { return mapI(i, (Object) f); } static IterableIterator mapI(Iterable i, Object f) { return mapI(f, i.iterator()); } static IterableIterator mapI(Object f, Iterable i) { return mapI(i, f); } static String curlyBrace(String s) { return "{" + s + "}"; } static A reverseLookup(B value, Map map) { return reverseLookup(map, value); } static A reverseLookup(Map map, B value) { if (map != null && value != null) for (A key : map.keySet()) if (eq(map.get(key), value)) return key; return null; } static Container getPIFrame(Component c) { return (Container) getPossiblyInternalFrame(c); } static A setSize(final A c, final int w, final int h) { if (c != null) { swing(new Runnable() { public void run() { try { c.setSize(w, h); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.setSize(w, h);"; }}); } return c; } static void setSize(Component c, Dimension d) { setSize(c, d.width, d.height); } static String assertIPv4(String s) { assertTrue(s, isIPv4(s)); return s; } static Matcher regexp(String pat, String s) { return regexp(compileRegexp(pat), unnull(s)); } static Matcher regexp(java.util.regex.Pattern pat, String s) { return pat.matcher(unnull(s)); } static java.util.regex.Pattern regexp(String pat) { return compileRegexp(pat); } static Object dm_mod(Object moduleOrID) { return dm_getModule(moduleOrID); } static boolean shortClassNameIs(Object o, String name) { return eq(shortClassName(o), name); } static boolean shortClassNameIs(String name, Object o) { return shortClassNameIs(o, name); } static ThreadLocal> holdInstance_l = new ThreadLocal(); static AutoCloseable holdInstance(Object o) { if (o == null) return null; listThreadLocalAdd(holdInstance_l, o); return new AutoCloseable() { public void close() { listThreadLocalPopLast(holdInstance_l); } }; } static void messageBox(final String msg) { if (headless()) print(msg); else { swing(new Runnable() { public void run() { try { JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES..."; }}); } } static void messageBox(Throwable e) { //showConsole(); printStackTrace(e); messageBox(hideCredentials(innerException2(e))); } static boolean containsSpace(String s) { return containsSpaces(s); } static String firstToUpper(String s) { if (empty(s)) return s; return Character.toUpperCase(s.charAt(0)) + s.substring(1); } static List replaceElementsUsingMap(Iterable l, final Map map) { return map(l, new F1() { public A get(A a) { try { return getOrKeep(map, a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getOrKeep(map, a)"; }}); } static List splitCamelCase(String s) { return ai_splitCamelCase(s); } static JTextField jTextField() { return jTextField(""); } static JTextField jTextField(final String text) { return swing(new F0() { public JTextField get() { try { JTextField tf = new JTextField(unnull(text)); standardTextFieldPopupMenu(tf); jenableUndoRedo(tf); tf.selectAll(); return tf; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JTextField tf = new JTextField(unnull(text));\r\n standardTextFieldPopupMenu..."; }}); } static JTextField jTextField(Object o) { return jTextField(strOrEmpty(o)); } static JPanel showInternalFrameFormTitled(final JDesktopPane desktop, final String title, final Object... _parts) { JPanel panel = showForm_makePanel(true, _parts); showForm_makeInternalFrame(desktop, title, panel); return panel; } static JFrame showForm_makeFrame(String title, JPanel panel) { return handleEscapeKey(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400)); } static List showForm_arrange1(List> l) { int minW = showForm_leftWidth(l); List out = new ArrayList(); for (List row : l) out.add(westAndCenter(withRightMargin(showForm_gapBetweenColumns, jMinWidth(minW, first(row))), second(row))); return out; } static List> showForm_makeComponents(final Boolean internalFrame, Object... _parts) { List> l = new ArrayList(); List parts = asList(_parts); JButton submitButton = null; for (int i = 0; i < l(parts); i++) { final Object o = parts.get(i), next = get(parts, i+1); if (o instanceof String && next instanceof Component) setComponentID((Component) next, (String) o); if (o instanceof Component || o instanceof String || next instanceof Component) { // smartAdd accepts strings l.add(mapLL("wrapForSmartAdd", o == null ? new JPanel() : o instanceof String ? humanizeFormLabel((String) o) : o, next)); if (next instanceof JButton && submitButton == null) submitButton = (JButton) next; i++; } else if (isRunnable(o)) l.add(mapLL("wrapForSmartAdd",null, submitButton = jbutton(showFormSubmitButtonName(), new Runnable() { public void run() { try { Object result = call(o); if (neq(Boolean.FALSE, result)) { if (isTrue(internalFrame)) disposeInternalFrame(heldInstance(JButton.class)); else if (isFalse(internalFrame)) disposeFrame(heldInstance(JButton.class)); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object result = call(o);\r\n if (neq(Boolean.FALSE, result)) {\r\n ..."; }}))); else print("showForm: Unknown element type: " + getClassName(o)); } if (submitButton != null) { final JButton _submitButton = submitButton; onEnterInAllTextFields(concatLists(l), new Runnable() { public void run() { try { clickButton(_submitButton) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "clickButton(_submitButton)"; }}); } // massage labels for (List row : l) { JComponent left = first(row); if (left instanceof JLabel) makeBold((JLabel) left).setVerticalAlignment(JLabel.TOP); } return l; } static int vstackWithSpacing_default = 10; static JPanel vstackWithSpacing(final List parts) { return vstackWithSpacing(parts, vstackWithSpacing_default); } static JPanel vstackWithSpacing(final List parts, final int spacing) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.insets = new Insets(spacing/2, 0, spacing/2, 0); // well... smartAddWithLayout(panel, gbc, toObjectArray(nonNulls(parts))); //gbc = (GridBagConstraints) gbc.clone(); //gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 1; gbc.insets = new Insets(0, 0, 0, 0); panel.add(jrigid(), gbc); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new GridBagLayout);\r\n new GridBagConstraints gbc..."; }}); } static JPanel vstackWithSpacing(Component... parts) { return vstackWithSpacing(asList(parts), vstackWithSpacing_default); } static JPanel vstackWithSpacing(int spacing, Component... parts) { return vstackWithSpacing(asList(parts), spacing); } static String getTextTrim(JTextComponent c) { return trim(getText(c)); } // tested for editable combo box - returns the contents of text field static String getTextTrim(JComboBox cb) { return trim(getText(cb)); } static String getTextTrim(JComponent c) { if (c instanceof JLabel) return trim(((JLabel) c).getText()); if (c instanceof JComboBox) return getTextTrim((JComboBox) c); return getTextTrim((JTextComponent) c); } static A setToolTipText(final A c, final Object toolTip) { if (c == null) return null; { swing(new Runnable() { public void run() { try { String s = nullIfEmpty(str(toolTip)); if (neq(s, c.getToolTipText())) c.setToolTipText(s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ..."; }}); } return c; } static A setToolTipText(Object toolTip, A c) { return setToolTipText(c, toolTip); } static JButton jbutton(String text, Object action) { return newButton(text, action); } // button without action static JButton jbutton(String text) { return newButton(text, null); } /*static JButton jbutton(BufferedImage img, O action) { ret setButtonImage(img, jbutton("", action)); }*/ static JButton jbutton(Action action) { return swingNu(JButton.class, action); } static String unicode_downPointingTriangle() { return charToString(0x25BC); } // now also takes a map as single array entry static A optPar_ignoreOddLength(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; } for (int i = 0; i+1 < l(opt); i += 2) if (eq(opt[i], name)) return (A) opt[i+1]; return defaultValue; } static Object optPar_ignoreOddLength(Object[] opt, String name) { return optPar_ignoreOddLength(opt, name, null); } static Object optPar_ignoreOddLength(String name, Object[] params) { return optPar_ignoreOddLength(params, name); } 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 IVF1) callF(o, m); else if (o instanceof List) fillJPopupMenu(m, asArray((List) o)); else if (isMenuSeparatorIndicator(o)) m.addSeparator(); else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) { final LiveValue lv = (LiveValue) o; final JMenuItem mi = jmenuItem("", y); bindLiveValueListenerToComponent(mi, lv, new Runnable() { public void run() { try { String s = lv.get(); if (isCurlyBracketed(s)) { setEnabled(mi, false); s = unCurlyBracket(s); } else setEnabled(mi, true); setText(mi, s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = lv.get();\r\n if (isCurlyBracketed(s)) {\r\n setEnable..."; }}); m.add(mi); } else if (o instanceof String && isRunnableX(y)) { m.add(jmenuItem((String) o, y)); ++i; } else if (o instanceof JMenuItem) m.add((JMenuItem) o); // "call" might use wrong method else if (o instanceof String || o instanceof Action || o instanceof Component) call(m, "add", o); else if (o != null) print("Unknown menu item: " + o); } } static Object[] paramsWithout(Object[] a1, Object... keys) { if (l(a1) == 1 && a1[0] instanceof Map) return new Object[] { mapMinus((Map) a1[0], keys) }; Set set = lithashset(keys); List l = new ArrayList(); int n = l(a1); for (int i = 0; i < n; i += 2) if (i == n-1) l.add(a1[i]); else if (!set.contains(a1[i])) { l.add(a1[i]); l.add(a1[i+1]); } return toObjectArray(l); } static A heldInstance(Class c) { List l = holdInstance_l.get(); for (int i = l(l)-1; i >= 0; i--) { Object o = l.get(i); if (isInstanceOf(o, c)) return (A) o; } throw fail("No instance of " + className(c) + " held"); } static int getPreferredWidth(Component c) { return preferredWidth(c); } static String programName() { return getProgramName(); } static void callF_thread(final Object f, final Object... args) { if (f != null) { startThread(new Runnable() { public void run() { try { callF(f, args); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(f, args);"; }}); } } static A renameSubmitButton(A form, String newName) { renameButton(form, showFormSubmitButtonName(), newName); return form; } static A renameSubmitButton(String newName, A form) { return renameSubmitButton(form, newName); } static String ymdMinusHms() { return ymd_minus_hms(); } static void fileSavedInfoBox(File f) { infoBox("Saved " + fileInfo(f)); } public static String rtrimSpaces(String s) { if (s == null) return null; int i = s.length(); while (i > 0 && " \t".indexOf(s.charAt(i-1)) >= 0) --i; return i < s.length() ? s.substring(0, i) : s; } static void dm_clearError(Object mod) { dm_rcall("clearError",mod); } static String dm_freshModuleStructure(Object module) { dm_persistModule(module); return dm_getStructure(module); } static String dm_freshModuleStructure() { return dm_freshModuleStructure(dm_current_generic()); } static File execFileChooser(JFileChooser fileChooser) { return fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ? fileChooser.getSelectedFile() : null; } static boolean infoMessage_alwaysOnTop = true; static double infoMessage_defaultTime = 5.0; // automatically switches to AWT thread for you static JWindow infoMessage(String text) { return infoMessage(text, infoMessage_defaultTime); } static JWindow infoMessage(final String text, final double seconds) { printHidingCredentials(text); return infoMessage_noprint(text, seconds); } static JWindow infoMessage_noprint(String text) { return infoMessage_noprint(text, infoMessage_defaultTime); } static JWindow infoMessage_noprint(final String _text, final double seconds) { final String text = hideCredentials(_text); if (empty(text)) return null; logQuotedWithDate(infoBoxesLogFile(), text); if (isHeadless()) return null; return (JWindow) swingAndWait(new F0() { public Object get() { try { final JWindow window = showWindow(infoMessage_makePanel(text)); window.setSize(300, 150); moveToTopRightCorner(window); if (infoMessage_alwaysOnTop) window.setAlwaysOnTop(true); if (vmBus_noObjections("shouldShowInfoBox",window, text)) window.setVisible(true); if (seconds != 0) disposeWindowAfter(iround(seconds*1000), window); return window; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JWindow window = showWindow(infoMessage_makePanel(text));\r\n window.s..."; }}); } static JWindow infoMessage(Throwable e) { //showConsole(); printStackTrace(e); return infoMessage(exceptionToStringShort(e)); } static A setFont(final Font font, final A a) { if (a != null) { swing(new Runnable() { public void run() { try { a.setFont(font); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setFont(font);"; }}); } return a; } static A setFont(A a, Font font) { return setFont(font, a); } static A setFont(final String fontID, float fontSize, final A a) { return setFont(loadFont_cached(fontID, fontSize), a); } static Font typeWriterFont() { return typeWriterFont(iround(14*getSwingFontScale())); } static Font typeWriterFont(int size) { return new Font("Courier", Font.PLAIN, size); } 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);"; }}); } static Object findComponentPopupMenuListener_gen(final JComponent c) { return c == null ? null : swing(new F0() { public Object get() { try { return firstWithClassShortNamed("componentPopupMenu_Adapter", c.getMouseListeners()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret firstWithClassShortNamed('componentPopupMenu_Adapter, c.getMouseListeners..."; }}); } static boolean internalFrameActive(Component c) { final JInternalFrame f = getInternalFrame(c); return f != null && swing(new F0() { public Boolean get() { try { return f.isSelected(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret f.isSelected();"; }}); } static boolean jmenuItem_newThreads = false; static JMenuItem jmenuItem(final String text) { return jMenuItem(text, null); } 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..."; }}); } static MenuItem menuItem(String text, final Object r) { MenuItem mi = new MenuItem(text); mi.addActionListener(actionListener(r)); return mi; } static Runnable addThreadInfoToRunnable(final Object r) { final Object info = _threadInfo(); return info == null ? asRunnable(r) : new Runnable() { public void run() { try { _inheritThreadInfo(info); callF(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_inheritThreadInfo(info); callF(r);"; }}; } static ActionListener actionListener(final Object runnable) { return actionListener(runnable, null); } static ActionListener actionListener(final Object runnable, final Object instanceToHold) { if (runnable instanceof ActionListener) return (ActionListener) runnable; final Object info = _threadInfo(); return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { _threadInheritInfo(info); AutoCloseable __1 = holdInstance(instanceToHold); try { callF(runnable); } finally { _close(__1); }} catch (Throwable __e) { messageBox(__e); }}}; } static AutoCloseable tempActivity(Object r) { return null; } static boolean allPaused() { return ping_pauseAll; } static void bindTimerToComponent(final Timer timer, JFrame f) { bindTimerToComponent(timer, f.getRootPane()); } static void bindTimerToComponent(final Timer timer, JComponent c) { if (c.isShowing()) timer.start(); c.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { timer.start(); } public void ancestorRemoved(AncestorEvent event) { timer.stop(); } public void ancestorMoved(AncestorEvent event) { } }); } static boolean containsNewLines(String s) { return containsNewLine(s); } static String jlabel_textAsHTML_center(String text) { return "
" + replace(htmlencode(text), "\n", "
") + "
"; } static List buttonsInGroup(ButtonGroup g) { if (g == null) return ll(); return asList(g.getElements()); } static JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) { return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane"); } static A setFrameTitle(A c, final String title) { final Frame f = getAWTFrame(c); if (f != null) { swing(new Runnable() { public void run() { try { f.setTitle(title); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.setTitle(title);"; }}); } return c; } static A setFrameTitle(String title, A c) { return setFrameTitle(c, title); } // magically find a field called "frame" in main class :-) static JFrame setFrameTitle(String title) { Object f = getOpt(mc(), "frame"); if (f instanceof JFrame) return setFrameTitle((JFrame) f, title); return null; } static String getFrameTitle(Component c) { JFrame f = getFrame(c); return f == null ? null : f.getTitle(); } static void closeAutoCloseables(Collection l) { if (l != null) for (AutoCloseable c : l) { try { c.close(); } catch (Throwable __e) { _handleException(__e); }} } static boolean hasMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args) != null; } static A nuInstance(Class c) { return nuEmptyObject(c); } static A copyFields(Object x, A y, String... fields) { if (empty(fields)) { // assume we should copy all fields Map map = objectToMap(x); for (String field : map.keySet()) setOpt(y, field, map.get(field)); } else for (String field : fields) { Object o = getOpt(x, field); if (o != null) setOpt(y, field, o); } return y; } static A copyFields(Object x, A y, Collection fields) { return copyFields(x, y, asStringArray(fields)); } // return Int.MAX_VALUE if not applicable // Lower score is better static int methodApplicabilityScore_onTypes(Method m, Class[] argTypes) { Class[] types = m.getParameterTypes(); if (types.length != argTypes.length) return Integer.MAX_VALUE; int score = 0; for (int i = 0; i < types.length; i++) { Class a = argTypes[i]; Class c = types[i]; if (c == a) {} // perfect match else if (isSubclassOf(a, c)) ++score; else return Integer.MAX_VALUE; } return score; } static void addActionListener(JTextField tf, final Runnable action) { onEnter(tf, action); } static void addActionListener(final JComboBox cb, final Runnable action) { if (cb != null) { swing(new Runnable() { public void run() { try { cb.addActionListener(actionListener(action)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.addActionListener(actionListener(action));"; }}); } } static void addActionListener(final AbstractButton b, final Runnable action) { if (b != null) { swing(new Runnable() { public void run() { try { b.addActionListener(actionListener(action)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "b.addActionListener(actionListener(action));"; }}); } } static String selectedItem(JList l) { return getSelectedItem(l); } static String selectedItem(JComboBox cb) { return getSelectedItem(cb); } static void addMenuItems(JMenu m, Object... x) { fillJMenu(m, x); } static void addMenuItems(JPopupMenu m, Object... x) { fillJPopupMenu(m, x); } 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();"; }}); } 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();"; }}); } static void setTrayIconToolTip(TrayIcon trayIcon, String toolTip) { if (trayIcon != null) trayIcon.setToolTip(toolTip); } static JLabel jImageLabel(Image img) { return swingNu(JLabel.class, imageIcon(img)); } static JLabel jImageLabel(javax.swing.Icon icon) { return swingNu(JLabel.class, icon); } static JLabel jImageLabel(String imageID) { return jImageLabel(imageIcon(imageID)); } static JLabel jImageLabel(String text, String imageID) { final JLabel l = swingNu(JLabel.class, text, imageIcon(imageID), JLabel.CENTER); { swing(new Runnable() { public void run() { try { l.setVerticalTextPosition(SwingConstants.BOTTOM); l.setHorizontalTextPosition(SwingConstants.CENTER); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "l.setVerticalTextPosition(SwingConstants.BOTTOM);\r\n l.setHorizontalTextPos..."; }}); } return l; } static Set synchroWeakHashSet() { return Collections.newSetFromMap((Map) newWeakHashMap()); } static String mechList_opt_raw_fresh(String name) { Object readMode = mechMode().readMode; if (readMode instanceof File) { String md5Name = uniqueFileNameUsingMD5_80_v2(upper(name)); return loadTextFileFromZipFile((File) readMode, md5Name); } boolean useLocal = false, useRemote = true; if (eq(readMode, "mergeLocalAndRemote")) useLocal = true; else if (eq(readMode, "local")) { useLocal = true; useRemote = false; } String s = ""; if (useRemote) { if (eq(mechMode().readMode, "localCopies")) s = unnull(loadTextFile(remoteMechListMirrorFile(name))); else s = serverMechList_raw_fresh(name, true); } if (useLocal) s = appendNewLineIfNempty(s) + localMechList_opt_raw_fresh(name); return s; } static int globalIDLength() { return 16; } static boolean allLowerCaseCharacters(String s) { for (int i = 0; i < l(s); i++) if (Character.getType(s.charAt(i)) != Character.LOWERCASE_LETTER) return false; return true; } static String hopeningTag(String tag, Map params) { return hopeningTag(tag, mapToParams(params)); } static String hopeningTag(String tag, Object... params) { StringBuilder buf = new StringBuilder(); buf.append("<" + tag); for (int i = 0; i < l(params); i += 2) { String name = (String) get(params, i); Object val = get(params, i+1); if (nempty(name) && val != null) { if (val == html_valueLessParam()) buf.append(" " + name); else { String s = str(val); if (!empty(s)) buf.append(" " + name + "=" + htmlQuote(s)); } } } buf.append(">"); return str(buf); } static File imageSnippetCacheFile(String snippetID) { File dir = imageSnippetsCacheDir(); if (!loadBufferedImage_useImageCache) return null; return new File(dir, parseSnippetID(snippetID) + ".png"); } static String snippetImageURL_noHttps(String snippetID) { return snippetImageURL_noHttps(snippetID, "png"); } 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/"); } static ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal(); static ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal(); static byte[] loadBinaryPage(String url) { try { print("Loading " + url); return loadBinaryPage(loadPage_openConnection(new URL(url))); } catch (Exception __e) { throw rethrow(__e); } } 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); } } 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/*Long*/(); } 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); } } /** writes safely (to temp file, then rename) */ public static byte[] saveBinaryFile(String fileName, byte[] contents) { try { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = newFileOutputStream(tempFileName); fileOutputStream.write(contents); fileOutputStream.close(); if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); vmBus_send("wroteFile", file); return contents; } catch (Exception __e) { throw rethrow(__e); } } static byte[] saveBinaryFile(File fileName, byte[] contents) { return saveBinaryFile(fileName.getPath(), contents); } static String dataSnippetLink(String snippetID) { long id = parseSnippetID(snippetID); if (id >= 1100000 && id < 1200000) return imageServerURL() + id; if (id >= 1200000 && id < 1300000) { // Woody files, actually String pw = muricaPassword(); if (empty(pw)) throw fail("Please set 'murica password by running #1008829"); return "https://botcompany.de/files/" + id + "?_pass=" + pw; // XXX, although it typically gets hidden when printing } return fileServerURL() + "/" + id /*+ "?_pass=" + muricaPassword()*/; } static A addAndReturn(Collection c, A a) { if (c != null) c.add(a); return a; } static void loadBinaryPageToFile(String url, File file) { try { print("Loading " + url); loadBinaryPageToFile(openConnection(new URL(url)), file); } catch (Exception __e) { throw rethrow(__e); } } static void loadBinaryPageToFile(URLConnection con, File file) { try { setHeaders(con); loadBinaryPageToFile_noHeaders(con, file); } catch (Exception __e) { throw rethrow(__e); } } 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/*Long*/(); } catch (Throwable e) { printStackTrace(e); } String pat = " {*}" + (len != 0 ? "/" + len : "") + " bytes loaded."; copyStreamWithPrints(inputStream, buf, pat); inputStream.close(); buf.close(); file.delete(); renameFile_assertTrue(ftemp, file); } finally { if (buf != null) buf.close(); } } catch (Exception __e) { throw rethrow(__e); } } static List allToString(Iterable c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } static List allToString(Object[] c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } static DynModule dm_currentModuleMandatory() { return dm_current_mandatory(); } 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); }}; } static A third(List l) { return _get(l, 2); } static A third(Iterable l) { if (l == null) return null; Iterator it = iterator(l); for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) { if (!it.hasNext()) return null; it.next(); } return it.hasNext() ? it.next() : null; } static A third(Producer p) { if (p == null) return null; for (int _repeat_1 = 0; _repeat_1 < 2; _repeat_1++) { if (p.next() == null) return null; } return p.next(); } static A third(A[] bla) { return bla == null || bla.length <= 2 ? null : bla[2]; } static C third(T3 t) { return t == null ? null : t.c; } 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()"; }}; } static Map mruCache(int maxSize) { return synchronizedMRUCache(maxSize); } static int defaultStringTransformerCacheSize() { return 1000; } static List quotelessJavaTok(String s) { ArrayList tok = new ArrayList(); int l = l(s); int i = 0, n = 0; while (i < l) { int j = i; char c, d; // scan for whitespace 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); // scan for non-whitespace if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } else ++j; tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static Object loadJSONPage(String url) { return jsonDecode(loadPage(url)); } static A printHidingCredentials(A o) { print(hideCredentials(str(o))); return o; } static String agiBlue_linkForPhrase(String phrase, Object... additionalParams) { return agiBlueURL() + hquery(arrayPlus /* allow multiple "get" parameters */(additionalParams, "q" , phrase)); } static Object[] paramsWithSameKey(Object key, Collection values) { return paramsWithSameKey(key, asObjectArray(values)); } 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; } static boolean agiBlueURL_noHTTPS = false; static String agiBlueURL_url = "https://agi.blue"; static String agiBlueURL() { return agiBlueURL_noHTTPS ? replacePrefix("https://", "http://", agiBlueURL_url) : agiBlueURL_url; } static String hquery(Map params) { return htmlQuery(params); } static String hquery(Object... data) { return htmlQuery(data); } static int localYear() { return localYear(now()); } static int localYear(long time) { return parseInt(simpleDateFormat_local("yyyy").format(time)); } static java.text.SimpleDateFormat simpleDateFormat(String format, TimeZone timeZone) { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format); sdf.setTimeZone(timeZone); return sdf; } static String padLeft(String s, char c, int n) { return rep(c, n-l(s)) + s; } // default to space static String padLeft(String s, int n) { return padLeft(s, ' ', n); } static int localMonth(long time) { return parseInt(simpleDateFormat_local("MM").format(time)); } static int localMonth() { return localMonth(now()); } static int localDayOfMonth(long time) { return parseInt(simpleDateFormat_local("dd").format(time)); } static int localDayOfMonth() { return localDayOfMonth(now()); } // i must point at the (possibly imaginary) opening bracket // index returned is index of closing bracket + 1 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(); } static Map ciMapWithoutKeysEqualToValues(Map map) { if (map == null) return null; Map map2 = ciMap(); for (String key : keys( map)) { String value = map.get(key); if (!eqic(key, value)) map2.put(key, value); } return map2; } static Map zipTwoTokenizationsToCIMap_strict(List l1, List l2) { int n = l(l1); if (n != l(l2)) return null; Map map = ciMap(); for (int i = 1; i < n; i += 2) if (!strictPutIC(map, l1.get(i), l2.get(i))) return null; return map; } static boolean canPutAllStrictlyIC(Map map, Map map2) { { final Map __0 = unnull(map2); for (A key : keys( __0)) { String value = __0.get(key); if (!canPutStrictlyIC(map, key, value)) return false; }} return true; } static int getIndentOfLine(String s) { int i = 0, n = l(s); while (i < n && s.charAt(i) == ' ') ++i; return i; } static Pair listToPair(List l) { return l(l) != 2 ? null : pair(first(l), second(l)); } static List splitAtDoubleArrow(String s) { return splitAtDoubleArrow(javaTok(s)); } static List splitAtDoubleArrow(List tok) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { int j = indexOfSubList(tok, splitAtDoubleArrow_tok(), i); if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j+3; } return l; } static Map matchDollarVarsIC_withBrackets(String pat, String s) { if (s == null) return null; return matchDollarVarsIC(pat, javaTokNPunctuationWithBrackets(s)); } static String replaceVars_optRound2(String s, Map map) { return tok_deRoundOrCurlyBracket(replaceVars_optRound(s, map)); } static boolean moreThanOneToken(String s) { Producer it = javaTokC_producer(s); if (it.next() == null) return false; return it.next() != null; } static boolean moreThanOneToken(List tok) { return l(tok) > 3; } static Class primitiveToBoxedTypeOpt(Class type) { return or(primitiveToBoxedType(type), type); } static boolean isImageFileName(String s) { return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif"); } static F1 toF1(final Object f) { return functionToF1(f); } static IterableIterator emptyIterableIterator_instance = new IterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; static IterableIterator emptyIterableIterator() { return emptyIterableIterator_instance; } // f: func -> A | endMarker static IterableIterator iff(Object f) { return iteratorFromFunction_withEndMarker(f); } // can't use type parameter because end marker static IterableIterator iff(F0 f) { return iteratorFromFunction_withEndMarker(f); } static IterableIterator iff(IF0 f) { return iteratorFromFunction_withEndMarker(f); } static Object endMarker() { return iteratorFromFunction_endMarker; } static String formatFunctionCall(String fname, Object... args) { return fname + "(" + joinWithComma(allToString(args)) + ")"; } static RootPaneContainer getPossiblyInternalFrame(Component c) { JInternalFrame f = getInternalFrame(c); if (f != null) return f; return optCast(RootPaneContainer.class, getWindow(c)); } static boolean isIPv4(String s) { return s != null && l(javaTokC(s)) == 7 && jfind(javaTok(s), "...") == 1; } static void listThreadLocalAdd(ThreadLocal> tl, A a) { List l = tl.get(); if (l == null) tl.set(l = new ArrayList()); l.add(a); } static A listThreadLocalPopLast(ThreadLocal> tl) { List l = tl.get(); if (l == null) return null; A a = popLast(l); if (empty(l)) tl.set(null); return a; } static boolean headless() { return isHeadless(); } static boolean containsSpaces(String s) { return indexOf(s, ' ') >= 0; } static A getOrKeep(Map map, A a) { if (map == null) return a; A v = map.get(a); return v != null ? v : a; } static List ai_splitCamelCase(String s) { int j = 0; List l = new ArrayList(); // new addition if (isAllUpperCase(s)) { l.add(s); return l; } for (int i = 0; i < l(s); i++) if (i > j && isUpperCaseLetter(s.charAt(i))) { l.add(substring(s, j, i)); j = i; } if (j < l(s)) l.add(substring(s, j)); return l; } static JTextField standardTextFieldPopupMenu(final JTextField tf) { final WeakReference ref = weakRef(tf); componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() { public void run() { try { copyTextToClipboard(ref.get().getText()) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(ref.get().getText())"; }}); componentPopupMenuItem(tf, "Paste", new Runnable() { public void run() { try { ref.get().paste() ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ref.get().paste()"; }}); return tf; } static A jenableUndoRedo(final A textcomp) { { swing(new Runnable() { public void run() { try { final UndoManager undo = new UndoManager(); vm_generalWeakSet("Undo Managers").add(undo); textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent evt) { undo.addEdit(evt.getEdit()); } }); textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() { public void run() { try { if (undo.canUndo()) undo.undo() ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canUndo()) undo.undo()"; }})); textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() { public void run() { try { if (undo.canRedo()) undo.redo() ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canRedo()) undo.redo()"; }})); textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo"); textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new UndoManager undo;\r\n vm_generalWeakSet(\"Undo Managers\").add(undo)..."; }}); } return textcomp; } static String strOrEmpty(Object o) { return o == null ? "" : str(o); } static JInternalFrame showForm_makeInternalFrame(JDesktopPane desktop, String title, JPanel panel) { JInternalFrame f = addInternalFrame(desktop, title, withMargin(panel)); minInternalFrameWidth(f, 400); packInternalFrameVertically(f); centerInternalFrame(f); // TODO: handleEscapeKey(f); return f; } static JFrame handleEscapeKey(final JFrame frame) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); frame.getRootPane().registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { frame.dispose(); } }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); return frame; } static JFrame minFrameWidth(JFrame frame, int w) { if (frame != null && frame.getWidth() < w) frame.setSize(w, frame.getHeight()); return frame; } static JFrame minFrameWidth(int w, JFrame frame) { return minFrameWidth(frame, w); } static JFrame showPackedFrame(String title, Component contents) { return packFrame(showFrame(title, contents)); } static JFrame showPackedFrame(Component contents) { return packFrame(showFrame(contents)); } static int withMargin_defaultWidth = 6; static JPanel withMargin(Component c) { return withMargin(withMargin_defaultWidth, c); } static JPanel withMargin(int w, Component c) { return withMargin(w, w, c); } static JPanel withMargin(int w, int h, Component c) { return withMargin(w, h, w, h, c); } static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) { return swing(new F0() { 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..."; }}); } static int showForm_leftWidth(List> l) { int minW = 0; for (List row : l) minW = max(minW, getMinimumSize(first(row)).width); return minW; } static JPanel westAndCenter(final Component w, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.WEST, wrap(w)); panel.add(BorderLayout.CENTER, wrap(c)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST..."; }}); } static int withRightMargin_defaultWidth = 6; static JPanel withRightMargin(Component c) { return withRightMargin(withRightMargin_defaultWidth, c); } static JPanel withRightMargin(final int w, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, w)); p.add(c); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat..."; }}); } static A jMinWidth(final int w, final A c) { if (c == null) return null; return swing(new F0() { public A get() { try { Dimension size = c.getMinimumSize(); c.setMinimumSize(new Dimension(/*max(w, size.width) ??? */w, size.height)); return jPreferWidth(w, c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Dimension size = c.getMinimumSize();\r\n c.setMinimumSize(new Dimension(/*ma..."; }}); } static void setComponentID(Component c, String id) { if (c != null) componentID_map.put(c, id); } static List mapLL(Object f, Object... data) { return map(f, ll(data)); } static Component wrapForSmartAdd(Object o) { if (o == null) return jpanel(); if (o instanceof String) return jlabel((String) o); return wrap(o); } static boolean isRunnable(Object o) { return o instanceof Runnable || hasMethod(o, "get"); } static String showFormSubmitButtonName() { return "Submit"; } static void disposeInternalFrame(Component c) { final JInternalFrame f = getInternalFrame(c); if (f != null) { swing(new Runnable() { public void run() { try { f.dispose(); setOpt(f, "lastFocusOwner" , null); // Help GC } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.dispose();\r\n setOpt(f, lastFocusOwner := null); // Help GC"; }}); } } static void disposeFrame(final Component c) { disposeWindow(c); } static void onEnterInAllTextFields(JComponent c, Object action) { if (action == null) return; for (Component tf : allChildren(c)) onEnterIfTextField(tf, action); } static void onEnterInAllTextFields(List c, Object action) { for (Object o : unnull(c)) if (o instanceof JComponent) onEnterInAllTextFields((JComponent) o, action); } static void clickButton(final JButton b) { if (b != null) { swing(new Runnable() { public void run() { try { if (b.isEnabled()) b.doClick(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (b.isEnabled())\r\n b.doClick();"; }}); } } static A makeBold(final A c) { if (c != null) { swing(new Runnable() { public void run() { try { c.setFont(c.getFont().deriveFont(java.awt.Font.BOLD)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.setFont(c.getFont().deriveFont(java.awt.Font.BOLD));"; }}); } return c; } static JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) { for (Object o : parts) panel.add(wrapForSmartAdd(o), layout); return panel; } static JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) { return smartAddWithLayout(panel, layout, asList(flattenArray2(parts))); } static List nonNulls(List l) { return withoutNulls(l); } static List nonNulls(A[] l) { return withoutNulls(l); } static Map nonNulls(Map map) { return withoutNulls(map); } static Component jrigid() { return javax.swing.Box.createRigidArea(new Dimension(0, 0)); } static String nullIfEmpty(String s) { return isEmpty(s) ? null : s; } static Map nullIfEmpty(Map map) { return isEmpty(map) ? null : map; } static List nullIfEmpty(List l) { return isEmpty(l) ? null : l; } static boolean newButton_autoToolTip = true; // action can be Runnable or a function name static JButton newButton(final String text, final Object action) { return swing(new F0() { public JButton get() { try { String text2 = dropPrefix("[disabled] ", text); final JButton btn = new JButton(text2); if (l(text2) < l(text)) btn.setEnabled(false); if (newButton_autoToolTip) { btn.setToolTipText(btn.getText()); //onChangeAndNow(btn, r { btn.setToolTipText(btn.getText()) }); } // submitButtonOnEnter(btn); // test this first if (action != null) btn.addActionListener(actionListener(action, btn)); return btn; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "S text2 = dropPrefix(\"[disabled] \", text);\r\n final JButton btn = new JButt..."; }}); } static String charToString(char c) { return String.valueOf(c); } static String charToString(int c) { return String.valueOf((char) c); } static Object[] asArray(List l) { return toObjectArray(l); } static A[] asArray(Class type, List l) { return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size())); } static boolean isMenuSeparatorIndicator(Object o) { return eqOneOf(o, "***", "---", "===", ""); } static boolean isRunnableX(Object o) { if (o == null) return false; if (o instanceof String) return hasMethod(mc(), (String) o); return o instanceof Runnable || hasMethod(o, "get"); } static A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) { if (lv != null) bindToComponent(component, new Runnable() { public void run() { try { lv.onChangeAndNow(listener); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindLiveValueListenerToComponent_debug\r\n print(\"bindLiveValueL..."; }}, new Runnable() { public void run() { try { lv.removeOnChangeListener(listener) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lv.removeOnChangeListener(listener)"; }}); return component; } static String unCurlyBracket(String s) { return tok_unCurlyBracket(s); } static boolean isInstanceOf(Object o, Class type) { return type.isInstance(o); } static int preferredWidth(Component c) { return c == null ? 0 : getPreferredSize(c).width; } static JButton renameButton(JComponent c, String name) { JButton b = first(childrenOfType(c, JButton.class)); if (b != null) b.setText(name); return b; } static JButton renameButton(JComponent c, String oldName, String newName) { JButton b = findButton(c, oldName); if (b != null) b.setText(newName); return b; } static String fileInfo(File f) { return renderFileInfo(f); } static String fileInfo(String f) { return renderFileInfo(newFile(f)); } static void dm_persistModule(Object module) { call(dm_getStem(module), "persistContents"); } static String dm_getStructure(Object module) { return (String) get(dm_getStem(module), "oStruct"); } static void logQuotedWithDate(String s) { logQuotedWithTime(s); } static void logQuotedWithDate(String logFile, String s) { logQuotedWithTime(logFile, s); } static void logQuotedWithDate(File logFile, String s) { logQuotedWithTime(logFile, s); } static File infoBoxesLogFile() { return new File(javaxDataDir(), "Logs/infoBoxes.txt"); } static JWindow showWindow(Component c) { JWindow w = new JWindow(); w.add(wrap(c)); return w; } static JPanel infoMessage_makePanel(String text) { final JTextArea ta = wrappedTextArea(text); onClick(ta, new Runnable() { public void run() { try { disposeWindow(ta) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disposeWindow(ta)"; }}); int size = 14; if (l(text) <= 50) size *= 2; else if (l(text) < 100) size = iround(size*1.5); ta.setFont(typeWriterFont(size)); JScrollPane sp = jscroll(ta); return withMargin(sp); } static int moveToTopRightCorner_inset = 20; static A moveToTopRightCorner(A a) { return moveToTopRightCorner(moveToTopRightCorner_inset, moveToTopRightCorner_inset, a); } static A moveToTopRightCorner(int insetX, int insetY, A a) { Window w = getWindow(a); if (w != null) w.setLocation(getScreenSize().width-w.getWidth()-insetX, insetY); return a; } static boolean vmBus_noObjections(String msg, Object... args) { return !vmBus_anyFalse(msg, args); } static A disposeWindowAfter(int delay, final A w) { if (w != null) swingLater(delay, new Runnable() { public void run() { try { w.dispose(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "w.dispose();"; }}); return w; } static A disposeWindowAfter(A w, double seconds) { return disposeWindowAfter(toMS_int(seconds), w); } static A disposeWindowAfter(double seconds, A w) { return disposeWindowAfter(w, seconds); } static Map loadFont_cached_cache = new HashMap(); static synchronized Font loadFont_cached(String snippetID) { try { snippetID = formatSnippetID(snippetID); Font f = loadFont_cached_cache.get(snippetID); if (f == null) loadFont_cached_cache.put(snippetID, f = loadFont(snippetID, 12f)); return f; } catch (Exception __e) { throw rethrow(__e); } } static synchronized Font loadFont_cached(String snippetID, float size) { try { return loadFont_cached(snippetID).deriveFont(size); } catch (Exception __e) { throw rethrow(__e); } } static float getSwingFontScale() { return or((Float) vm_generalMap_get("swingFontScale_value"), 1f); } static A firstWithClassShortNamed(String shortName, Iterable l) { if (l != null) for (A o : l) if (eq(shortClassName(o), shortName)) return o; return null; } static A firstWithClassShortNamed(String shortName, A[] l) { if (l != null) for (A o : l) if (eq(shortClassName(o), shortName)) return o; return null; } static JMenuItem jMenuItem(final String text) { return jmenuItem(text); } static JMenuItem jMenuItem(String text, Object r) { return jmenuItem(text, r); } static Pair jmenu_autoMnemonic(String s) { int i = indexOf(s, '&'); if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i+1))) return pair(substring(s, 0, i) + substring(s, i+1), (int) s.charAt(i+1)); return pair(s, 0); } static 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; } static Runnable asRunnable(Object o) { return toRunnable(o); } static void _inheritThreadInfo(Object info) { _threadInheritInfo(info); } static String htmlencode(Object o) { return htmlencode(str(o)); } static String htmlencode(String s) { if (s == null) return ""; StringBuilder out = new StringBuilder(Math.max(16, s.length())); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c > 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(); } static Component childWithClassNameEndingWith(Component c, String suffix) { if (endsWith(className(c), suffix)) return c; Component x; for (Component comp : getComponents(c)) if ((x = childWithClassNameEndingWith(comp, suffix)) != null) return x; return null; } static Frame getAWTFrame(final Object _o) { return swing(new F0() { public Frame get() { try { Object o = _o; /* ifdef HaveProcessing if (o instanceof PApplet) o = ((PApplet) o).getSurface(); endifdef */ if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof Frame) return (Frame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n /*\r\n ifdef HaveProcessing\r\n if (o instanceof PApplet) ..."; }}); } // o is either a map already (string->object) or an arbitrary object, // in which case its fields are converted into a map. static Map objectToMap(Object o) { try { if (o instanceof Map) return (Map) o; TreeMap map = new TreeMap(); Class c = o.getClass(); while (c != Object.class) { Field[] fields = c.getDeclaredFields(); for (final Field field : fields) { if ((field.getModifiers() & Modifier.STATIC) != 0) continue; field.setAccessible(true); final Object value = field.get(o); if (value != null) map.put(field.getName(), value); } c = c.getSuperclass(); } // XXX NEW - hopefully this doesn't break anything if (o instanceof DynamicObject) map.putAll(((DynamicObject) o).fieldValues); return map; } catch (Exception __e) { throw rethrow(__e); } } // same for a collection (convert each element) static List> objectToMap(Iterable l) { if (l == null) return null; List x = new ArrayList(); for (Object o : l) x.add(objectToMap(o)); return x; } static String[] asStringArray(Collection c) { return toStringArray(c); } static String[] asStringArray(Object o) { return toStringArray(o); } static boolean isSubclassOf(Class a, Class b) { return isSubclass(a, b); } static JTextField onEnter(final JTextField tf, final Object action) { if (action == null || tf == null) return tf; tf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { tf.selectAll(); callF(action); } catch (Throwable __e) { messageBox(__e); }}}); return tf; } static JButton onEnter(JButton btn, final Object action) { if (action == null || btn == null) return btn; btn.addActionListener(actionListener(action)); return btn; } static JList onEnter(JList list, Object action) { list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action))); return list; } static JComboBox onEnter(final JComboBox cb, final Object action) { { swing(new Runnable() { public void run() { try { if (cb.isEditable()) { JTextField text = (JTextField) cb.getEditor().getEditorComponent(); onEnter(text, action); } else { cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter"); cb.getActionMap().put("enter", abstractAction("", new Runnable() { public void run() { try { cb.hidePopup(); callF(action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.hidePopup(); callF(action);"; }})); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (cb.isEditable()) {\r\n JTextField text = (JTextField) cb.getEditor().g..."; }}); } return cb; } static JTable onEnter(final JTable table, final Object action) { table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter"); table.getActionMap().put("Enter", new AbstractAction() { public void actionPerformed(ActionEvent e) { callF(action, table.getSelectedRow()); } }); return table; } /*static JTextArea onEnter(final JTextArea ta, fO action) { addKeyListener(ta, enterKeyListener(action)); ret ta; }*/ static JTextField onEnter(Object action, JTextField tf) { return onEnter(tf, action); } static String getSelectedItem(JList l) { return (String) l.getSelectedValue(); } static String getSelectedItem(JComboBox cb) { return strOrNull(cb.getSelectedItem()); } static void fillJMenu(final JMenu m, Object... x) { //ifdef fillJMenu_debug //print("fillJMenu " + m); //endifdef if (x == null) return; for (int i = 0; i < l(x); i++) { Object o = x[i], y = get(x, i+1); if (o instanceof List) fillJMenu(m, asArray((List) o)); else if (isMenuSeparatorIndicator(o)) { if (menuItemCount(m) != 0) // auto-skip separator if at top m.addSeparator(); } else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) { final LiveValue lv = (LiveValue) o; final JMenuItem mi = jmenuItem(or2(unCurlyBracket(lv.get()), "..."), y); bindLiveValueListenerToComponent(mi, lv, new Runnable() { public void run() { try { String s = lv.get(); if (isCurlyBracketed(s)) { setEnabled(mi, false); s = unCurlyBracket(s); } else setEnabled(mi, true); setText(mi, s); revalidate(m); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = lv.get();\r\n if (isCurlyBracketed(s)) {\r\n setEnable..."; }}); print("bound live value " + lv + " to menu item " + mi); m.add(mi); ++i; } else if (o instanceof String && isRunnableX(y)) { m.add(jmenuItem((String) o, y)); ++i; } else if (o instanceof JMenuItem) m.add((JMenuItem) o); // "call" might use wrong method else if (o instanceof String || o instanceof Action || o instanceof Component) call(m, "add", o); else if (o == null && y instanceof Runnable) ++i; // text == null => disabled item else print("Unknown menu item: " + o); } } static int imageIcon_cacheSize = 10; static boolean imageIcon_verbose = false; static Map imageIcon_cache; static Lock imageIcon_lock = lock(); static ThreadLocal imageIcon_fixGIF = new ThreadLocal(); // not going through BufferedImage preserves animations static ImageIcon imageIcon(String imageID) { try { if (imageID == null) return null; Lock __0 = imageIcon_lock; lock(__0); try { if (imageIcon_cache == null) imageIcon_cache = new MRUCache(imageIcon_cacheSize); imageID = fsI(imageID); ImageIcon ii = imageIcon_cache.get(imageID); if (ii == null) { if (imageIcon_verbose) print("Loading image icon: " + imageID); File f = loadBinarySnippet(imageID); Boolean b = imageIcon_fixGIF.get(); if (!isFalse(b)) ii = new ImageIcon(loadBufferedImageFixingGIFs(f)); else ii = new ImageIcon(f.toURI().toURL()); } else imageIcon_cache.remove(imageID); // move to front of cache on access imageIcon_cache.put(imageID, ii); return ii; } finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } } // doesn't fix GIFs static ImageIcon imageIcon(File f) { try { return new ImageIcon(f.toURI().toURL()); } catch (Exception __e) { throw rethrow(__e); } } static ImageIcon imageIcon(Image img) { return new ImageIcon(img); } static ImageIcon imageIcon(RGBImage img) { return imageIcon(img.getBufferedImage()); } // requires ugly casting when used (O -> A) static Object iteratorFromFunction_endMarker = new Object(); // f: func -> A | endMarker static IterableIterator iteratorFromFunction_withEndMarker(final Object f) { class IFF extends IterableIterator { A a; boolean have, done; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; have = false; return _a; } void getNext() { if (done || have) return; Object o = callF(f); if (o == iteratorFromFunction_endMarker) { done = true; return; } a = (A) o; have = true; } }; return new IFF(); } // optimized version for F0 argument; TODO: do same for IF0 static IterableIterator iteratorFromFunction_withEndMarker(final F0 f) { return iteratorFromFunction_withEndMarker_f0(f); } static Map componentID_map = weakHashMap(); static String componentID(Component c) { return c == null ? null : componentID_map.get(c); } static MechMode mechMode_value = new MechMode(); static MechMode mechMode() { return mechMode_value; } static String loadTextFileFromZipFile(File inZip, String fileName) { try { if (!fileExists(inZip)) return null; try { ZipFile zip = new ZipFile(inZip); try { return loadTextFileFromZipFile(zip, fileName); } finally { _close(zip); }} catch (Throwable e) { throw fail(f2s(inZip), e); } } catch (Exception __e) { throw rethrow(__e); } } static String loadTextFileFromZipFile(ZipFile zip, String fileName) { try { ZipEntry entry = zip.getEntry(fileName); if (entry == null) return null; InputStream fin = zip.getInputStream(entry); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copyStream(fin, baos); return fromUTF8(baos.toByteArray()); } finally { _close(fin); }} catch (Exception __e) { throw rethrow(__e); } } static File remoteMechListMirrorFile(String listName) { return newFile(remoteMechListMirrorsDir(), uniqueFileNameUsingMD5_80_v2(upper(listName))); } static boolean serverMechList_raw_fresh_verbose = false; static String serverMechList_raw_fresh(String name) { return serverMechList_raw_fresh(name, false); } static String serverMechList_raw_fresh(String name, boolean opt) { Lock __0 = downloadLock(); lock(__0); try { /*if (serverMechList_raw_fresh_verbose) print("serverMechList_raw_fresh " + name);*/ String text = null; try { text = loadTextFile(remoteMechListMirrorFile(name)); } catch (Throwable __e) { _handleException(__e); } Object[] params = muricaCredentialsPlus("md5" , md5OrNull(text), "l" , l(text), "opt" , opt ? 1 : 0, "withStatus" , 1); String url = "http://butter.botcompany.de:8080/mech/raw/list-text/" + urlencode(name); String page = postPageSilently(url, params); Map map = jsonDecodeMap(page); boolean same = eq(map.get("Same"), true); boolean appended = eq(map.get("Appended"), true); saveTextFile(remoteMechListMirrorMetaFile(name), struct(getMultipleKeys(map, "Name", "Status"))); if (!same) { if (appended) text += (String) map.get("Text"); else text = (String) map.get("Text"); saveTextFile(remoteMechListMirrorFile(name), text); File nameFile = remoteMechListMirrorNameFile(name); if (!fileExists(nameFile)) { String actualName = or((String) map.get("Name"), name); saveTextFile(nameFile, actualName); } } if (serverMechList_raw_fresh_verbose) print("Mech list " + name + ": " + (appended ? "appended" : same ? "same" : "downloaded") + ": " + n2(countLines(text), "line")); if (!same) vmBus_send("remoteMechListMirrorChanged", name); return text; } finally { unlock(__0); } } static String localMechList_opt_raw_fresh(String name) { return unnull(loadTextFile(localMechListFile(name))); } static Object html_valueLessParam_cache; static Object html_valueLessParam() { if (html_valueLessParam_cache == null) html_valueLessParam_cache = html_valueLessParam_load(); return html_valueLessParam_cache; } static Object html_valueLessParam_load() { return new Object(); } static String htmlQuote(String s) { return "\"" + htmlencode_forParams(s) + "\""; } static A println(A a) { return print(a); } static String fileServerURL() { return "https://botcompany.de/files"; } 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(100000, total)))); total += n; } } catch (Exception __e) { throw rethrow(__e); } } 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); } } static boolean jsonDecode_useOrderedMaps = true; static Object jsonDecode(final String text) { final List tok = jsonTok(text); if (l(tok) == 1) return null; class Y { int i = 1; Object parse() { String t = tok.get(i); if (t.startsWith("\"") || t.startsWith("'")) { String s = unquote(tok.get(i)); i += 2; return s; } if (t.equals("{")) return parseMap(); if (t.equals("[")) return this.parseList(); // avoid loading standard function "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)) { int j = i; i += 2; if (eqOneOf(get(tok, i), ".", "e", "E")) { // rough parsing for doubles while (isInteger(get(tok, i)) || eqOneOf(get(tok, i), ".", "e", "E", "-")) i += 2; double d = parseDouble(joinSubList(tok, j, i-1)); if (minus) d = -d; return d; } else { long l = parseLong(t); if (minus) l = -l; return l != (int) l ? (Object) new Long(l) : new Integer((int) l); } } throw new RuntimeException("Unknown token " + (i+1) + ": " + t + ": " + text); } 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; } 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; } 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(); } // one array plus more elements static Object[] arrayPlus(Object[] a1, Object... a2) { return concatArrays(a1, a2); } static Object[] asObjectArray(Collection l) { return toObjectArray(l); } static boolean canPutStrictlyIC(Map map, A key, String value) { if (!(map != null && key != null && value != null)) return true; String old = map.get(key); return old == null || eqic(old, value); } static Map matchDollarVarsIC(String pat, String s) { if (s == null) return null; return matchDollarVarsIC(pat, parse3_cachedInput(s)); } static Map matchDollarVarsIC(String pat, List tokS) { if (pat == null || tokS == null) return null; List vars = new ArrayList(); String pat2 = dollarVarsToStars(pat, vars); Matches m = new Matches(); if (!match3(pat2, tokS, m)) return null; Map map = new HashMap(); for (int i = 0; i < l(m.m); i++) { String var = vars.get(i); String value = m.get(i); String oldValue = map.get(var); if (oldValue == null) map.put(var, value); else if (neqic(oldValue, value)) return null; } return map; } static String replaceVars_optRound(String s, Map map) { return replaceCodeTokensUsingMap(s, mapValues(__94 -> optRound(__94),map)); } static Producer javaTokC_producer(String s) { return javaTokC_iterator(s); } static Class primitiveToBoxedType(Class type) { if (type == boolean.class) return Boolean.class; if (type == int.class) return Integer.class; if (type == long.class) return Long.class; if (type == float.class) return Float.class; if (type == short.class) return Short.class; if (type == char.class) return Character.class; if (type == byte.class) return Byte.class; if (type == double.class) return Double.class; return null; } static F1 functionToF1(final Object f) { if (isString(f)) return mainFunctionToF1((String) f); if (f instanceof F1) return (F1) f; return new F1() { public Object get(Object a) { try { return callF(f, a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret callF(f, a);"; }}; } static A optCast(Class c, Object o) { return isInstance(c, o) ? (A) o : null; } static Window getWindow(Object o) { if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof Window) return (Window) c; c = c.getParent(); } return null; } static boolean isAllUpperCase(String s) { return hasLettersAllUpperCase(s); } static boolean isUpperCaseLetter(char c) { return Character.isUpperCase(c); } static Set vm_generalWeakSet(Object name) { synchronized(get(javax(), "generalMap")) { Set set = (Set) (vm_generalMap_get(name)); if (set == null) vm_generalMap_put(name, set = newWeakHashSet()); return set; } } static ThreadLocal addInternalFrame_dontSelect = new ThreadLocal(); static ThreadLocal addInternalFrame_layer = new ThreadLocal(); static ThreadLocal addInternalFrame_toBack = new ThreadLocal(); static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h) { return addInternalFrame(desktop, title, x, y, w, h, null); } static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h, final Component contents) { return addInternalFrame(desktop, title, rect(x, y, w, h), contents); } static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Component contents) { return addInternalFrame(desktop, title, null, contents); } static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Rect r, final Component contents) { final boolean dontSelect = isTrue(optParam(addInternalFrame_dontSelect)); final boolean toBack = isTrue(optParam(addInternalFrame_toBack)); final Integer layer = optParam(addInternalFrame_layer); return swing(new F0() { public JInternalFrame get() { try { JInternalFrame frame; if (contents instanceof JInternalFrame) frame = (JInternalFrame) contents; else { frame = jInternalFrame(title); setInternalFrameContents(frame, contents); } frame.setVisible(true); desktop.add(frame, layer); if (r != null) setBounds(frame, r); else internalFrameDefaultPosition(frame); if (dontSelect) if (toBack) frame.toBack(); else frame.toFront(); else frame.setSelected(true); return fixInternalFrame(frame); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JInternalFrame frame;\r\n if (contents instanceof JInternalFrame)\r\n fra..."; }}); } static JInternalFrame addInternalFrame(JDesktopPane desktop, String title) { return addInternalFrame(desktop, title, jpanel()); } static JInternalFrame minInternalFrameWidth(final JInternalFrame frame, final int w) { { swing(new Runnable() { public void run() { try { if (frame != null && frame.getWidth() < w) frame.setSize(w, frame.getHeight()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (frame != null && frame.getWidth() < w)\r\n frame.setSize(w, frame.getH..."; }}); } return frame; } static JInternalFrame minInternalFrameWidth(int w, JInternalFrame frame) { return minInternalFrameWidth(frame, w); } static A packInternalFrameVertically(A c) { return packInternalFrameVertically(-1, c); } static A packInternalFrameVertically(int width, A c) { final JInternalFrame win = getInternalFrame(c); if (win == null) return c; final int w = width < 0 ? win.getWidth() : width; { swing(new Runnable() { public void run() { try { win.pack(); win.setSize(w, win.getHeight()); fixInternalFrame(win); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "win.pack();\r\n win.setSize(w, win.getHeight());\r\n fixInternalFrame(win);"; }}); } return c; } static JInternalFrame centerInternalFrame(final JInternalFrame f) { { swing(new Runnable() { public void run() { try { Container c = f.getParent(); if (c != null) { //print("Container type: " + className(c) + ", bounds: " + c.getBounds()); f.setLocation((c.getWidth()-f.getWidth())/2, (c.getHeight()-f.getHeight())/2); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Container c = f.getParent();\r\n if (c != null) {\r\n //print(\"Container ..."; }}); } return f; } static JInternalFrame centerInternalFrame(final int w, final int h, final JInternalFrame f) { { swing(new Runnable() { public void run() { try { f.setSize(w, h); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.setSize(w, h);"; }}); } return centerInternalFrame(f); } static int packFrame_minw = 150, packFrame_minh = 50; static A packFrame(final A c) { { swing(new Runnable() { public void run() { try { Window w = getWindow(c); if (w != null) { w.pack(); int maxW = getScreenWidth()-50, maxH = getScreenHeight()-50; w.setSize( min(maxW, max(w.getWidth(), packFrame_minw)), min(maxH, max(w.getHeight(), packFrame_minh))); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Window w = getWindow(c);\r\n if (w != null) {\r\n w.pack();\r\n int ma..."; }}); } return c; } static JFrame packFrame(ButtonGroup g) { return packFrame(getFrame(g)); } static JFrame showFrame() { return makeFrame(); } static JFrame showFrame(Object content) { return makeFrame(content); } static JFrame showFrame(String title) { return makeFrame(title); } static JFrame showFrame(String title, Object content) { return makeFrame(title, content); } static JFrame showFrame(final JFrame f) { if (f != null) { swing(new Runnable() { public void run() { try { if (frameTooSmall(f)) frameStandardSize(f); if (!f.isVisible()) f.setVisible(true); // XXX if (f.getState() == Frame.ICONIFIED) f.setState(Frame.NORMAL); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (frameTooSmall(f)) frameStandardSize(f);\r\n if (!f.isVisible()) f.setVis..."; }}); } return f; } // make or update frame static JFrame showFrame(String title, Object content, JFrame frame) { if (frame == null) return showFrame(title, content); else { frame.setTitle(title); setFrameContents(frame, content); return frame; } } static Dimension getMinimumSize(final Component c) { return c == null ? null : swing(new F0() { public Dimension get() { try { return c.getMinimumSize(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getMinimumSize();"; }}); } // c = Component or something implementing swing() static JComponent wrap(Object swingable) { return _recordNewSwingComponent(wrap_2(swingable)); } 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; } static A jPreferWidth(int w, A c) { Dimension size = c.getPreferredSize(); c.setPreferredSize(new Dimension(/*max(w, size.width) ??? */w, size.height)); return c; } static JLabel jlabel(final String text) { return swingConstruct(BetterLabel.class, text); } static JLabel jlabel() { return jlabel(" "); } static void disposeWindow(final Window window) { if (window != null) { swing(new Runnable() { public void run() { try { window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); // call listeners myFrames_list.remove(window); window.dispose(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //..."; }}); } } static void disposeWindow(final Component c) { disposeWindow(getWindow(c)); } static void disposeWindow(Object o) { if (o != null) disposeWindow(((Component) o)); } static void disposeWindow() { disposeWindow(heldInstance(Component.class)); } static List allChildren(Component c) { return childrenOfType(c, Component.class); } static void onEnterIfTextField(Component c, Object action) { if (action == null) return; if (c instanceof JTextField) onEnter((JTextField) c, action); else if (c instanceof JComboBox) onEnter((JComboBox) c, action); } static Object[] flattenArray2(Object... a) { List l = new ArrayList(); if (a != null) for (Object x : a) if (x instanceof Object[]) l.addAll(asList((Object[]) x)); else if (x instanceof Collection) l.addAll((Collection) x); else l.add(x); return asObjectArray(l); } static List withoutNulls(List l) { if (!containsNulls(l)) return l; List l2 = new ArrayList(); for (A a : l) if (a != null) l2.add(a); return l2; } static Map withoutNulls(Map map) { Map map2 = similarEmptyMap(map); for (A a : keys(map)) if (a != null) { B b = map.get(a); if (b != null) map2.put(a, b); } return map2; } static List withoutNulls(A[] l) { List l2 = new ArrayList(); if (l != null) for (A a : l) if (a != null) l2.add(a); return l2; } static boolean isEmpty(Collection c) { return c == null || c.isEmpty(); } static boolean isEmpty(CharSequence s) { return s == null || s.length() == 0; } static boolean isEmpty(Object[] a) { return a == null || a.length == 0; } static boolean isEmpty(byte[] a) { return a == null || a.length == 0; } static boolean isEmpty(Map map) { return map == null || map.isEmpty(); } static A bindToComponent(final A component, final Runnable onShow, final Runnable onUnShow) { { swing(new Runnable() { public void run() { try { final Var < Boolean > flag = new Var<>(false); component.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { if (flag.get()) print("Warning: bindToComponent logic failure"); flag.set(true); pcallF(onShow); } public void ancestorRemoved(AncestorEvent event) { if (!flag.get()) print("Warning: bindToComponent logic failure"); flag.set(false); pcallF(onUnShow); } public void ancestorMoved(AncestorEvent event) { } }); if (component.isShowing()) { // Hopefully this matches the AncestorListener logic flag.set(true); pcallF(onShow); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final Var flag = new(false);\r\n component.addAncestorListener(new ..."; }}); } return component; } static A bindToComponent(A component, Runnable onShow) { return bindToComponent(component, onShow, null); } static String tok_unCurlyBracket(String s) { return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s; } static List childrenOfType(Component c, Class theClass) { List l = new ArrayList(); scanForComponents(c, theClass, l); return l; } static List childrenOfType(Class theClass, Component c) { return childrenOfType(c, theClass); } static JButton findButton(Component c, String name) { for (JButton b : childrenOfType(c, JButton.class)) if (eq(b.getText(), name)) return b; for (JButton b : childrenOfType(getFrame(c), JButton.class)) if (eq(b.getText(), name)) return b; return null; } static JButton findButton(Component c) { return childOfType(c, JButton.class); } static String renderFileInfo(File f) { return f == null ? "-" : f2s(f) + " " + (f.isFile() ? "(file, " + n2(fileSize(f)) + " bytes)" : f.isDirectory() ? "(dir)" : "(not found)"); } static void logQuotedWithTime(String s) { logQuotedWithTime(standardLogFile(), s); } static void logQuotedWithTime(File logFile, String s) { logQuoted(logFile, logQuotedWithTime_format(s)); } static void logQuotedWithTime(String logFile, String s) { logQuoted(logFile, logQuotedWithTime_format(s)); } static String logQuotedWithTime_format(String s) { return /*formatGMTWithDate_24*/(now()) + " " + s; } static JTextArea wrappedTextArea(final JTextArea ta) { enableWordWrapForTextArea(ta); return ta; } static JTextArea wrappedTextArea() { return wrappedTextArea(jtextarea()); } static JTextArea wrappedTextArea(String text) { JTextArea ta = wrappedTextArea(); setText(ta, text); return ta; } static A onClick(final A c, final Object runnable) { if (c != null) { swing(new Runnable() { public void run() { try { c.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { callF(runnable, e); } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(MouseEv..."; }}); } return c; } // re-interpreted for buttons static void onClick(JButton btn, final Object runnable) { onEnter(btn, runnable); } static Dimension getScreenSize() { return Toolkit.getDefaultToolkit().getScreenSize(); } static boolean vmBus_anyFalse(String msg, Object... args) { return contains(vmBus_queryAll(msg, args), false); } static int toMS_int(double seconds) { return toInt_checked((long) (seconds*1000)); } static Font loadFont(String snippetID) { try { return loadFont(snippetID, 12f); } catch (Exception __e) { throw rethrow(__e); } } static Font loadFont(InputStream in) { try { return Font.createFont(Font.TRUETYPE_FONT, in); } catch (Exception __e) { throw rethrow(__e); } } static Font loadFont(String snippetID, float fontSize) { return loadFont(loadLibrary(snippetID), fontSize); } static Font loadFont(File f, float fontSize) { try { return Font.createFont(Font.TRUETYPE_FONT, f).deriveFont(fontSize); } catch (Exception __e) { throw rethrow(__e); } } static Font loadFont(InputStream in, float fontSize) { try { return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(fontSize); } catch (Exception __e) { throw rethrow(__e); } } static boolean isLetterOrDigit(char c) { return Character.isLetterOrDigit(c); } static String intToHex_flexLength(int i) { return Integer.toHexString(i); } 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();"; }})); } static boolean isSubclass(Class a, Class b) { return a != null && b != null && b.isAssignableFrom(a); } static KeyListener enterKeyListener(final Object action) { return new KeyAdapter() { public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_ENTER) pcallF(action); } }; } static Runnable rCallOnSelectedListItem(final JList list, final Object action) { return new Runnable() { public void run() { try { pcallF(action, getSelectedItem(list)) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, getSelectedItem(list))"; }}; } static String strOrNull(Object o) { return o == null ? null : str(o); } static int menuItemCount(JMenu menu) { return menu == null ? 0 : swing(() -> menu.getItemCount()); } static boolean loadBufferedImageFixingGIFs_debug = false; static ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal(); static Image loadBufferedImageFixingGIFs(File file) { try { if (!file.exists()) return null; // Load anything but GIF the normal way if (!isGIF(file)) return ImageIO.read(file); if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": checking gif"); // Get GIF reader ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next(); // Give it the stream to decode from reader.setInput(ImageIO.createImageInputStream(file)); int numImages = reader.getNumImages(true); // Get 'metaFormatName'. Need first frame for that. IIOMetadata imageMetaData = reader.getImageMetadata(0); String metaFormatName = imageMetaData.getNativeMetadataFormatName(); // Find out if GIF is bugged boolean foundBug = false; for (int i = 0; i < numImages && !foundBug; i++) { // Get metadata IIOMetadataNode root = (IIOMetadataNode)reader.getImageMetadata(i).getAsTree(metaFormatName); // Find GraphicControlExtension node int nNodes = root.getLength(); for (int j = 0; j < nNodes; j++) { org.w3c.dom.Node node = root.item(j); if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) { // Get delay value String delay = ((IIOMetadataNode)node).getAttribute("delayTime"); // Check if delay is bugged if (Integer.parseInt(delay) == 0) { foundBug = true; } break; } } } if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug); // Load non-bugged GIF the normal way Image image; if (!foundBug) { image = Toolkit.getDefaultToolkit().createImage(f2s(file)); } else { // Prepare streams for image encoding ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); { ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream); try { // Get GIF writer that's compatible with reader ImageWriter writer = ImageIO.getImageWriter(reader); // Give it the stream to encode to writer.setOutput(ios); writer.prepareWriteSequence(null); for (int i = 0; i < numImages; i++) { // Get input image BufferedImage frameIn = reader.read(i); // Get input metadata IIOMetadataNode root = (IIOMetadataNode)reader.getImageMetadata(i).getAsTree(metaFormatName); // Find GraphicControlExtension node int nNodes = root.getLength(); for (int j = 0; j < nNodes; j++) { org.w3c.dom.Node node = root.item(j); if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) { // Get delay value String delay = ((IIOMetadataNode)node).getAttribute("delayTime"); // Check if delay is bugged if (Integer.parseInt(delay) == 0) { // Overwrite with a valid delay value ((IIOMetadataNode)node).setAttribute("delayTime", "10"); } break; } } // Create output metadata IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null); // Copy metadata to output metadata metadata.setFromTree(metadata.getNativeMetadataFormatName(), root); // Create output image IIOImage frameOut = new IIOImage(frameIn, null, metadata); // Encode output image writer.writeToSequence(frameOut, writer.getDefaultWriteParam()); } writer.endWriteSequence(); } finally { _close(ios); }} // Create image using encoded data byte[] data = baoStream.toByteArray(); setVar(loadBufferedImageFixingGIFs_output.get(), data); if (loadBufferedImageFixingGIFs_debug) print("Data size: " + l(data)); image = Toolkit.getDefaultToolkit().createImage(data); } return image; } catch (Exception __e) { throw rethrow(__e); } } static Map myFrames_list = weakHashMap(); static List myFrames() { return swing(new F0>() { public List get() { try { return keysList(myFrames_list); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret keysList(myFrames_list);"; }}); } static IterableIterator iteratorFromFunction_withEndMarker_f0(final F0 f) { class IFF2 extends IterableIterator { A a; boolean have, done; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; have = false; return _a; } void getNext() { if (done || have) return; Object o = f.get(); if (o == iteratorFromFunction_endMarker) { done = true; return; } a = (A) o; have = true; } }; return new IFF2(); } static Map weakHashMap() { return newWeakHashMap(); } static String fromUTF8(byte[] bytes) { return fromUtf8(bytes); } static File remoteMechListMirrorsDir() { return javaxDataDir("Remote Mech Lists"); } static Object[] muricaCredentialsPlus(Object... params) { return concatArrays(muricaCredentials(), params); } static String md5OrNull(String s) { return s == null ? null : md5(s); } static String postPageSilently(String url, Object... params) { return doPostSilently(litmap(params), url); } static Map jsonDecodeMap(String s) { Object o = jsonDecode(s); if (o instanceof List && empty((List) o)) return new HashMap(); if (o instanceof Map) return (Map) o; else throw fail("Not a JSON map: " + s); } static File remoteMechListMirrorMetaFile(String listName) { return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".meta"); } static Map getMultipleKeys(Map map, A... keys) { Map map2 = similarEmptyMap(map); if (map != null) for (A key : keys) map2.put(key, map.get(key)); return map2; } static File remoteMechListMirrorNameFile(String listName) { return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".name"); } static int countLines(String s) { return l(toLines(s)); // yeah could be optimized :-) } static File localMechListFile(String listName) { return newFile(localMechListsDir(), uniqueFileNameUsingMD5_80_v2(listName) + ".text"); } static String htmlencode_forParams(String s) { if (s == null) return ""; StringBuilder out = new StringBuilder(Math.max(16, s.length())); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); /*if (c >= 0x100) out.append("&#x").append(charToHex(c)).append(';'); else*/ if (c > 127 || c == '"' || c == '<' || c == '>') { out.append("&#"); out.append((int) c); out.append(';'); } else out.append(c); } return out.toString(); } static int roundDownTo(int n, int x) { return x/n*n; } static long roundDownTo(long n, long x) { return x/n*n; } 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; // scan for whitespace while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j+2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/")); j = Math.min(j+2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); // cc is not needed in rest of loop body // scan for non-whitespace (json strings, "null" identifier, numbers. everything else automatically becomes a one character token.) 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; } 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; } static String dollarVarsToStars(String s) { return dollarVarsToStars(s, null); } static String dollarVarsToStars(String s, List varNames_out) { List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (isDollarVar(t)) { listAdd(varNames_out, t); tok.set(i, "*"); } else if (eq(t, "*")) listAdd(varNames_out, "*"); } return join(tok); } static Producer javaTokC_iterator(final String s) { return new Producer() { final int l = s.length(); int i = 0; public String next() { if (i >= l) return null; int j = i; char c, d; // scan for whitespace while (j < l) { c = s.charAt(j); d = j+1 >= l ? '\0' : s.charAt(j+1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/")); j = Math.min(j+2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } i = j; if (i >= l) return null; c = s.charAt(i); d = i+1 >= l ? '\0' : s.charAt(i+1); // scan for non-whitespace if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors ++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)); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } 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; String t = quickSubstring(s, i, j); i = j; return t; } }; } static F1 mainFunctionToF1(final String fname) { return new F1() { public Object get(Object a) { try { return callMC(fname, a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callMC(fname, a)"; }}; } static boolean hasLettersAllUpperCase(String s) { return hasLetters(s) && !containsLowerCase(s); } static Rect rect(int x, int y, int w, int h) { return new Rect(x, y, w, h); } static boolean jInternalFrame_iconifiable = true; static JInternalFrame jInternalFrame() { return jInternalFrame(""); } static JInternalFrame jInternalFrame(final String title) { return swing(new F0() { public JInternalFrame get() { try { JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame_iconifiable); f.setVisible(true); return f; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame..."; }}); } static void setInternalFrameContents(final Component c, final Object contents) { { swing(new Runnable() { public void run() { try { JInternalFrame frame = getInternalFrame(c); if (frame == null) return; frame.getContentPane().removeAll(); frame.getContentPane().setLayout(new BorderLayout()); if (contents != null) frame.getContentPane().add(wrap(contents)); revalidate(frame); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JInternalFrame frame = getInternalFrame(c);\r\n if (frame == null) return;\r\n..."; }}); } } static A setBounds(final int x, final int y, final int w, final int h, final A a) { if (a != null) { swing(new Runnable() { public void run() { try { a.setBounds(x, y, w, h); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setBounds(x, y, w, h);"; }}); } return a; } static A setBounds(A a, Rect r) { if (a != null && r != null) { swing(new Runnable() { public void run() { try { a.setBounds(toRectangle(r)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setBounds(toRectangle(r));"; }}); } return a; } static A setBounds(Rect r, A a) { return setBounds(a, r); } static A setBounds(A a, int x, int y, int w, int h) { return setBounds(x, y, w, h, a); } static void internalFrameDefaultPosition(JInternalFrame f) { f.setSize(500, 300); centerInternalFrame(f); } static int fixInternalFrame_borderTopLeft = 0; static int fixInternalFrame_borderBottomRight = 40; // for title bar static JInternalFrame fixInternalFrame(final JInternalFrame f) { return swing(new F0() { public JInternalFrame get() { try { Container c = f.getParent(); if (c == null) return f; Rect r = toRect(f.getBounds()); int a = fixInternalFrame_borderTopLeft, b = fixInternalFrame_borderBottomRight; Rect outer = new Rect(a, a, c.getWidth()-b, c.getHeight()-b); if (!rectContains(outer, r)) f.setLocation( max(a, min(r.x, outer.x2())), max(a, min(r.y, outer.y2()))); if (r.w > c.getWidth() || r.h > c.getHeight()) f.setSize(c.getWidth()-a, c.getHeight()-a); return f; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Container c = f.getParent();\r\n if (c == null) ret f;\r\n Rect r = toRect(..."; }}); } static int getScreenWidth() { return getScreenSize().width; } static int getScreenHeight() { return getScreenSize().height; } static String makeFrame_defaultIcon; static boolean makeFrame_hideConsole = false; static ThreadLocal> makeFrame_post = new ThreadLocal(); static JFrame makeFrame() { return makeFrame((Component) null); } static JFrame makeFrame(Object content) { return makeFrame(programTitle(), content); } static JFrame makeFrame(String title) { return makeFrame(title, null); } static JFrame makeFrame(String title, Object content) { return makeFrame(title, content, true); } static JFrame makeFrame(final String title, final Object content, final boolean showIt) { final VF1 post = optParam(makeFrame_post); return swing(new F0() { public JFrame get() { try { if (getFrame(content) != null) return getFrame(setFrameTitle((Component) content, title)); final JFrame frame = new JFrame(title); if (makeFrame_defaultIcon != null) setFrameIconLater(frame, makeFrame_defaultIcon); _initFrame(frame); Component wrapped = wrap(content); if (wrapped != null) frame.getContentPane().add(wrapped); frame.setBounds(defaultNewFrameBounds()); callF(post, frame); if (showIt) frame.setVisible(true); //callOpt(content, "requestFocus"); //exitOnFrameClose(frame); if (showIt && makeFrame_hideConsole) { hideConsole(); makeFrame_hideConsole = false; } return frame; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (getFrame(content) != null)\r\n ret getFrame(setFrameTitle((Component) ..."; }}); } static boolean frameTooSmall(JFrame frame) { return frame.getWidth() < 100 || frame.getHeight() < 50; } static void frameStandardSize(JFrame frame) { frame.setBounds(300, 100, 500, 400); } static void setFrameContents(final Component c, final Object contents) { swing(new Runnable() { public void run() { try { JFrame frame = getFrame(c); if (frame == null) return; frame.getContentPane().removeAll(); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(wrap(contents)); revalidate(frame); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFrame frame = getFrame(c);\r\n if (frame == null) return;\r\n frame.getContent..."; }}); } static A _recordNewSwingComponent(A c) { if (c != null) callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c); return c; } 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)); } static boolean containsNulls(Collection c) { return contains(c, null); } static void scanForComponents(final Component c, final Class theClass, final List l) { if (theClass.isInstance(c)) l.add((A) c); if (c instanceof Container) { swing(new Runnable() { public void run() { try { for (Component comp : ((Container) c).getComponents()) scanForComponents(comp, theClass, l); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "for (Component comp : ((Container) c).getComponents())\r\n scanForComponen..."; }}); } } static A childOfType(Component c, Class theClass) { return first(childrenOfType(c, theClass)); } static A childOfType(Class theClass, Component c) { return childOfType(c, theClass); } static File standardLogFile() { return getProgramFile("log"); } static void enableWordWrapForTextArea(JTextArea ta) { enableWordWrapForTextArea(ta, true); } static void enableWordWrapForTextArea(JTextArea ta, boolean enabled) { if (ta != null) { swing(new Runnable() { public void run() { try { ta.setLineWrap(enabled); ta.setWrapStyleWord(true); // Haven't found a way to reliable enable word-wrapping for // an already visible text area //revalidate(enclosingScrollPane(ta)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ta.setLineWrap(enabled);\r\n ta.setWrapStyleWord(true);\r\n // Haven't foun..."; }}); } } static JTextArea jtextarea() { return jTextArea(); } static JTextArea jtextarea(String text) { return jTextArea(text); } static byte[] isGIF_magic = bytesFromHex("47494638"); // Actual signature is longer, but we're lazy static boolean isGIF(byte[] data) { return byteArrayStartsWith(data, isGIF_magic); } static boolean isGIF(File f) { return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic))); } static void setVar(IVar v, A value) { if (v != null) v.set(value); } static List keysList(Map map) { return cloneListSynchronizingOn(keys(map), map); } static String doPostSilently(Map urlParameters, String url) { return doPostSilently(makePostData(urlParameters), url); } static String doPostSilently(String urlParameters, String url) { doPost_silently.set(true); return doPost(urlParameters, url); } static File localMechListsDir() { return javaxDataDir("Mech Lists"); } static void listAdd(Collection c, A a) { if (c != null) c.add(a); } static boolean hasLetters(String s) { for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i))) return true; return false; } static boolean containsLowerCase(String s) { for (int i = 0; i < l(s); i++) if (isLowerCase(s.charAt(i))) return true; return false; } static Rectangle toRectangle(Rect r) { return r == null ? null : r.getRectangle(); } static Rect toRect(Rectangle r) { return r == null ? null : new Rect(r); } static Rect toRect(RectangularShape r) { return r == null ? null : toRect(r.getBounds()); } static Rect toRect(Rect r) { return r; } static boolean rectContains(int x1, int y1, int w, int h, Pt p) { return p.x >= x1 && p.y >= y1 && p.x < x1+w && p.y < y1+h; } static boolean rectContains(Rect a, Rect b) { return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2(); } static boolean rectContains(Rect a, int x, int y) { return a != null && a.contains(x, y); } static String programTitle() { return getProgramName(); } static JFrame setFrameIconLater(Component c, final String imageID) { final JFrame frame = getFrame(c); if (frame != null) startThread("Loading Icon", new Runnable() { public void run() { try { final Image i = imageIcon(or2(imageID, "#1005557")).getImage(); swingLater(new Runnable() { public void run() { try { frame.setIconImage(i); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setIconImage(i);"; }}); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n swingL..."; }}); return frame; } static void _initFrame(JFrame f) { myFrames_list.put(f, Boolean.TRUE); standardTitlePopupMenu(f); } static Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400); static Rectangle defaultNewFrameBounds() { return swing(new F0() { public Rectangle get() { try { defaultNewFrameBounds_r.translate(60, 20); if (!screenRectangle().contains(defaultNewFrameBounds_r)) defaultNewFrameBounds_r.setLocation(30+random(30), 20+random(20)); return new Rectangle(defaultNewFrameBounds_r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "defaultNewFrameBounds_r.translate(60, 20);\r\n if (!screenRectangle().contai..."; }}); } static void hideConsole() { final JFrame frame = consoleFrame(); if (frame != null) { autoVMExit(); swingLater(new Runnable() { public void run() { try { frame.setVisible(false); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setVisible(false);"; }}); } } static JTextArea jTextArea() { return jTextArea(""); } static JTextArea jTextArea(final String text) { return jTextAreaWithUndo(text); } static byte[] bytesFromHex(String s) { return hexToBytes(s); } static boolean byteArrayStartsWith(byte[] a, byte[] b) { if (a == null || b == null) return false; if (a.length < b.length) return false; for (int i = 0; i < b.length; i++) if (a[i] != b[i]) return false; return true; } static byte[] loadBeginningOfBinaryFile(File file, int maxBytes) { return loadBinaryFilePart(file, 0, maxBytes); } static boolean isLowerCase(char c) { return Character.isLowerCase(c); } static void standardTitlePopupMenu(final JFrame frame) { // standard right-click behavior on titles if (!isSubstanceLAF()) return; titlePopupMenu(frame, new VF1() { public void get(JPopupMenu menu) { try { boolean alwaysOnTop = frame.isAlwaysOnTop(); menu.add(jmenuItem("Restart Program", "restart")); menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram")); menu.add(jmenuItem("Show Console", "showConsole")); menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() { public void run() { try { toggleAlwaysOnTop(frame) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "toggleAlwaysOnTop(frame)"; }})); /*ifndef standardTitlePopupMenu_noShootWindow { menu.add(jMenuItem("Shoot Window", r { shootWindowGUI_external(frame, 500) })); } endifndef*/ //addMenuItem(menu, "Bigger fonts", f swingBiggerFonts); //addMenuItem(menu, "Smaller fonts", f swingSmallerFonts); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n ifndef standardTitlePopupMenu_..."; }}); } static Rectangle screenRectangle() { return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); } static Rectangle screenRectangle(GraphicsDevice device) { if (device == null) return null; DisplayMode mode = device.getDisplayMode(); return new Rectangle(0, 0, mode.getWidth(), mode.getHeight()); } static JFrame consoleFrame() { return (JFrame) getOpt(get(getJavaX(), "console"), "frame"); } static void autoVMExit() { call(getJavaX(), "autoVMExit"); } static JTextArea jTextAreaWithUndo() { return jTextAreaWithUndo(""); } static JTextArea jTextAreaWithUndo(final String text) { return jenableUndoRedo(swingNu(JTextArea.class, text)); } static byte[] loadBinaryFilePart(File file, long start, long end) { try { RandomAccessFile raf = new RandomAccessFile(file, "r"); int n = toInt(min(raf.length(), end-start)); byte[] buffer = new byte[n]; try { raf.seek(start); raf.readFully(buffer, 0, n); return buffer; } finally { raf.close(); } } catch (Exception __e) { throw rethrow(__e); } } static void duplicateThisProgram() { nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs")))); } static void showConsole() { callOpt(get(javax(), "console"), "showConsole"); } static boolean isSubstanceLAF() { return substanceLookAndFeelEnabled(); } // menuMaker = voidfunc(JPopupMenu) // return true if menu could be added static boolean titlePopupMenu(final Component c, final Object menuMaker) { JComponent titleBar = getTitlePaneComponent(getPossiblyInternalFrame(c)); if (titleBar == null) { print("Can't add title right click!"); return false; } else { componentPopupMenu(titleBar, menuMaker); return true; } } static void toggleAlwaysOnTop(JFrame frame) { frame.setAlwaysOnTop(!frame.isAlwaysOnTop()); } static void nohupJavax(final String javaxargs) { { startThread(new Runnable() { public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs);"; }}); } } static void nohupJavax(final String javaxargs, final String vmArgs) { { startThread(new Runnable() { public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs, vmArgs);"; }}); } } // Try to get the quoting right... static String smartJoin(String[] args) { if (empty(args)) return ""; if (args.length == 1) return args[0]; String[] a = new String[args.length]; for (int i = 0; i < a.length; i++) a[i] = !isJavaIdentifier(args[i]) && !isQuoted(args[i]) ? quote(args[i]) : args[i]; return join(" ", a); } static String smartJoin(List args) { return smartJoin(toStringArray(args)); } static boolean substanceLookAndFeelEnabled() { return startsWith(getLookAndFeel(), "org.pushingpixels."); } static JComponent getTitlePaneComponent(RootPaneContainer window) { if (window instanceof JInternalFrame) return getInternalFrameTitlePaneComponent((JInternalFrame) window); if (!substanceLookAndFeelEnabled() || window == null) return null; JRootPane rootPane = window.getRootPane(); if (rootPane != null) { Object /*SubstanceRootPaneUI*/ ui = rootPane.getUI(); return (JComponent) call(ui, "getTitlePane"); } return null; } static Class hotwireOnce(String programID) { return hotwireCached(programID, false); } static String getLookAndFeel() { return getClassName(UIManager.getLookAndFeel()); } static TreeMap hotwireCached_cache = new TreeMap(); static Lock hotwireCached_lock = lock(); static Class hotwireCached(String programID) { return hotwireCached(programID, true); } static Class hotwireCached(String programID, boolean runMain) { return hotwireCached(programID, runMain, false); } static Class hotwireCached(String programID, boolean runMain, boolean dependent) { Lock __0 = hotwireCached_lock; lock(__0); try { programID = formatSnippetID(programID); Class c = hotwireCached_cache.get(programID); if (c == null) { c = hotwire(programID); if (dependent) makeDependent(c); if (runMain) callMain(c); hotwireCached_cache.put(programID, c); } return c; } finally { unlock(__0); } } static Object makeDependent_postProcess; static void makeDependent(Object c) { if (c == null) return; assertTrue("Not a class", c instanceof Class); dependentClasses(); // cleans up the list hotwire_classes.add(new WeakReference(c)); Object local_log = getOpt(mc(), "local_log"); if (local_log != null) setOpt(c, "local_log", local_log); /*if (isTrue(getOpt(c, 'ping_actions_shareable))) setOpt(c, +ping_actions);*/ Object print_byThread = getOpt(mc(), "print_byThread"); if (print_byThread != null) setOpt(c, "print_byThread", print_byThread); callF(makeDependent_postProcess, c); } static List dependentClasses() { return cleanUpAndGetWeakReferencesList(hotwire_classes); } static List> hotwire_classes = synchroList(); static Class hotwireDependent(String src) { Class c = hotwire(src); makeDependent(c); return c; } static List cleanUpAndGetWeakReferencesList(List> l) { if (l == null) return null; synchronized(l) { List out = new ArrayList(); for (int i = 0; i < l(l); i++) { A a = l.get(i).get(); if (a == null) l.remove(i--); else out.add(a); } return out; } } static abstract class VF3 { abstract void get(A a, B b, C c); }static abstract class VF2 { abstract void get(A a, B b); }static class JSection extends SingleComponentPanel { JSection(Component c) { super(c); } String getTitle() { Border border = getBorder(); if (border instanceof TitledBorder) return ((TitledBorder) border).getTitle(); return null; } } static class LinkedTreeSet extends AbstractSet { Set set; LinkedList list = new LinkedList(); LinkedTreeSet() { set = new TreeSet(); } LinkedTreeSet(Set set) { this.set = set;} public int size() { return list.size(); } public Iterator iterator() { return list.iterator(); } public boolean contains(Object o) { return set.contains(o); } public boolean add(A a) { if (!set.add(a)) return false; { list.add(a); return true; } } // TODO: optimize public boolean remove(Object o) { if (!set.remove(o)) return false; { list.remove(o); return true; } } } static abstract class LiveValue { abstract Class getType(); abstract A get(); abstract void onChange(Runnable l); abstract void removeOnChangeListener(Runnable l); void onChangeAndNow(Runnable l) { onChange(l); callF(l); } }static class Dyn_FieldWatcher { DynModule module; String field; Object value; Runnable action; transient IF1 cloneValue; Object cloneValue(Object o) { return cloneValue != null ? cloneValue.get(o) : cloneValue_base(o); } final Object cloneValue_fallback(IF1 _f, Object o) { return _f != null ? _f.get(o) : cloneValue_base(o); } Object cloneValue_base(Object o) { return o; } Dyn_FieldWatcher(DynModule module, String field, Runnable action) { this(module, field, action, null); } Dyn_FieldWatcher(DynModule module, String field, Runnable action, IF1 cloneValue) { this.cloneValue = cloneValue; this.action = action; this.field = field; this.module = module; value = cloneValue(get(module, field)); // Let's do both for safety module.onChange(new Runnable() { public void run() { try { check(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "check();"; }}); module.onFieldChange(new VF1() { public void get(String f) { try { if (eq(f, field)) check(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(f, field))\r\n check();"; }}); } void check() { Object newValue = cloneValue(get(module, field)); if (eq(value, newValue)) return; value = newValue; dm_q(module, action); } }static abstract class F2 { abstract C get(A a, B b); }static class CancelPoint implements AutoCloseable { volatile boolean closed = false; public void close() { closed = true; } }static class BetterLabel extends JLabel { boolean autoToolTip = true; BetterLabel() { // Listeners given out to componentPopupMenu must not directly // reference the outer object (-> weak map problem). final WeakReference < BetterLabel > me = new WeakReference<>(this); componentPopupMenu(this, BetterLabel_menuItems(me)); } BetterLabel(String text) { this(); this.setText(text); } public void setText(String text) { super.setText(text); if (autoToolTip) if (!swic(text, "")) // HTML labels make super-huge, confusing tool tips setToolTipText(nullIfEmpty(text)); } } // moved outside of class for GC reasons (see above) static VF1 BetterLabel_menuItems(final WeakReference me) { return new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try { copyTextToClipboard(me.get().getText()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(me.get().getText());"; }}); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(me..."; }}; }static class CancelToCancelPoint extends QuickException { CancelPoint cp; CancelToCancelPoint(CancelPoint cp) { this.cp = cp;} }static class ExpiringMap2 extends AbstractMap { Map> byKey = new HashMap(); // key -> pair(expiry sys time, value) PriorityBlockingQueue> queue = new PriorityBlockingQueue(); // queue(pair(expiry sys time, key)) long standardExpiryTime; // ms boolean renewOnOverwrite = true, renewOnGet; Object onChange; // new RestartableCountdown countdown; // TODO ExpiringMap2() {} ExpiringMap2(long standardExpiryTime) { this.standardExpiryTime = standardExpiryTime;} ExpiringMap2(long standardExpiryTime, Object onChange) { this.onChange = onChange; this.standardExpiryTime = standardExpiryTime;} synchronized boolean clean() { boolean changes = false; Pair p; while ((p = queue.peek()) != null && sysTime() >= p.a) { p = queue.poll(); Pair v = byKey.get(p.b); if (v != null /*&& v.a == p.a*/) { byKey.remove(p.b); changes = true; change(); } } return changes; } void change() { callF(onChange); } synchronized public B put(A a, B b) { clean(); long timeout = sysTime()+standardExpiryTime; Pair p = byKey.get(a); if (p != null && renewOnOverwrite) queue.remove(new Pair(p.a, a)); byKey.put(a, pair(timeout, b)); change(); if (p == null || renewOnOverwrite) queue.add(new Pair(timeout, a)); return pairB(p); } synchronized public B remove(Object a) { clean(); Pair p = byKey.get(a); if (p == null) return null; queue.remove(new Pair(p.a, a)); byKey.remove(a); change(); return p.b; } synchronized public B get(Object a) { clean(); Pair p = byKey.get(a); if (renewOnGet && p != null) { queue.remove(new Pair(p.a, a)); long timeout = sysTime()+standardExpiryTime; byKey.put((A) a, pair(timeout, p.b)); queue.add(new Pair(timeout, a)); } return pairB(p); } synchronized public Set> entrySet() { clean(); // TODO: mutex return synchronizedSet(mapValues("pairB", byKey).entrySet()); } synchronized public Set keySet() { clean(); return synchronizedSet(byKey.keySet()); } synchronized public int size() { clean(); return byKey.size(); } void setStandardExpiryTime(long ms) { standardExpiryTime = ms; } synchronized ExpiringMap2 setMap(Map innerMap) { byKey = innerMap; return this; } } static class Lowest { A best; double score; transient Object onChange; synchronized boolean isNewBest(double score) { return best == null || score < this.score; } synchronized double bestScore() { return best == null ? Double.NaN : score; } double score() { return bestScore(); } synchronized float floatScore() { return best == null ? Float.NaN : (float) score; } synchronized float floatScoreOr(float defaultValue) { return best == null ? defaultValue : (float) score; } boolean put(A a, double score) { boolean change = false; synchronized(this) { if (a != null && isNewBest(score)) { best = a; this.score = score; change = true; } } if (change) pcallF(onChange); return change; } synchronized void clear() { best = null; score = 0; } synchronized A get() { return best; } synchronized boolean has() { return best != null; } synchronized Pair pair() { return best == null ? null : new Pair(best, bestScore()); } public String toString() { return "Score " + formatDouble_significant2(score, 4) + ": " + best; } }static interface IVF3 { void get(A a, B b, C c); }static class BasicLogicRule implements IFieldsToList, Transformable, Visitable{ A lhs; A rhs; BasicLogicRule() {} BasicLogicRule(A lhs, A rhs) { this.rhs = rhs; this.lhs = lhs;} public boolean equals(Object o) { if (!(o instanceof BasicLogicRule)) return false; BasicLogicRule __0 = (BasicLogicRule) o; return eq(lhs, __0.lhs) && eq(rhs, __0.rhs); } public int hashCode() { int h = -1439627508; h = boostHashCombine(h, _hashCode(lhs)); h = boostHashCombine(h, _hashCode(rhs)); return h; } public Object[] _fieldsToList() { return new Object[] {lhs, rhs}; } public Object transformUsing(IF1 f) { return new BasicLogicRule((A) f.get(lhs), (A) f.get(rhs)); } public void visitUsing(IVF1 f) { f.get(lhs); f.get(rhs); } Object trail; public String toString() { return lhs + " => " + rhs; } String render() { return toString(); } }static class MechMode implements IFieldsToList{ Object readMode; Object writeMode; MechMode() {} MechMode(Object readMode, Object writeMode) { this.writeMode = writeMode; this.readMode = readMode;} public String toString() { return shortClassName(this) + "(" + readMode + ", " + writeMode + ")"; } public boolean equals(Object o) { if (!(o instanceof MechMode)) return false; MechMode __1 = (MechMode) o; return eq(readMode, __1.readMode) && eq(writeMode, __1.writeMode); } public int hashCode() { int h = -866263200; h = boostHashCombine(h, _hashCode(readMode)); h = boostHashCombine(h, _hashCode(writeMode)); return h; } public Object[] _fieldsToList() { return new Object[] {readMode, writeMode}; } } static class QuickException extends RuntimeException { public Throwable fillInStackTrace() { return this; } QuickException() {} QuickException(Throwable e) { super(e); } QuickException(String msg) { super(msg); } QuickException(String msg, Throwable e) { super(msg, e); } }static class SingleComponentPanel extends JPanel { SingleComponentPanel() { super(new BorderLayout()); } SingleComponentPanel(Component component) { this(); if (component != null) setComponent(component); } void setComponent(final Component component) { { swing(new Runnable() { public void run() { try { removeAll(); if (component != null) add(BorderLayout.CENTER, wrap(component)); _revalidate(SingleComponentPanel.this); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "removeAll();\r\n if (component != null)\r\n add(BorderLayout.CENTER, ..."; }}); } } // Sometimes we need this? void setComponentAndRevalidateParent(Component component) { setComponent(component); _revalidate(_getParent(this)); } void noComponent() { setComponent(null); } Component getComponent() { return getComponentCount() == 0 ? null : getComponent(0); } } static B pairB(Pair p) { return p == null ? null : p.b; } static boolean allLinesAreUnindented(String text) { for (String s : lines(text)) if (startsWithSpace(s)) return false; return true; } static String withoutLinesEmptyAfterTrim(String text) { List lines = filter(lines(text), s -> !emptyAfterTrim(s)); return lines_possiblyRTrim(text, lines); } // leaves lines enclosed in brackets alone static String autoUnindent_honoringBrackets(String s) { List l = lines_honoringBrackets(s); if (empty(l)) return s; // find indent int n = Integer.MAX_VALUE; for (String line : l) n = min(n, getIndentOfLine(line)); if (n == 0) return s; // unindent int _n = n; return lines_possiblyRTrim(s, map(l, line -> substring(line, _n))); } /* e.g. if (x exists): ask (what is x?) else: ask (does x exist?) => a list with two elements input has to be starting at column 1! (call autoUnindent if unsure) */ static List groupPythonStyleIndents_honoringBrackets(String text) { List lines = lines_honoringBrackets(text); List out = new ArrayList(); int startOfBlock = 0; for (int i = 0; i < l(lines); i++) { boolean indented = startsWithSpace(lines.get(i)); if (!indented) { addIfNempty(out, lines_rtrim(subList(lines, startOfBlock, i))); startOfBlock = i; } } addIfNempty(out, lines_rtrim(subList(lines, startOfBlock))); return out; } static String deRoundBracket(String s) { if (startsWith(s, "(") && endsWith(s, ")")) return substring(s, 1, l(s)-1); return s; } static boolean eqGet(List l, int i, Object o) { return eq(get(l, i), o); } static boolean eqGet(Map map, A key, Object o) { return eq(mapGet(map, key), o); } public static String rtrim(String s) { if (s == null) return null; int i = s.length(); while (i > 0 && " \t\r\n".indexOf(s.charAt(i-1)) >= 0) --i; return i < s.length() ? s.substring(0, i) : s; } // rtrims each item static List tok_splitAtEmptyLines(String s) { List indices = new ArrayList(); List tok = javaTokWithAllBrackets_cached(s); List out = new ArrayList(); int start = 0; String spacing = ""; for (int i = 2; i+1 < l(tok); i += 2) { int idx = indexOf_regexp(tok.get(i), "\r?\n\\s*\r?\n"); if (idx < 0) continue; int idx2 = idx+1; if (tok.get(i).charAt(idx) == '\r') ++idx2; out.add(dropPrefix("\n", spacing + joinSubList(tok, start, i))); start = i+1; spacing = substring(tok.get(i), idx2); // TODO: not exact } if (start < l(tok)) out.add(dropPrefix("\n", spacing + joinSubList(tok, start))); return out; } static String joinWithEmptyLines(Iterable l) { return join("\n\n", map("rtrim",l)); } static String joinWithEmptyLines(String... l) { return joinWithEmptyLines(asList(l)); } static boolean isSingleLine(String s) { return !containsNewLine(s); } static Pair, List> filterAntiFilter(Iterable c, Object pred) { List yes = new ArrayList(); List no = new ArrayList(); if (c != null) for (A o : c) (isTrue(callF(pred, o)) ? yes : no).add(o); return pair(yes, no); } static Pair, List> filterAntiFilter(Iterable c, IF1 pred) { return filterAntiFilter(c, (Object) pred); } static Pair, List> filterAntiFilter(IF1 pred, Iterable c) { return filterAntiFilter(c, pred); } static Pair, List> filterAntiFilter(Object pred, Iterable c) { return filterAntiFilter(c, pred); } // currently collection and map only static void pnlStruct(Object o) { if (o instanceof Collection) pnlStruct(((Collection) o)); else if (o instanceof Map) pnlStruct(((Map) o)); else if (o != null) pnlStruct(ll(o)); } static > B pnlStruct(B l) { pnlStruct((Iterable) l); return l; } static Iterable pnlStruct(Iterable l) { return pnlStruct("", l); } static Iterable pnlStruct(String prefix, Iterable l) { int i = 0; if (l != null) for (A a : l) print(prefix + (++i) + ". " + struct_noStringSharing(a)); return l; } static A[] pnlStruct(A[] l) { pnlStruct(asList(l)); return l; } static Map pnlStruct(Map map) { pnl(map(map, new F2() { public Object get(A a, B b) { try { return sfu(a) + " = " + sfu(b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "sfu(a) + \" = \" + sfu(b)"; }})); return map; } static GlobalID aGlobalIDObjUnlessLoading() { return dynamicObjectIsLoading() ? null : aGlobalIDObj(); } static java.awt.Color colorFromHex(String hex) { return awtColor(hex); } 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)"; }}; } static boolean logModuleOutput_installed = false; 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);"; }}); } // discord without opus/JNA //static LS _stickyLibs_discordBot = ll(#1400215); // can cause loader constraint violations 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); } }); } 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.awaitSatus(JDA.Status.CONNECTED); jda.awaitReady(); print("Started Discord bot (token: " + shorten(token, 7) + ")"); return jda; } catch (Exception __e) { throw rethrow(__e); } } static Object[] litmapparams(Object... l) { return new Object[] { litmap(l) }; } static DynModule dm_me() { return dm_current_mandatory(); } static Object dm_discord_lineForMsgID_unimported(long msgID) { return dm_call(dm_gazelle_linesCRUD(), "lineForID", msgID); } static long discord_guildIDFromEvent_gen(Object event) { return rcall_long("getIdLong",rcall("getGuild",event)); } 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))); } 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 __1 = m.enter(); try { return callF(f); } finally { _close(__1); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n ret callF(f);"; }})); } 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 __2 = m.enter(); try { return callF(f); } finally { _close(__2); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n ret callF(f);"; }})); } 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 __3 = m.enter(); try { return callF(f, arg); } finally { _close(__3); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n ret callF(f, arg);"; }})); } static long jda_selfUserID(JDA jda) { return jda.getSelfUser().getIdLong(); } static String dm_gazelle_linesCRUD() { return dm_require("#1021628/GLines"); } static Object[] litobjectarray(Object... l) { return litObjectArray(l); } static String getChannel() { return getChannelName(); } static String shortenForDiscord(String msg) { return shorten(msg, 2000); } static Object dm_pcall(Object moduleOrID, String method, Object... args) { try { return dm_call(moduleOrID, method, args); } catch (Throwable __e) { return null; } } static String gazelle_postedLinesCRUD() { return dm_require("#1022603/GPostedLines"); } static long dm_discord_channelID(String name) { return (long) dm_call(dm_gazelle_linesCRUD(), "getChannelID", name); } static String absoluteURL(String url) { return isAbsoluteURL(url) ? url : "http://" + url; } static IVF1 toIVF1(final Object f) { if (f == null) return null; if (f instanceof IVF1) return (IVF1) f; if (isString(f)) return mainFunctionToIVF1((String) f); return (IVF1) a -> { callF(f, a); }; } static String dm_discord_startKeepAliveModule(Object mod) { String discordToken = (String) (dm_get(mod, "discordToken")); return dm_showNewModuleWithParams("#1024196/DiscordKeepAlive", "discordToken", discordToken); } static JPanel centerAndSouthWithMargins(Component c, Component s) { return applyDefaultMargin(centerAndSouth(c, withTopMargin(s))); } static JPanel jrightalignedline(Component... components) { return jrightAlignedLine(components); } static JPanel jrightalignedline(List components) { return jrightAlignedLine(components); } static JCheckBox dm_fieldCheckBox(String field) { return dm_fieldCheckBox(humanizeFormLabel(field), field); } static JCheckBox dm_fieldCheckBox(String text, String field) { // magic parameter swap :) if (isIdentifier(text) && !isIdentifier(field)) { String temp = field; field = text; text = temp; } return jLiveValueCheckBox(text, dm_fieldLiveValue(field)); } static Border getBorder(final JComponent c) { return c == null ? null : swing(new F0() { public Border get() { try { return c.getBorder(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getBorder();"; }}); } static Q dm_q() { return dm_current_mandatory().q(); } static void dm_q(Runnable r) { dm_inQ(r); } static void dm_q(DynModule module, Runnable r) { module.q().add(r); } static A dm_q(IF0 f) { return dm_evalInQ(if0ToF0(f)); } static long sysTime() { return sysNow(); } static float score(Scored s) { return s == null ? 0 : s.score(); } static String formatDouble_significant2(double d, int digits) { try { digits -= max(0, Math.floor(Math.log10(abs(d))+1)); return formatDouble(d, digits); } catch (Throwable _e) { print("Had number: " + d + ", digits: " + digits); throw rethrow(_e); } } static void setComponent(SingleComponentPanel scp, Component c) { setSCPComponent(scp, c); } static void setComponent(SingleComponentPanel scp, IF0 c) { if (scp != null) setComponent(scp, callF(c)); } static void removeAll(Collection a, Collection b) { if (a != null && b != null) a.removeAll(b); } static void removeAll(Map a, Collection b) { if (a != null && b != null) for (A x : b) a.remove(x); } static Container _getParent(Component c) { return getParent(c); } static boolean startsWithSpace(String s) { return nempty(s) && isSpace(first(s)); } static boolean emptyAfterTrim(String s) { return empty(trim(s)); } static String lines_possiblyRTrim(String originalText, List lines) { return endsWithNewLine(originalText) ? lines(lines) : lines_rtrim(lines); } static int indexOf_regexp(String s, String pat) { Matcher m = compileRegexp(pat).matcher(s); return m.find() ? m.start() : -1; } static boolean dynamicObjectIsLoading() { return isTrue(getThreadLocal(DynamicObject_loading)); } static java.awt.Color awtColor(String hex) { byte[] b = bytesFromHex(dropPrefix("#", hex)); return new Color(ubyteToInt(b[0]), ubyteToInt(b[1]), ubyteToInt(b[2])); } static String vm_cleanForPrint(Object o) { String s = str(o); return or((String) vmBus_query("cleanForPrint", s), s); } static String localDateWithMilliseconds(Date time) { return localDateWithMilliseconds(time.getTime()); } static String localDateWithMilliseconds(long time) { SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss''SSSS"); return format.format(time); } static String localDateWithMilliseconds() { return localDateWithMilliseconds(now()); } static void print_forAllThreads(Object f) { assertNull("todo", print_allThreads); print_allThreads = f; } static String stringPar(Object[] params, String name) { return stringOptPar(params, name); } static String stringPar(String name, Object[] params) { return stringOptPar(params, name); } static String stringPar(String name, Map params) { return (String) optPar(name, params); } static String stringPar(String name, Object[] params, String defaultValue) { return optPar(name, params, defaultValue); } static A assertNempty(A a) { return assertNempty("empty", a); } static A assertNempty(String msg, A a) { if (empty(a)) throw fail(msg + ": " + a); return a; } static String dm_moduleID(Object module) { return strOrNull(getOpt(dm_getStem(module), "id")); } static String dm_moduleID() { return dm_moduleID(dm_current_mandatory_generic()); } // listener: voidfunc(S, O) or func(S, O) 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()); // We're technically violating the one-synchronized-object-per-thread rule, // but it should be OK here. // TODO: remove empty sets from map return tempAdd(listeners, listener); } } // makes dynamic & static modules static String dm_require(String moduleLibID) { return dm_makeModule(moduleLibID); } static Object[] litObjectArray(Object... l) { return l; } static String getChannelName() { return (String) callOpt(getMainBot(), "getChannelName"); } static IVF1 mainFunctionToIVF1(final String fname) { return (IVF1) a -> { callMC(fname, a); }; } 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; } 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..."; }}); } static int withTopMargin_defaultWidth = 6; static JPanel withTopMargin(Component c) { return withTopMargin(withTopMargin_defaultWidth, c); } 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..."; }}); } 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);"; }}); } static JPanel jrightAlignedLine(List components) { return jrightAlignedLine(asArray(Component.class, components)); } static JCheckBox jLiveValueCheckBox(String text, final SimpleLiveValue lv) { final JCheckBox cb = jCheckBox(text); bindCheckBoxToLiveValue(cb, lv); return cb; } static SimpleLiveValue dm_fieldLiveValue(String fieldName) { return dm_fieldLiveValue(dm_current_mandatory(), fieldName); } static SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) { Lock __0 = module.lock; lock(__0); try { AutoCloseable __2 = module.enter(); try { // for dm_watchField Class type = getFieldType(module, fieldName); final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName)); dm_watchField(fieldName, 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 { _close(__2); }} finally { unlock(__0); } } static void dm_inQ(Runnable r) { dm_q().add(r); } static A dm_evalInQ(F0 f) { return dm_evalInQ(dm_current_mandatory(), f); } static A dm_evalInQ(IF0 f) { return dm_evalInQ(dm_current_mandatory(), if0ToF0(f)); } static A dm_evalInQ(DynModule module, F0 f) { return evalInQ(module.q(), f); } static F0 if0ToF0(IF0 f) { return f == null ? null : new F0() { public A get() { try { return f.get(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret f.get();"; }}; } static float abs(float f) { return Math.abs(f); } static int abs(int i) { return Math.abs(i); } static double abs(double d) { return Math.abs(d); } static String formatDouble(double d, int digits) { String format = digits <= 0 ? "0" : "0." + rep(digits, '#'); return decimalFormatEnglish(format, d); } static void setSCPComponent(SingleComponentPanel scp, Component c) { if (scp != null) scp.setComponent(c); } static Container getParent(final Component c) { return c == null ? null : swing(new F0() { public Container get() { try { return c.getParent(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret c.getParent();"; }}); } static boolean isSpace(char c) { return " \t\r\n".indexOf(c) >= 0; } static int ubyteToInt(byte b) { return b & 0x0FF; } // makes dynamic & static modules - returns module ID static String dm_makeModule(String moduleLibID) { return (String) dm_callOS("makeModule", moduleLibID); } static JCheckBox jCheckBox() { return swingNu(JCheckBox.class); } static JCheckBox jCheckBox(boolean checked) { return swingNu(JCheckBox.class, "", checked); } static JCheckBox jCheckBox(String text, boolean checked) { return swingNu(JCheckBox.class, text, checked); } static JCheckBox jCheckBox(String text) { return swingNu(JCheckBox.class, text); } static JCheckBox jCheckBox(String text, boolean checked, final Object onChange) { JCheckBox cb = jCheckBox(checked, onChange); cb.setText(text); return cb; } // onChange can be a Runnable or a voidfunc(bool) 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; } 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; } static Class getFieldType(Object o, String field) { return fieldType(o, field); } static A evalInQ(Q q, final F0 f) { if (isInQ(q)) return callF(f); final Var> var = new Var(); q.add(new Runnable() { public void run() { try { try { var.set(main. eitherA(callF(f))); } catch (Throwable e) { var.set(main. eitherB(e)); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n var.set(main. eitherA(callF(f)));\r\n } catch (Th..."; }}); return returnOrThrow_either(waitForVarToBeNotNull(var)); } static String decimalFormatEnglish(String format, double d) { return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d); } static void setChecked(JCheckBox checkBox, 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);"; }}); } } static void setChecked(JCheckBoxMenuItem mi, boolean b) { if (mi != null) { swing(new Runnable() { public void run() { try { mi.setSelected(b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "mi.setSelected(b);"; }}); } } static boolean isInQ(Q q) { return q != null && isCurrentThread(q.rst.thread); } static Either eitherA(A a) { return new Either(1, a); } static Either eitherB(B b) { return new Either(2, b); } static A returnOrThrow_either(Either e) { if (isEitherB(e)) throw rethrow(e.b()); return eitherAOpt(e); } static A waitForVarToBeNotNull(Var v) { try { synchronized(v) { while (!v.has()) v.wait(); return v.get(); } } catch (Exception __e) { throw rethrow(__e); } } static boolean isCurrentThread(Thread t) { return t != null && t == currentThread(); } static boolean isEitherB(Either e) { return eitherIsB(e); } static A eitherAOpt(Either e) { return e != null && e.isA() ? e.a() : null; } static boolean eitherIsB(Either e) { return e != null && e.isB(); } static class SimpleLiveValue extends LiveValue { Class type; volatile A value; transient List onChange = synchroList(); SimpleLiveValue(Class type) { this.type = type;} 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); } void fireChanged() { pcallFAll(onChange); } void set(A a) { if (neq(value, a)) { value = a; fireChanged(); } } }static class LineBuffer { VF1 onLine; StringBuilder currentLine = new StringBuilder(); LineBuffer() {} LineBuffer(VF1 onLine) { this.onLine = onLine;} void append(String s) { append(s, onLine); } 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)); } } int size() { return l(currentLine); } }static class Either { byte which; Object value; Either() {} Either(int which, Object value) { this.which = (byte) which; this.value = value; } boolean isA() { return which == 1; } boolean isB() { return which == 2; } A a() { if (which != 1) _failMe(); return (A) value; } B b() { if (which != 2) _failMe(); return (B) value; } A aOpt() { return which != 1 ? null : (A) value; } B bOpt() { return which != 2 ? null : (B) value; } void _failMe() { throw fail("Either object is of wrong type: " + shortClassName(value)); } public String toString() { return "Either" + (isA() ? "A" : "B") + "(" + value + ")"; } }static class Scored extends Var { float score; Scored() {} Scored(A a, float score) { super(a); this.score = score; } Scored(A a, double score) { super(a); this.score = (float) score; } float score() { return score; } public String toString() { return toIntPercent(score) + "%: " + str(get()); } }static class RightAlignedLine extends JPanel { RightAlignedLine(Component... components) { setLayout(LetterLayout.rightAlignedRow()); for (Component component : components) add(component); } public void add(String text) { add(new JLabel(text)); } } static class LetterLayout implements LayoutManager { private String[] lines; private Map map = new TreeMap(); private RC[] rows; private RC[] cols; private Cell[][] cells; private int spacingX = 10, spacingY = 10; private int insetTop, insetBottom, insetLeft, insetRight; private int template; private boolean formWideLeftSide, formWideRightSide; private static final int STALACTITE = 1, LEFT_ALIGNED_ROW = 2, CENTERED_ROW = 3, FORM = 4, RIGHT_ALIGNED_ROW = 5; private boolean debug = false; public void setLeftBorder(int border) { insetLeft = border; } public void setRightBorder(int border) { insetRight = border; } public static JComponent withBorder(JComponent component, int border) { JPanel panel = new JPanel(new LetterLayout("C").setBorder(border)); panel.add("C", component); return panel; } public static JPanel panel(String... lines) { return new JPanel(new LetterLayout(lines)); } public static JPanel stalactitePanel() { return new JPanel(stalactite()); } static class DummyComponent extends JComponent { } /** * info about one matrix cell */ static class Cell { boolean aux = false; // part of a larger cell, but not top-left corner int minWidth, minHeight; Component component; int colspan, rowspan; double weightX, weightY; } /** * info about one matrix row / column */ static class RC { int min; double weightSum; int start; int minEnd; } private 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); // do layout 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; } } } } private 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(); // define cells 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; } } // determine minStarts, weightSums 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; } // determine row, col starts 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); } private boolean allWeightsZero(RC[] rcs) { for (int i = 0; i < rcs.length; i++) if (rcs[i].weightSum != 0.0) return false; return true; } private static int getMinimumHeight(Component c) { /*if (c instanceof JTextArea) { return (int) ((JTextArea) c).getUI().getRootView((JTextArea) c).getPreferredSpan(javax.swing.text.View.Y_AXIS); }*/ return c.getMinimumSize().height; } private 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) { /* old method of calculating numRows: int numRows = 0; for (String key : map.keySet()) { if (key.length() == 1) numRows = Math.max(numRows, Character.toLowerCase(key.charAt(0))-'a'); }*/ 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) }; } } private 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(); } private 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; //System.out.println("totalSize="+totalSize+",minTotal="+minTotal+",weightSum="+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; //System.out.println("i="+i+",prevws="+prevWeightSum+",ws="+rcs[i].weightSum+",min="+rcs[i].min+",width="+width); 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; } private 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; } /** * layout components from top to bottom; add components without letters! */ public static LetterLayout stalactite() { return new LetterLayout(STALACTITE); } /** * layout components from left to right; add components without letters! */ public static LetterLayout leftAlignedRow() { return new LetterLayout(LEFT_ALIGNED_ROW); } public static LetterLayout leftAlignedRow(int spacing) { return leftAlignedRow().setSpacing(spacing); } /** * layout components from left to right, center in container; add components without letters! */ 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); } private static JPanel makePanel(LetterLayout letterLayout, JComponent[] components) { JPanel panel = new JPanel(letterLayout); for (JComponent component : components) { panel.add(component); } return panel; } /** * layout components from top to bottom; two components per row */ public static LetterLayout form() { LetterLayout letterLayout = new LetterLayout(FORM); letterLayout.formWideLeftSide = true; letterLayout.formWideRightSide = true; return letterLayout; } /** * layout components from top to bottom; two components per row * left column is small, right column is wide */ public static LetterLayout formWideRightSide() { LetterLayout letterLayout = new LetterLayout(FORM); letterLayout.formWideRightSide = true; return letterLayout; } public static Component getDummyComponent() { return new DummyComponent(); } public static JPanel newPanel(String... lines) { return new JPanel(new LetterLayout(lines)); } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public static char makeIndexChar(int idx) { return (char) ('a' + idx*2); } public static char makeAlternateIndexChar(int idx) { return (char) ('b' + idx*2); } public static char LEFT_CHAR = ',', RIGHT_CHAR = '.'; public static void main(String[] args) { System.out.println((int) makeIndexChar(0)); System.out.println((int) makeAlternateIndexChar(0)); System.out.println((int) makeIndexChar(32000)); System.out.println((int) makeAlternateIndexChar(32000)); System.out.println((int) LEFT_CHAR); System.out.println((int) RIGHT_CHAR); } } static String dropTrailingBackslashR(String s) { int i = l(s); while (i > 0 && s.charAt(i-1) == '\r') --i; return substring(s, 0, i); } static String b(Object contents, Object... params) { return tag("b", contents, params); } static boolean isA(Either e) { return eitherIsA(e); } static int toIntPercent(double ratio) { return roundToInt(ratio*100); } // when used with map function static int toIntPercent(float ratio) { return toIntPercent((double) ratio); } static String tag(String tag) { return htag(tag); } static String tag(String tag, Object contents, Object... params) { return htag(tag, str(contents), params); } static String tag(String tag, StringBuilder contents, Object... params) { return htag(tag, contents, params); } static String tag(String tag, StringBuffer contents, Object... params) { return htag(tag, contents, params); } static boolean eitherIsA(Either e) { return e != null && e.isA(); } static int roundToInt(double d) { return (int) Math.round(d); } static String htag(String tag) { return htag(tag, ""); } static String htag(String tag, Object contents, Object... params) { String openingTag = hopeningTag(tag, params); String s = str(contents); if (empty(s) && neqic(tag, "script")) return dropLast(openingTag) + "/>"; return openingTag + s + ""; } }