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 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 javax.swing.event.AncestorListener; import javax.swing.event.AncestorEvent; import javax.swing.Timer; public class main { static class GenTesting { Object makeGenerators; // voidfunc(L gens, L log) // method to compare generator output & user line String comparison = "eqic"; GenTesting(Object makeGenerators) { this.makeGenerators = makeGenerators;} MultiSet scoreGenerators(List log) { return scoreGenerators(log, null); } MultiSet scoreGenerators(List log, BitSet interestingLines) { MultiSet scores = new MultiSet(); for (int i = 0; i < l(log); i++) if (interestingLines == null || interestingLines.get(i)) scoreGenerators1(subList(log, 0, i+1), scores); print(/*asciiHeading2("SCORES")*/); for (String name : scores.getTopTen()) print(" [" + scores.get(name) + "] " + name); print(); return scores; } void scoreGenerators1(List log, MultiSet scores) { if (empty(log)) return; String line = last(log); log = dropLast(log); genLog_set(log); try { List gens = makeGenerators(log); for (Gen gen : gens) { try { if (compare(callGen(gen), line)) scores.add(gen.name); } catch (Throwable _e) {} } } finally { genLog_clear(); } } String callSingle(List log, Object genName) { genLog_set(log); try { List gens = makeGenerators(log); Gen gen = findByField(gens, "name", genName); if (gen == null) return null; return callGen(gen); } finally { genLog_clear(); } } boolean verifySingle(List log, Object genName) { if (empty(log)) return false; String line = last(log); log = dropLast(log); genLog_set(log); try { List gens = makeGenerators(log); Gen gen = findByField(gens, "name", genName); if (gen == null) return false; try { if (compare(callGen(gen), line)) return true; } catch (Throwable _e) {} return false; } finally { genLog_clear(); } } List makeGenerators(List log) { List gens = new ArrayList(); callF(makeGenerators, gens, log); return gens; } // returns score int scoreGenerator(List log, String genName) { int score = 0; for (int i = 1; i < l(log); i++) { String expect = log.get(i), s = null; boolean ok = false; try { s = callSingle(subList(log, 0, i), genName); ok = compare(s, expect); } catch (Throwable e) { s = exceptionToStringShort(e); } if (ok) { ++score; print(genName + " OK: " + s + (eq(s, expect) ? "" : " / " + expect)); } else print(genName + " NO [" + s + "]: " + expect); } print(); return score; } boolean compare(String a, String b) { if (eq(comparison, "eq")) return eq(a, b); else if (eq(comparison, "eqic")) return eqic(a, b); else if (eq(comparison, "match")) return match(a, b); else throw fail("Unknown comparison: " + comparison); } // run a single generator on all lines and print each line void debugSingle(List log, String name) { for (int i = 0; i < l(log); i++) debugSingle1(subList(log, 0, i+1), name); } void debugSingle1(List log, String genName) { String line = last(log); log = dropLast(log); genLog_set(log); try { List gens = makeGenerators(log); Gen gen = findByField(gens, "name", genName); if (gen == null) return; boolean ok = false; try { ok = compare(callGen(gen), line); } catch (Throwable _e) {} print((ok ? "OK" : "NO") + " " + line); } finally { genLog_clear(); } } } // GenTesting static class Thinker { List ranking = synchroList(); int listMakingTimeout = 2000; int maxListLength = 100; boolean showExceptions, debug; volatile int load; void startUp(List log) { readLocally2(this, "ranking"); print("Ranking: " + structure(ranking)); } MultiSet scores(List log) { return makeGT().scoreGenerators(log); } MultiSet scores(List log, BitSet interestingLines) { return makeGT().scoreGenerators(log, interestingLines); } GenTesting makeGT() { return new GenTesting(new Object() { void get(List gens, List log) { makeGenerators(gens); } public String toString() { return "makeGenerators(gens);"; }}); } // also called from outside void recommendSolver(String solverID) { if (!isRecommendedSolver(solverID = fsi(solverID))) { print("Adding recommended solver: " + solverID); logQuoted("recommendations.txt", solverID); } else print("Solver already recommended: " + solverID); } boolean isRecommendedSolver(String solverID) { return contains(scanLog("recommendations.txt"), fsI(solverID)); } // log = what's in the chat // input = what user is typing void makeListData(List thelog, String input, List> otherLogs, List l) { long started = now(); try { long timeout = started + listMakingTimeout; HashMap seen = new HashMap(); // maps to the line // extended log including what user is typing List xlog = listPlus(thelog, input); // Make generators for both modes List gens = new ArrayList(); for (boolean completing : ll(false, true)) { List gens_ = new ArrayList(); try { genLog_set(completing ? xlog : log); gOtherLogs_set(otherLogs); gCompleting_set(completing); makeGenerators(gens_); for (Gen g : gens_) gens.add(new Gen(g.name + gMode(), g.func)); } finally { genLog_clear(); gOtherLogs_clear(); gCompleting_set(null); } } // Rank all generators gens = rankGenerators(gens); // Produce list int i = -1; while (now() < timeout && l(l) < maxListLength && nempty(gens)) { i = (i+1) % l(gens); Gen gen = gens.get(i); boolean completing = gen.name.endsWith("/i"); try { genLog_set(completing ? xlog : log); gOtherLogs_set(otherLogs); gCompleting_set(completing); boolean remove = false; if (debug) print("Trying generator " + gen.name); try { String s = callGen(gen); if (empty(s) /*|| eq(input, s)*/) remove = true; else if (seen.containsKey(s)) { Map line = seen.get(s); setAdd((List) line.get("Suggesters"), gen.name); remove = true; } else { Map line = litorderedmap("Suggestion", s, "Suggesters", ll(gen.name)); l.add(line); seen.put(s, line); } } catch (Throwable e) { if (showExceptions) l.add(litorderedmap("Suggestion", "[error] " + exceptionToStringShort(e), "Suggesters", ll(gen.name))); remove = true; } if (remove) gens.remove(i--); } finally { genLog_clear(); gOtherLogs_clear(); gCompleting_set(null); } } } catch (Throwable e) { printStackTrace(e); l.add(e.toString()); } finally { load = (int) ((now()-started)*100/listMakingTimeout); } } List rankGenerators(List gens) { Map index = indexByField(gens, "name"); List l = new ArrayList(); List rank = cloneList(ranking); for (String name : rank) { Gen g = index.get(name); if (g != null) { l.add(g); index.remove(name); } } l.addAll(values(index)); // add rest in unspecified order //print("Using ranking: " + struct(rank)); //print("Ranked generators: " + struct(l)); return l; } void rankToTop(String name) { if (empty(name)) return; if (eq(first(ranking), name)) return; ranking.remove(name); ranking.add(0, name); saveLocally2(this, "ranking"); print("New ranking: " + structure(ranking)); } } // Thinker static boolean assisting; static String generatorsID; static JFrame frame; static JTable table, chatTable; //static JTextArea chat; static JTextField input; static List log = synchroList(); static List recommendations; static List thinkThreads = synchroList(); static JLabel status; static String lastInput; static Map matchingSuggestion; static Map> allLogs = synchroMap(); static JFrame analyzersFrame; static String dialogImageID; static JFrame dialogImageFrame; static int listDelay = 2000; static int maxLineLength = 1000; static int maxLongStringLength = 100*1000; static Boolean thinking; static Thinker thinker = new Thinker(); static boolean showCPU = true; static String systemPrefix = "[system]"; static String dialog = "new"; static void randomMain() { //substanceLAF("EmeraldDusk"); // Too dark! //substanceLAF("ChallengerDeep"); // So purple! //substance("MistAqua"); substance("Moderate"); table = tableWithTooltips(); //chat = autoScroll(wordWrapTextArea()); chatTable = tableWithTooltips(); input = new JTextField(); status = new JLabel(" "); String title = assisting ? "Assistance - " + autoFrameTitle() : autoFrameTitle(); frame = showFrame(title, vgrid(centerAndSouth( //jtabs(1, "Chat", chat, "Details", chatTable), chatTable, input), centerAndSouth(table, status))); //setFrameIconLater(frame, "#1003593"); addMenu(frame, "Random", "Delete last line (!delete)", new Runnable() { public void run() { try { post("!delete"); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}, "Reload generators (!gen)", new Runnable() { public void run() { try { post("!gen"); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}, "Restart app (!restart)", new Runnable() { public void run() { try { post("!restart"); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}, "Restart Java engine (!fresh)", new Runnable() { public void run() { try { post("!fresh"); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}, "Execute Java code (!j ...)", new Runnable() { public void run() { try { setInput("!j 1+2"); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}, "Switch dialog (!dialog ...)", new Runnable() { public void run() { try { setInput("!dialog bla"); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}, "Restore last input", new Runnable() { public void run() { try { if (nempty(lastInput)) setInput(lastInput); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}, "Show raw dialog", new Runnable() { public void run() { try { showText("Raw Dialog", rawDialog()); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); makeDialogsMenu(); onEnter(input, new Runnable() { public void run() { try { post(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); onDoubleClick(table, new Object() { void get(int row) { chooseSuggestion(row); } public String toString() { return "chooseSuggestion(row);"; }}); for (int i = 1; i <= 12; i++) { final int _i = i; registerFunctionKey(frame, i, new Runnable() { public void run() { try { chooseSuggestionForEditing(_i-1); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); registerShiftFunctionKey(frame, i, new Runnable() { public void run() { try { chooseSuggestion(_i-1); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); registerCtrlFunctionKey(frame, i, new Runnable() { public void run() { try { // post user input and then choose suggestion for editing Map map = getTableLineAsMap(table, _i-1); if (map == null) return; rankToTop(map); String s = trim(unnull(map.get("Suggestion"))); logEvent("Suggestion chosen for editing with pre-post", mapPlus(map, "Row", _i, "Input", getInput(), "Top Suggesters", topSuggesters())); post(); setInput(s); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } onDoubleClickOrEnter(chatTable, new Object() { void get(int row) { List line = getTableLine(chatTable, row); if (line != null) setInput(getString(line, 0)); } public String toString() { return "L line = getTableLine(chatTable, row);\r\n if (line != null)\r\n setInput(getString(line, 0));"; }}); onUpdate(input, new Runnable() { public void run() { try { updateOnce(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); loadDialog(); logEvent("Starting"); updateOnce(); input.requestFocus(); if (isAction(last(log)) && confirmYesNo(input, "Run action? " + last(log))) action(last(log)); } static String getInput() { return joinLines(" # ", input.getText().trim()); } static void post() { postAsUser(getInput(), null); } static void postAsUser(String i, Map infos) { if (inputAllowedByUser(i)) post(i, infos); } static void chooseSuggestionForEditing(int row) { Map map = getTableLineAsMap(table, row); if (map == null) return; rankToTop(map); String s = trim(unnull(map.get("Suggestion"))); logEvent("Suggestion chosen for editing", mapPlus(map, "Row", row+1, "Input", getInput(), "Top Suggesters", topSuggesters())); setInput(s); } static void setInput(final String s) { swingNowOrLater(new Runnable() { public void run() { try { lastInput = input.getText(); input.setText(s); input.selectAll(); input.requestFocus(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static void rankToTop(Map map) { rankToTop(map, false); } static void rankToTop(Map map, boolean removeISuggesters) { if (map == null) return; Object s = map.get("Suggesters"); // Table cells have been structure'd by dataToTable List sugg = s instanceof List ? (List) s : (List) unstructure((String) s); // These are cheaters! if (removeISuggesters) sugg = rejectWhere(new Object() { Object get(String s) { return s.endsWith("/i") ; } public String toString() { return "s.endsWith(\"/i\")"; }}, sugg); thinker.rankToTop(first(sugg)); } static void chooseSuggestion(int row) { Map map = getTableLineAsMap(table, row); if (map == null) return; rankToTop(map); String s = trim(unnull(map.get("Suggestion"))); if (empty(s)) return; //logEvent("Suggestion chosen", mapPlus(map, "Row", row+1, "Input", getInput(), "Top Suggesters", topSuggesters)); setInput(s); postAsUser(s, mapPlus(map, "Index", row+1)); } static List topSuggesters() { int n = 20; n = min(n, tableRows(table)); List topSuggesters = new ArrayList(); for (int i = 0; i < n; i++) topSuggesters.add(getTableLineAsMap(table, i)); //if (empty(topSuggesters)) topSuggesters = null; return topSuggesters; } static void logEvent(String type) { logEvent(type, litmap()); } static void logEvent(String type, Map map) { logStructure(new File(dialogDir(), "event.log"), ll(type, chatTime(), map)); } static boolean inputAllowedByUser(String i) { return !swic(i, systemPrefix); } // may be called from other thread static void postSystemMessage(final String msg) { if (empty(msg)) return; swingNowOrLater(new Runnable() { public void run() { try { post(systemPrefix + " " + msg, litmap("By", "System")); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static void post(String i) { post(i, null); } static void post(String i, Map infos) { try { i = trim(i); if (empty(i)) return; //i = escapeNewLines(i); if (infos == null) { infos = matchingSuggestion; if (infos != null) print("Ranking to top: " + struct(infos)); rankToTop(infos, true); } infos = mapPlus(infos, "Top Suggesters", topSuggesters()); boolean tooLong = l(i) > maxLongStringLength; if (l(i) > maxLineLength) { String id = saveLongString(i); i = substring(i, 0, maxLineLength) + "... [" + (tooLong ? "too " : "") + "long text " + id + "]"; } } catch (Throwable e) { printStackTrace(e); i = systemPrefix + " " + exceptionToStringShort(e); } String s = i + "\n"; //chat.append(escapeNewLines(i) + "\n"); appendToFile(logFile(), "[" + chatTime() + "] " + s); logEvent("Posting", litmap("Text", i, "Infos", infos)); log.add(i); updateChatTable(); input.selectAll(); updateOnce(); try { action(i); } catch (Throwable e) { printStackTrace(e); postSystemMessage(exceptionToStringShort(e)); } } static String dropActionPrefix(String s) { if (s == null) return null; s = dropBracketPrefix(s); // e.g. "[bot]" if (!s.startsWith("!")) return null; return s.substring(1); } static boolean isAction(String s) { return dropActionPrefix(s) != null; } static void action(String s) { s = dropActionPrefix(s); if (s == null) return; final String _s = s; { /*nt*/ Thread _t_0 = new Thread("Action") { public void run() { /* in run */ try { /* pcall 1*/ /* in thread */ JWindow _loading_window = showLoadingAnimation(); try { genLog_set(getLog()); // 'case user needs it gOtherLogs_set(getOtherLogs()); // ditto randomsOwnCmds(_s); systemCommands(_s, mc()); } catch (Throwable e) { printStackTrace(e); postSystemMessage("Error - " + exceptionToStringShort(e)); } finally { genLog_clear(); gOtherLogs_clear(); disposeWindow(_loading_window); } /* in thread */ /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } /* in run */ } }; _t_0.start(); } } static volatile boolean again; // This logic is bad... static void fillList(boolean force) { boolean t = force || shouldUpdateList(); if (neq(t, thinking)) { thinking = t; setFrameIcon(table, t ? "#1003603" : "#1003593"); } if (!t) { if (!force) againl8r(); } else { if (nempty(thinkThreads)) { again = true; return; } fillListImpl(); } } static void addKeys(List data) { for (int i = 0; i < l(data); i++) { int k = i+1; String key = k <= 12 ? "F" + k : null; Map m = litorderedmap("Key", key); m.putAll(data.get(i)); data.set(i, m); } } static void removeMatchingLine(List data) { String input = getInput(); matchingSuggestion = null; for (int i = 0; i < l(data); i++) if (eq(input, data.get(i).get("Suggestion"))) { matchingSuggestion = mapPlus(data.get(i), "Index", i+1); data.remove(i); return; } } static void fillListImpl() { { /*nt*/ Thread _t_1 = new Thread("Fill List") { public void run() { /* in run */ try { /* pcall 1*/ /* in thread */ try { thinkThreads.add(currentThread()); final List data = new ArrayList(); thinker.makeListData(cloneList(log), getInput(), getOtherLogs(), data); swingLater(new Runnable() { public void run() { try { try { /* pcall 1*/ removeMatchingLine(data); addKeys(data); dataToTable_uneditable(table, data); tableColumnMaxWidth(table, 0, 30); // "Key" column /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } againl8r(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } finally { thinkThreads.remove(currentThread()); if (again) { again = false; fillListImpl(); } } /* in thread */ /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } /* in run */ } }; _t_1.start(); } } static void updateOnce() { fillList(true); } static void againl8r() { swingAfter(table, listDelay, new Runnable() { public void run() { try { fillList(false); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static boolean shouldUpdateList() { boolean result = false; String text = " "; if (getFrame(table).isFocused()) { result = !mouseInComponent(table); text = result ? " Thinking..." + (showCPU /*&& thinker.load != 0*/ ? " (" + thinker.load + "% CPU)" : "") : "Not thinking cause you got the mouse in there"; } status.setText(text); return result; } // also called from outside static List loadLog() { log.clear(); log.addAll(scanEventLogForText(dialogDir())); return log; } static void loadAllLogs() { allLogs.clear(); for (File f : findAllFiles(getProgramDir())) if (f.getName().equals("event.log")) allLogs.put(f.getParentFile().getName(), new ImmL(scanEventLogForText(f))); } synchronized static List getLastFromLog(int n) { return cloneList(getLast(log, n)); } synchronized static List getLog() { return cloneList(log); } static File dialogDir() { return prepareProgramFile(dialog); } static File logFile() { return new File(dialogDir(), "log.txt"); } static void switchDialog(final String name) { swingAndWait(new Runnable() { public void run() { try { dialog = name; touchFile(new File(dialogDir(), "event.log")); loadDialog(); loadAllLogs(); makeDialogsMenu(); setFrameTitle(dialog + " - " + getProgramTitle()); // show special stuff for dialog, like an image dialogImageID = trim(readTextFile(new File(dialogDir(), "image-id.txt"))); showDialogImage(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static void loadDialog() { loadLog(); thinker = new Thinker(); thinker.startUp(log); //chat.setText(joinLines(log)); updateChatTable(); } static void randomsOwnCmds(String s) { Matches m = new Matches(); if (match("dialog *", s, m)) { switchDialog(m.unq(0)); // TODO: show current dialog somewhere else //postSystemMessage("OK, dialog switched to " + quote(dialog)); } if (match("gen", s, m)) generators = null; if (match("delete", s, m)) updateChatTable(); if (match("analyzers", s, m)) showAnalyzers(); if (matchOneOf(s, m, "img *", "image *")) { String imageID = m.fsi(0); saveTextFile(new File(dialogDir(), "image-id.txt"), imageID); dialogImageID = imageID; showDialogImage(); } if (matchOneOf(s, m, "img", "image")) { if (empty(dialogImageID)) postSystemMessage("No image set for this dialog"); else postSystemMessage("Image for this dialog: " + fsI(dialogImageID)); } } static void showAnalyzers() { if (analyzersFrame == null) analyzersFrame = showFrame("Analyzers"); } static void updateChatTable() { swingNowOrLater(new Runnable() { public void run() { try { List data = new ArrayList(); List l = scanLog_safeUnstructure(new File(dialogDir(), "event.log")); for (int i = 0; i < l(l); i++) try { /* pcall 1*/ List a = l.get(i), prev = get(l, i-1); if (firstIs(a, "Posting")) { Map map = (Map) ( get(a, 2)); String text = getString(map, "Text").trim(); if (eq(text, "!delete")) { removeLast(data); continue; } String idx = ""; Map infos = (Map) ( map.get("Infos")); if (infos != null && infos.containsKey("Index")) idx = str(infos.get("Index")); else try { /* pcall 1*/ //printStruct("prev: ", prev); if (prev != null && firstIs(prev, "Suggestion chosen for editing")) { Map m = getMap(prev, 2); String suggestion = getString(m, "Suggestion"); //print("Suggestion: " + structure(suggestion)); idx = str(get(m, "Row")); if (neq(suggestion, text)) idx += "?"; } /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } data.add(litorderedmap("Text", escapeNewLines(text), "Sugg." /* Suggestion Index */, idx)); } /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } dataToTable_uneditable(chatTable, data); tableColumnMaxWidth(chatTable, 1, 40); // enough for 2 digits and a "?" scrollTableDownIn(chatTable, 50); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static synchronized String saveLongString(String s) { s = substring(s, 0, maxLongStringLength); String id; File f; do { id = randomID(10); f = getProgramFile("long-strings/" + id); } while (f.exists()); saveTextFile(f, s); return id; } static Object generators; static void makeGenerators(List l) { synchronized(main.class) { if (!isSnippetID(generatorsID)) throw fail("No generators ID set"); if (generators == null) generators = hotwire(generatorsID); } List l2 = new ArrayList(); callOpt(generators, "makeGenerators", l2); callOpt(generators, "deterministicGenerators", l2); l.addAll((List) quickImport(l2)); } static String rawDialog() { return fromLines(log); } static void makeDialogsMenu() { List items = new ArrayList(); for (File dir : listDirs(getProgramDir())) if (containsFile(dir, "event.log")) { final String dialog = dir.getName(); items.add(dialog); items.add(new Runnable() { public void run() { try { switchDialog(dialog); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } addMenu(frame, "Dialogs", items); } static List> getOtherLogs() { // TODO: sort by latest or smth? return valuesList(mapMinus(allLogs, dialog)); } static void hideDialogImage() { if (dialogImageFrame != null) { disposeFrame(dialogImageFrame); dialogImageFrame = null; } } static void showDialogImage() { hideDialogImage(); if (nempty(dialogImageID)) { String title = getSnippetTitle(dialogImageID) + " [" + fsI(dialogImageID) + "/" + dialog + "]"; dialogImageFrame = getFrame(showImage(dialogImageID, title)); } } // Random Main v9 public static void main(String[] args) throws Exception { swingLater(new Runnable() { public void run() { try { generatorsID = "#1004039"; randomMain(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}});} static String struct(Object o) { return structure(o); } static JTextArea showText(final String title, final String text) { return (JTextArea) swingAndWait(new Object() { Object get() { JTextArea textArea = newTypeWriterTextArea(text); makeFrame(title, new JScrollPane(textArea)); return textArea; } public String toString() { return "JTextArea textArea = newTypeWriterTextArea(text);\r\n makeFrame(title, new JScrollPane(textArea));\r\n ret textArea;"; }}); } static JTextArea showText(Object text) { return showText(str(text)); } static JTextArea showText(String text) { return showText(autoFrameTitle(), text); } static Object callF(Object f, Object... args) { return callFunction(f, args); } static String showImage_defaultIcon = "#1004230"; // "#1004227"; static ImageSurface showImage(String snippetIDOrURL, String title) { return showImage(loadImage(snippetIDOrURL), title); } static ImageSurface showImage(final BufferedImage img, final String title) { return (ImageSurface) swing(new Object() { Object get() { ImageSurface is = showImage(img); getFrame(is).setTitle(title); return is; } public String toString() { return "ImageSurface is = showImage(img);\r\n getFrame(is).setTitle(title);\r\n return is;"; }}); } static ImageSurface showImage(final BufferedImage img) { return (ImageSurface) swing(new Object() { Object get() { ImageSurface is = new ImageSurface(img); JFrame frame = showPackedFrame(new JScrollPane(is)); moveToTopRightCorner(frame); frameIcon(frame, showImage_defaultIcon); return is; } public String toString() { return "ImageSurface is = new ImageSurface(img);\r\n JFrame frame = showPackedFrame(new JScrollPane(is));\r\n moveToTopRightCorner(frame);\r\n frameIcon(frame, showImage_defaultIcon);\r\n return is;"; }}); } static ImageSurface showImage(RGBImage img) { return showImage(img.getBufferedImage()); } static ImageSurface showImage(RGBImage img, String title) { ImageSurface is = showImage(img.getBufferedImage()); getFrame(is).setTitle(title); return is; } static ImageSurface showImage(String imageID) { return showImage(loadImage(imageID)); } static ImageSurface showImage(RGBImage img, ImageSurface surface) { if (surface == null) return showImage(img); else { surface.setImage(img); return surface; } } static String[] dropLast(String[] a, int n) { n = Math.min(n, a.length); String[] b = new String[a.length-n]; System.arraycopy(a, 0, b, 0, b.length); return b; } static List dropLast(List l) { return subList(l, 0, l(l)-1); } static Map getTableLineAsMap(JTable tbl, int row) { if (row >= 0 && row < tbl.getModel().getRowCount()) { Map map = litorderedmap(); // keep order of columns for (int i = 0; i < tbl.getModel().getColumnCount(); i++) map.put(tbl.getModel().getColumnName(i), String.valueOf(tbl.getModel().getValueAt(row, i))); return map; } return null; } static JPanel vgrid(List parts) { return vgrid(asArray(parts)); } static JPanel vgrid(Object... parts) { JPanel panel = new JPanel(); panel.setLayout(new GridLayout(parts.length, 1)); smartAdd(panel, parts); return panel; } static String trim(String s) { return s == null ? null : s.trim(); } static String trim(StringBuilder buf) { return buf.toString().trim(); } static String trim(StringBuffer buf) { return buf.toString().trim(); } static void disposeFrame(final JFrame frame) { swingNowOrLater(new Runnable() { public void run() { try { frame.dispose(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } // key = 1 to 12 static void registerFunctionKey(JFrame frame, int key, final Runnable r) { String name = "F" + key; Action action = abstractAction(name, r); JComponent pnl = frame.getRootPane(); KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F1+key-1, 0); pnl.getActionMap().put(name, action); pnl.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name); } public static String readTextFile(String fileName, String defaultContents) throws IOException { return loadTextFile(fileName, defaultContents); } public static String readTextFile(File file) { try { return readTextFile(file, null); } catch (IOException e) { throw new RuntimeException(e); } } public static String readTextFile(File file, String defaultContents) throws IOException { return loadTextFile(file.getPath(), defaultContents); } static String fsI(String id) { return formatSnippetID(id); } static void swingAndWait(Runnable r) { try { if (isAWTThread()) r.run(); else EventQueue.invokeAndWait(r); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__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 __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); return result.get(); } } static Thread currentThread() { return Thread.currentThread(); } static void printStackTrace(Throwable e) { // we go to system.out now - system.err is nonsense print(getStackTrace(e)); } static void printStackTrace() { printStackTrace(new Throwable()); } // key = 1 to 12 static void registerCtrlFunctionKey(JFrame frame, int key, final Runnable r) { String name = "Ctrl+F" + key; Action action = abstractAction(name, r); JComponent pnl = frame.getRootPane(); KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F1+key-1, InputEvent.CTRL_MASK); pnl.getActionMap().put(name, action); pnl.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name); } static JMenu addMenu(JFrame frame, String menuName, Object... items) { JMenuBar bar = addMenuBar(frame); JMenu menu = getMenuNamed(bar, menuName); boolean isNew = menu == null; if (isNew) menu = new JMenu(menuName); else menu.removeAll(); fillJMenu(menu, items); if (isNew) bar.add(menu); return menu; } static boolean mouseInComponent(Component c) { return boundsOnScreen(c).contains(mousePosition()); } static List cloneList(Collection l) { //O mutex = getOpt(l, "mutex"); /*if (mutex != null) synchronized(mutex) { ret new ArrayList(l); } else ret new ArrayList(l);*/ // assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does. synchronized(l) { return new ArrayList(l); } } static Map litmap(Object... x) { TreeMap map = new TreeMap(); litmap_impl(map, x); return map; } static void litmap_impl(Map map, Object... x) { for (int i = 0; i < x.length-1; i += 2) if (x[i+1] != null) map.put(x[i], x[i+1]); } // key = 1 to 12 static void registerShiftFunctionKey(JFrame frame, int key, final Runnable r) { String name = "Shift+F" + key; Action action = abstractAction(name, r); JComponent pnl = frame.getRootPane(); KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F1+key-1, InputEvent.SHIFT_MASK); pnl.getActionMap().put(name, action); pnl.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name); } static String str(Object o) { return String.valueOf(o); } static RuntimeException fail() { throw new RuntimeException("fail"); } static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); } static RuntimeException fail(String msg) { throw new RuntimeException(unnull(msg)); } // disabled for now to shorten some programs /*static RuntimeException fail(S msg, O... args) { throw new RuntimeException(format(msg, args)); }*/ 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.indexOf(c) >= 0; } static List valuesList(Map map) { return new ArrayList(values(map)); } 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 String fsi(String id) { return formatSnippetID(id); } static String unnull(String s) { return s == null ? "" : s; } static List unnull(List l) { return l == null ? emptyList() : l; } static Iterable unnull(Iterable i) { return i == null ? emptyList() : i; } static Object[] unnull(Object[] a) { return a == null ? new Object[0] : a; } static boolean swic(String a, String b) { return startsWithIgnoreCase(a, b); } static boolean setFrameTitle(Component c, String title) { JFrame f = getFrame(c); if (f == null) return false; f.setTitle(title); return true; } // magically find a field called "frame" in main class :-) static boolean setFrameTitle(String title) { Object f = getOpt(mc(), "frame"); if (f instanceof JFrame) return setFrameTitle((JFrame) f, title); return false; } // runnable can be a func(O o) {} receving the selected row index static void onDoubleClickOrEnter(final JTable table, final Object runnable) { onDoubleClick(table, runnable); 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(runnable, table.getSelectedRow()); } }); } // runnable can be a func(O o) {} receving the selected item static void onDoubleClick(final JList list, final Object runnable) { list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { int idx = list.locationToIndex(evt.getPoint()); Object item = list.getModel().getElementAt(idx); list.setSelectedIndex(idx); callF(runnable, item); } } }); } // runnable can be a func(O o) {} receving the selected row index static void onDoubleClick(final JTable table, final Object runnable) { table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { int idx = table.rowAtPoint(evt.getPoint()); table.setRowSelectionInterval(idx, idx); callF(runnable, idx); } } }); } static class DynamicObject { String className; Map fieldValues = new TreeMap(); } static Object unstructure(String text) { return unstructure(text, false); } // TODO: backrefs for hashmap{} etc static Object unstructure(String text, final boolean allDynamic) { if (text == null) return null; final List tok = javaTok(text); final boolean debug = unstructure_debug; class X { int i = 1; HashMap refs = new HashMap(); Object parse() { String t = tok.get(i); int refID = 0; if (t.startsWith("m") && isInteger(t.substring(1))) { refID = parseInt(t.substring(1)); i += 2; t = tok.get(i); } if (debug) print("parse: " + quote(t)); if (t.startsWith("\"")) { String s = unquote(tok.get(i)); i += 2; return s; } if (t.startsWith("'")) { char c = unquoteCharacter(tok.get(i)); i += 2; return c; } if (t.equals("bigint")) return parseBigInt(); if (t.equals("d")) return parseDouble(); if (t.equals("false") || t.equals("f")) { i += 2; return false; } if (t.equals("true") || t.equals("t")) { i += 2; return true; } if (t.equals("-")) { t = tok.get(i+2); i += 4; return isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)); } if (isInteger(t) || isLongConstant(t)) { i += 2; if (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t)); if (isLongConstant(t)) return parseLong(t); long l = parseLong(t); return l != (int) l ? new Long(l) : new Integer((int) l); } if (t.equals("File")) { File f = new File(unquote(tok.get(i+2))); i += 4; return f; } if (t.startsWith("r") && isInteger(t.substring(1))) { i += 2; int ref = Integer.parseInt(t.substring(1)); Object o = refs.get(ref); if (o == null) print("Warning: unsatisfied back reference " + ref); return o; } return parse_inner(refID); } // everything that can be backreferenced Object parse_inner(int refID) { String t = tok.get(i); if (debug) print("parse_inner: " + quote(t)); if (t.equals("hashset")) return parseHashSet(); if (t.equals("treeset")) return parseTreeSet(); if (t.equals("hashmap")) return parseHashMap(); if (t.equals("{")) return parseMap(); if (t.equals("[")) return parseList(); if (t.equals("array")) return parseArray(); if (t.equals("class")) return parseClass(); if (t.equals("l")) return parseLisp(); if (t.equals("null")) { i += 2; return null; } if (isJavaIdentifier(t)) { Class c = allDynamic ? null : findClass(t); DynamicObject dO = null; Object o = null; if (c != null) o = nuObject(c); else { dO = new DynamicObject(); dO.className = t; } if (refID != 0) refs.put(refID, o); i += 2; if (i < tok.size() && tok.get(i).equals("(")) { consume("("); while (!tok.get(i).equals(")")) { // It's like parsing a map. //Object key = parse(); //if (tok.get(i).equals(")")) // key = onlyField(); String key = unquote(tok.get(i)); i += 2; consume("="); Object value = parse(); if (o != null) setOpt(o, key, value); else dO.fieldValues.put(key, value); if (tok.get(i).equals(",")) i += 2; } consume(")"); } return o != null ? o : dO; } throw new RuntimeException("Unknown token " + (i+1) + ": " + t); } Object parseSet(Set set) { set.addAll((List) parseList()); return set; } Object parseLisp() { consume("l"); consume("("); List list = new ArrayList(); while (!tok.get(i).equals(")")) { list.add(parse()); if (tok.get(i).equals(",")) i += 2; } consume(")"); return newObject("main$Lisp", (String) list.get(0), subList(list, 1)); } 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 parseArray() { consume("array"); consume("{"); List list = new ArrayList(); while (!tok.get(i).equals("}")) { list.add(parse()); if (tok.get(i).equals(",")) i += 2; } consume("}"); return list.toArray(); } Object parseClass() { consume("class"); consume("("); String name = tok.get(i); i += 2; consume(")"); Class c = allDynamic ? null : findClass(name); if (c != null) return c; DynamicObject dO = new DynamicObject(); dO.className = "java.lang.Class"; dO.fieldValues.put("name", name); return dO; } Object parseBigInt() { consume("bigint"); consume("("); String val = tok.get(i); i += 2; if (eq(val, "-")) { val = "-" + tok.get(i); i += 2; } consume(")"); return new BigInteger(val); } Object parseDouble() { consume("d"); consume("("); String val = unquote(tok.get(i)); i += 2; consume(")"); return Double.parseDouble(val); } Object parseHashMap() { consume("hashmap"); return parseMap(new HashMap()); } Object parseHashSet() { consume("hashset"); return parseSet(new HashSet()); } Object parseTreeSet() { consume("treeset"); return parseSet(new TreeSet()); } Object parseMap() { return parseMap(new TreeMap()); } Object parseMap(Map map) { consume("{"); while (!tok.get(i).equals("}")) { Object key = parse(); 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 X().parse(); } static boolean unstructure_debug; static List scanEventLogForText(String progID, String dialogName) { return scanEventLogForText(getProgramFile(progID, dialogName)); } // f can be the dir or the log file static List scanEventLogForText(File f) { return collect(scanEventLogForPosts(f), "text"); } static void removeLast(List l) { if (!l.isEmpty()) l.remove(l(l)-1); } public static boolean isSnippetID(String s) { try { parseSnippetID(s); return true; } catch (RuntimeException e) { return false; } } // patterns last so we can use var args static boolean matchOneOf(String s, Matches m, String... pats) { for (String pat : pats) if (match(pat, s, m)) return true; return false; } static boolean matchOneOf(String s, String... pats) { return matchOneOf(s, null, pats); } static int min(int a, int 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 byte min(byte[] c) { byte x = 127; for (byte d : c) if (d < x) x = d; return x; } static JWindow showLoadingAnimation() { return showAnimationInTopRightCorner("#1003543", "Hold on user..."); } // get purpose 1: access a list/array (safer version of x.get(y)) static A get(List l, int idx) { return idx >= 0 && idx < l(l) ? l.get(idx) : null; } static A get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } // get purpose 2: access a field by reflection or a map static Object get(Object o, String field) { if (o instanceof Class) return get((Class) o, field); if (o instanceof Map) return ((Map) o).get(field); if (o.getClass().getName().equals("main$DynamicObject")) return call(get_raw(o, "fieldValues"), "get", field); return get_raw(o, field); } static Object get_raw(Object o, String field) { try { Field f = get_findField(o.getClass(), field); f.setAccessible(true); return f.get(o); } catch (Exception e) { throw new RuntimeException(e); } } static Object get(Class c, String field) { try { Field f = get_findStaticField(c, field); f.setAccessible(true); 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() & 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 quickImport(Object o) { return quickExport(o, mc()); } static String escapeNewLines(String s) { return s.replace("\n", " | "); } static String autoFrameTitle() { return getProgramTitle(); } 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 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 (String s : toLines(file)) if (isProperlyQuoted(s)) l.add(unquote(s)); return l; } static List subList(List l, int startIndex) { return subList(l, startIndex, l(l)); } static List subList(List l, int startIndex, int endIndex) { startIndex = max(0, min(l(l), startIndex)); endIndex = max(0, min(l(l), endIndex)); if (startIndex > endIndex) return litlist(); return l.subList(startIndex, endIndex); } static boolean containsFile(File dir, String name) { return new File(dir, name).exists(); } static List listDirs(File dir) { File[] files = dir.listFiles(); List l = new ArrayList(); if (files != null) for (File f : files) if (f.isDirectory()) l.add(f); return l; } static List listPlus(List l, A... more) { return concatLists(l, asList(more)); } static int l(Object[] array) { return array == null ? 0 : array.length; } static int l(byte[] array) { return array == null ? 0 : array.length; } static int l(int[] array) { return array == null ? 0 : array.length; } static int l(char[] array) { return array == null ? 0 : array.length; } static int l(Collection c) { return c == null ? 0 : c.size(); } static int l(Map m) { return m == null ? 0 : m.size(); } static int l(String s) { return s == null ? 0 : s.length(); } static int l(Object o) { return l((List) o); // incomplete } static String exceptionToStringShort(Throwable e) { e = getInnerException(e); String msg = unnull(e.getMessage()); if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0) return baseClassName(e) + ": " + msg; else return msg; } static File getProgramDir() { return programDir(); } static File getProgramDir(String snippetID) { return programDir(snippetID); } static ThreadLocal gCompleting; static boolean gCompleting() { gCompleting_init(); Boolean b = gCompleting.get(); /*if (b == null) b = (Bool) callOpt(creator(), "gCompleting");*/ return isTrue(b); } static void gCompleting_set(Boolean b) { gCompleting_init(); gCompleting.set(b); } static void gCompleting_init() { if (gCompleting == null) { gCompleting = (ThreadLocal) getOpt(creator(), "gCompleting"); if (gCompleting == null) gCompleting = new ThreadLocal(); } } static String gMode() { return gCompleting() ? "/i" : ""; } static List rejectWhere(Object pred, List l) { List x = new ArrayList(); for (Object o : l) if (!isTrue(callF(pred, o))) x.add(o); return x; } // action = runnable or method name static void onUpdate(JTextComponent c, final Object r) { c.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { callFunction(r); } public void removeUpdate(DocumentEvent e) { callFunction(r); } public void changedUpdate(DocumentEvent e) { callFunction(r); } }); } static Object first(Object list) { return ((List) list).isEmpty() ? null : ((List) list).get(0); } static A first(List list) { return list.isEmpty() ? null : list.get(0); } static A first(A[] bla) { return bla == null || bla.length == 0 ? null : bla[0]; } static A first(Iterable i) { if (i == null) return null; Iterator it = i.iterator(); return it.hasNext() ? it.next() : null; } static void setFrameIcon(JFrame frame, String imageID) { try { /* pcall 1*/ if (frame != null) frame.setIconImage(imageIcon(imageID).getImage()); /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } } static void setFrameIcon(Component c, String imageID) { setFrameIcon(getFrame(c), imageID); } static ArrayList ll(A... a) { return litlist(a); } static LinkedHashMap litorderedmap(Object... x) { LinkedHashMap map = new LinkedHashMap(); litmap_impl(map, x); return map; } static String dropBracketPrefix(String s) { s = s.trim(); if (s.startsWith("[")) { int i = s.indexOf(']'); return s.substring(i+1).trim(); } return s; } static String getSnippetTitle(String id) { try { if (!isSnippetID(id)) return "?"; return loadPageSilently(new URL("http://tinybrain.de:8080/tb-int/getfield.php?id=" + parseSnippetID(id) + "&field=title")); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static File prepareProgramFile(String name) { return mkdirsForFile(getProgramFile(name)); } static File prepareProgramFile(String progID, String name) { return mkdirsForFile(getProgramFile(progID, name)); } static String joinLines(List lines) { return fromLines(lines); } static String joinLines(String glue, String text) { return join(glue, toLines(text)); } static List getLast(List l, int n) { return subList(l, l(l)-n); } static boolean empty(Collection c) { return isEmpty(c); } static boolean empty(String s) { return isEmpty(s); } 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); throw fail("unknown type for 'empty': " + getType(o)); } static boolean confirmYesNo(Component owner, String msg) { return JOptionPane.showConfirmDialog(owner, msg, "JavaX", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION; } // Let's just generally synchronize this to be safe. static synchronized void appendToFile(String path, String s) { try { new File(path).getParentFile().mkdirs(); //print("[Logging to " + path + "]"); Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(path, true), "UTF-8")); writer.write(s); writer.close(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static void appendToFile(File path, String s) { if (path != null) appendToFile(path.getPath(), s); } static Class mc() { return getMainClass(); } static A findByField(Collection c, String field, Object value) { for (A a : c) if (eq(getOpt(a, field), value)) return a; return null; } static boolean neq(Object a, Object b) { return !eq(a, b); } static String getProgramTitle() { return getProgramName(); } static ThreadLocal> genLog_log; static List genLog() { genLog_init(); List log = genLog_log.get(); /*if (log == null) log = (L) callOpt(creator(), "genLog");*/ return assertNotNull("No log set for this thread", log); } static void genLog_set(List log) { genLog_init(); genLog_log.set(log); } static void genLog_clear() { genLog_init(); genLog_log.set(null); } static void genLog_init() { if (genLog_log == null) { genLog_log = (ThreadLocal) getOpt(creator(), "genLog_log"); if (genLog_log == null) genLog_log = new ThreadLocal(); } } static boolean firstIs(List l, A a) { return eq(get(l, 0), a); } // automatic conversion to string (for returning numbers etc.) static String callGen(Gen gen) { return strPreserveNull(callF(gen.func)); } static A last(List l) { return l.isEmpty() ? null : l.get(l.size()-1); } static boolean eq(Object a, Object b) { if (a == null) return b == null; if (a.equals(b)) return true; if (a instanceof BigInteger) { if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b)); if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b)); } return false; } static ThreadLocal>> gOtherLogs_data; // for now we return L> instead of L> // because ImmL class loader problems static List> gOtherLogs() { gOtherLogs_init(); return unnull((List) gOtherLogs_data.get()); } static void gOtherLogs_set(List> logs) { gOtherLogs_init(); gOtherLogs_data.set(logs); } static void gOtherLogs_clear() { gOtherLogs_init(); gOtherLogs_data.set(null); } static void gOtherLogs_init() { if (gOtherLogs_data == null) { gOtherLogs_data = (ThreadLocal) getOpt(creator(), "gOtherLogs_data"); if (gOtherLogs_data == null) gOtherLogs_data = new ThreadLocal(); } } static TableWithTooltips tableWithTooltips() { return new TableWithTooltips(); } static class TableWithTooltips extends JTable { public String getToolTipText(MouseEvent e) { String tip = null; Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); try { return str(getValueAt(rowIndex, colIndex)); } catch (Throwable _e) { return null; } } } static List findAllFiles(List dirs) { return findAllFiles(asObjectArray(dirs)); } // dirs are String's or File's static List findAllFiles(Object... dirs) { List l = new ArrayList(); for (Object dir : dirs) { if (dir instanceof String && ((String) dir).endsWith("/.")) // "/." means non-recurse for (File f : listFiles(dropSuffix("/.", (String) dir))) l.add(f); else findAllFiles_impl(toFile(dir), l); } return l; } static void findAllFiles_impl(File dir, List l) { for (File f : listFiles(dir)) { l.add(f); if (f.isDirectory()) findAllFiles_impl(f, l); } } static Map getMap(Map map, Object key) { return map == null ? null : (Map) map.get(key); } static Map getMap(List l, int idx) { return (Map) get(l, idx); } static Map getMap(Object o, Object key) { if (o instanceof Map) return getMap((Map) o, key); if (key instanceof String) return (Map) get(o, (String) key); throw fail("Not a string key: " + getClassName(key)); } static void onEnter(JTextField tf, final Runnable action) { tf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { action.run(); } catch (Throwable e) { e.printStackTrace(); } } }); } /** writes safely (to temp file, then rename) */ public static void saveTextFile(String fileName, String contents) throws IOException { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; if (contents != null) { FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); 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 (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); } public static void saveTextFile(File fileName, String contents) { try { saveTextFile(fileName.getPath(), contents); } catch (IOException e) { throw new RuntimeException(e); } } static List scanLog_safeUnstructure(String progID, String fileName) { return scanLog_safeUnstructure(getProgramFile(progID, fileName)); } static List scanLog_safeUnstructure(String fileName) { return scanLog_safeUnstructure(getProgramFile(fileName)); } static List scanLog_safeUnstructure(File file) { List l = new ArrayList(); for (String s : scanLog(file)) try { /* pcall 1*/ l.add(safeUnstructure(s)); /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } return l; } static void readLocally(String progID, String varNames) { readLocally2(mc(), progID, varNames); } static void readLocally(String varNames) { readLocally2(mc(), programID(), varNames); } static void readLocally2(Object obj, String varNames) { readLocally2(obj, programID(), varNames); } // read a string variable from standard storage // does not overwrite variable contents if there is no file static synchronized void readLocally2(Object obj, String progID, String varNames) { for (String variableName : codeTokensOnly(javaTok(varNames))) { File textFile = new File(programDir(progID), variableName + ".text"); File structureFile = new File(programDir(progID), variableName + ".structure"); String value = loadTextFile(textFile); if (value != null) set(main.class, variableName, value); else { value = loadTextFile(structureFile); if (value != null) readLocally_set(obj, variableName, unstructure(value)); } } } static void readLocally_set(Object c, String varName, Object value) { Object oldValue = get(c, varName); if (oldValue instanceof List && !(oldValue instanceof ArrayList) && value != null) { // Assume it's a synchroList. value = synchroList((List) value); } set(c, varName, value); } static int tableRows(JTable table) { return table.getRowCount(); } static Map synchroMap() { return synchroHashMap(); } static Object callOpt(Object o) { if (o == null) return null; return callF(o); } static Object callOpt(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Method m = callOpt_findStaticMethod((Class) o, method, args, false); if (m == null) return null; m.setAccessible(true); return m.invoke(null, args); } else { Method m = callOpt_findMethod(o, method, args, false); if (m == null) return null; m.setAccessible(true); return m.invoke(o, args); } } catch (Exception e) { throw new RuntimeException(e); } } static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (!m.getName().equals(method)) { if (debug) System.out.println("Method name mismatch: " + method); continue; } if ((m.getModifiers() & Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug)) continue; return m; } c = c.getSuperclass(); } return null; } static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) { Class c = o.getClass(); while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug)) return m; } c = c.getSuperclass(); } return null; } private static boolean callOpt_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 Collection values(Map map) { return map.values(); } static JFrame getFrame(Object 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; } static JPanel centerAndSouth(Component c, Component s) { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.CENTER, wrap(c)); if (s != null) panel.add(BorderLayout.SOUTH, wrap(s)); return panel; } static JTable dataToTable_uneditable(final JTable table, final Object data) { swingNowOrLater(new Runnable() { public void run() { try { dataToTable(table, data, true); makeTableUneditable(table); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); return table; } static JTable dataToTable_uneditable(final Object data) { return dataToTable_uneditable(showTable(), data); } static JTable dataToTable_uneditable(Object data, String title) { return dataToTable_uneditable(showTable(title), data); } static Map mapPlus(Map m, Object... data) { m = cloneMap(m); litmap_impl(m, data); return m; } public static String fromLines(List lines) { StringBuilder buf = new StringBuilder(); if (lines != null) for (String line : lines) buf.append(line).append('\n'); return buf.toString(); } static void logQuoted(String logFile, String line) { logQuoted(getProgramFile(logFile), line); } static void logQuoted(File logFile, String line) { appendToFile(logFile, quote(line) + "\n"); } static String substring(String s, int x) { return safeSubstring(s, x); } static String substring(String s, int x, int y) { return safeSubstring(s, x, y); } static List getTableLine(JTable tbl, int row) { if (row >= 0 && row < tbl.getModel().getRowCount()) { List l = new ArrayList(); for (int i = 0; i < tbl.getModel().getColumnCount(); i++) l.add(String.valueOf(tbl.getModel().getValueAt(row, i))); return l; } return null; } static List synchroList() { return Collections.synchronizedList(new ArrayList()); } static List synchroList(List l) { return Collections.synchronizedList(l); } static long now_virtualTime; static long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } static void scrollTableDownIn(final JTable table, int delayMS) { swingLater(delayMS, new Runnable() { public void run() { try { scrollTableDown(table); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static void systemCommands(String s, Object env) { call(env, "postSystemMessage", systemCommands_impl(s, env)); } static String systemCommands_impl(String s, Object env) { Matches m = new Matches(); // SYSTEM COMMANDS if (matchOneOf(s, m, "start program *", "start *") && isSnippetID(m.unq(0))) { String progID = m.fsi(0); String title = getSnippetTitle(progID); // TODO: Show author! String msg = "Run program " + progID + " - " + title + "?"; if (confirmOKCancel((JFrame) getOpt(env, "frame"), msg)) { call(env, "postSystemMessage", "Starting program " + progID + " - " + quote(title)); nohupJavax(progID); } else call(env, "postSystemMessage", "Program start cancelled by user (was: " + progID + ")"); } if (matchOneOf(s, m, "hotwire *", "hotwire * with argument *")) { String progID = m.fsi(0), arg = unnull(m.unq(1)); String title = getSnippetTitle(progID); String msg = "Hotwire & run program " + progID + " - " + quote(title) + (empty(arg) ? "" : " with argument " + quote(arg)) + "?"; if (confirmOKCancel((JFrame) getOpt(env, "frame"), msg)) { call(env, "postSystemMessage", "Hotwiring & running program " + progID + " - " + quote(title) + (empty(arg) ? "" : " with argument " + quote(arg))); run(progID, arg); } else call(env, "postSystemMessage", "Program start cancelled by user (was: " + progID + ")"); } if (matchOneOf(s, "jfresh", "fresh")) { return veryQuickJava_refresh() ? "OK, translator dropped." : "Nothing to do"; } if (startsWithOneOf(s, "java ", "j ")) { String code = onlyAfter(s, ' '); return systemCommands_evalJava(code); } if (startsWith(s, "jfresh ")) { veryQuickJava_refresh(); String code = dropPrefix("jfresh", s); return systemCommands_evalJava(code); } if (match("restart", s, m)) { call(env, "postSystemMessage", "Restarting..."); restart(); } if (match("pop", s, m)) { // pop up last chat line in a window String text = nextToLast((List) get(env, "log")); if (empty(text)) return "Nothing to show"; else showText(text); } return null; } static Object systemCommands_lastResult; static String systemCommands_evalJava(String code) { code = trim(code); code = tok_addReturn(code); String returnType = containsReturnWithArgument(code) ? "O" : "void"; String main = "!include #1003911\n" + // functions for quick eval "static " + returnType + " calc() { " + code + "\n" + "}"; Object obj = veryQuickJava(main); setOpt(obj, "getProgramName_cache", "User Code"); long time = now(); Object result = callCalc(obj); systemCommands_lastResult = result; time = now()-time; return time + " ms\n" + systemCommands_prettyPrint(result); } static String systemCommands_prettyPrint(Object o) { if (o instanceof List) return fromLines(map(new Object() { Object get(Object o) { return systemCommands_prettyPrint(o) ; } public String toString() { return "systemCommands_prettyPrint(o)"; }}, (List) o)); if (eq(getClassName(o), "main$Snippet")) return formatSnippetID(getString(o, "id")) + " - " + getString(o, "title"); return structureOrText(o); } static boolean setAdd(Collection c, A a) { if (c.contains(a)) return false; c.add(a); return true; } static Map mapMinus(Map map, Object... keys) { Map m2 = cloneMap(map); for (Object key : keys) m2.remove(key); return m2; } // compile JavaX source, load classes & return main class // src can be a snippet ID or actual source code // TODO: record injection? static Class hotwire(String src) { try { Class j = getJavaX(); 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"); if (androidContext != null) return (Class) call(j, "loadx2android", srcDir, src); File classesDir = (File) call(j, "TempDirMaker_make"); String javacOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir); System.out.println(javacOutput); URL[] urls = new URL[libraries.size()+1]; urls[0] = classesDir.toURI().toURL(); for (int i = 0; i < libraries.size(); i++) urls[i+1] = libraries.get(i).toURI().toURL(); // make class loader URLClassLoader classLoader = new URLClassLoader(urls); // load & return main class Class theClass = classLoader.loadClass("main"); callOpt(j, "registerSourceCode", theClass, loadTextFile(new File(srcDir, "main.java"))); call(j, "setVars", theClass, isSnippetID(src) ? src: null); if (isSnippetID(src)) callOpt(j, "addInstance", src, theClass); if (!_inCore()) hotwire_copyOver(theClass); return theClass; } } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } } static File getProgramFile(String progID, String fileName) { return new File(getProgramDir(progID), fileName); } static File getProgramFile(String fileName) { return getProgramFile(getProgramID(), fileName); } static void saveLocally(String variableName) { saveLocally(programID(), variableName); } static void saveLocally(String progID, String variableName) { saveLocally2(mc(), progID, variableName); } static void saveLocally2(Object obj, String variableName) { saveLocally2(obj, programID(), variableName); } static synchronized void saveLocally2(Object obj, String progID, String variableName) { File textFile = new File(programDir(progID), variableName + ".text"); File structureFile = new File(programDir(progID), variableName + ".structure"); Object x = get(obj, variableName); if (x == null) { textFile.delete(); structureFile.delete(); } else if (x instanceof String) { saveTextFile(textFile, (String) x); structureFile.delete(); } else { saveTextFile(structureFile, structure(x)); textFile.delete(); } } static void swingAfter(JFrame base, int delay, Runnable r) { installTimer((JComponent) base.getContentPane(), r, delay, delay, false); } static void swingAfter(JComponent base, int delay, Runnable r) { installTimer(base, r, delay, delay, false); } static void substance() { substanceLAF(); } static void substance(String skinName) { substanceLAF(skinName); } 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 nempty(Collection c) { return !isEmpty(c); } static boolean nempty(CharSequence s) { return !isEmpty(s); } static boolean nempty(Object[] o) { return !isEmpty(o); } static boolean nempty(Map m) { return !isEmpty(m); } static boolean nempty(Iterator i) { return i != null && i.hasNext(); } static boolean eqic(String a, String b) { if ((a == null) != (b == null)) return false; if (a == null) return true; return a.equalsIgnoreCase(b); } static String chatTime() { return formatInt(month(), 2) + "/" + formatInt(days(), 2) + " " + formatInt(hours(), 2) + ":" + formatInt(minutes(), 2) + ":" + formatInt(seconds(), 2); } 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) get(o, (String) key); throw fail("Not a string key: " + getClassName(key)); } static void disposeWindow(final Window window) { swingLater(new Runnable() { public void run() { try { window.dispose(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static String structure(Object o) { HashSet refd = new HashSet(); return structure_2(structure_1(o, 0, new IdentityHashMap(), refd), refd); } // leave to false, unless unstructure() breaks static boolean structure_allowShortening = false; static String structure_1(Object o, int stringSizeLimit, IdentityHashMap seen, HashSet refd) { if (o == null) return "null"; // these are never back-referenced (for readability) if (o instanceof String) return quote(stringSizeLimit != 0 ? shorten((String) o, stringSizeLimit) : (String) o); if (o instanceof BigInteger) return "bigint(" + o + ")"; if (o instanceof Double) return "d(" + quote(str(o)) + ")"; if (o instanceof Long) return o + "L"; if (o instanceof Integer) return str(o); if (o instanceof Boolean) return ((Boolean) o).booleanValue() ? "t" : "f"; if (o instanceof Character) return quoteCharacter((Character) o); if (o instanceof File) return "File " + quote(((File) o).getPath()); // referencable objects follow Integer ref = seen.get(o); if (ref != null) { refd.add(ref); return "r" + ref; } ref = seen.size()+1; seen.put(o, ref); String r = "m" + ref + " "; // marker String name = o.getClass().getName(); StringBuilder buf = new StringBuilder(); if (o instanceof HashSet) return r + "hashset " + structure_1(new ArrayList((Set) o), stringSizeLimit, seen, refd); if (o instanceof TreeSet) return r + "treeset " + structure_1(new ArrayList((Set) o), stringSizeLimit, seen, refd); if (o instanceof Collection) { for (Object x : (Collection) o) { if (buf.length() != 0) buf.append(", "); buf.append(structure_1(x, stringSizeLimit, seen, refd)); } return r + "[" + buf + "]"; } if (o instanceof Map) { for (Object e : ((Map) o).entrySet()) { if (buf.length() != 0) buf.append(", "); buf.append(structure_1(((Map.Entry) e).getKey(), stringSizeLimit, seen, refd)); buf.append("="); buf.append(structure_1(((Map.Entry) e).getValue(), stringSizeLimit, seen, refd)); } return r + (o instanceof HashMap ? "hashmap" : "") + "{" + buf + "}"; } if (o.getClass().isArray()) { int n = Array.getLength(o); for (int i = 0; i < n; i++) { if (buf.length() != 0) buf.append(", "); buf.append(structure_1(Array.get(o, i), stringSizeLimit, seen, refd)); } return r + "array{" + buf + "}"; } if (o instanceof Class) return r + "class(" + quote(((Class) o).getName()) + ")"; if (o instanceof Throwable) return r + "exception(" + quote(((Throwable) o).getMessage()) + ")"; if (o instanceof BitSet) { BitSet bs = (BitSet) o; for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { if (buf.length() != 0) buf.append(", "); buf.append(i); } return "bitset{" + buf + "}"; } // Need more cases? This should cover all library classes... if (name.startsWith("java.") || name.startsWith("javax.")) return r + String.valueOf(o); String shortName = o.getClass().getName().replaceAll("^main\\$", ""); if (shortName.equals("Lisp")) { buf.append("l(" + structure_1(getOpt(o, "head"), stringSizeLimit, seen, refd)); List args = (List) ( getOpt(o, "args")); if (nempty(args)) for (int i = 0; i < l(args); i++) { buf.append(", "); Object arg = args.get(i); // sweet shortening if (arg != null && eq(arg.getClass().getName(), "main$Lisp") && isTrue(call(arg, "isEmpty"))) arg = get(arg, "head"); buf.append(structure_1(arg, stringSizeLimit, seen, refd)); } buf.append(")"); return r + str(buf); } int numFields = 0; String fieldName = ""; if (shortName.equals("DynamicObject")) { shortName = (String) get_raw(o, "className"); Map fieldValues = (Map) get_raw(o, "fieldValues"); for (String _fieldName : fieldValues.keySet()) { fieldName = _fieldName; Object value = fieldValues.get(fieldName); if (value != null) { if (buf.length() != 0) buf.append(", "); buf.append(fieldName + "=" + structure_1(value, stringSizeLimit, seen, refd)); } ++numFields; } } else { // regular class Class c = o.getClass(); while (c != Object.class) { Field[] fields = c.getDeclaredFields(); for (Field field : fields) { if ((field.getModifiers() & Modifier.STATIC) != 0) continue; fieldName = field.getName(); // skip outer object reference if (fieldName.indexOf("$") >= 0) continue; Object value; try { field.setAccessible(true); value = field.get(o); } catch (Exception e) { value = "?"; } // put special cases here... if (value != null) { if (buf.length() != 0) buf.append(", "); buf.append(fieldName + "=" + structure_1(value, stringSizeLimit, seen, refd)); } ++numFields; } c = c.getSuperclass(); } } String b = buf.toString(); if (numFields == 1 && structure_allowShortening) b = b.replaceAll("^" + fieldName + "=", ""); // drop field name if only one String s = shortName; if (buf.length() != 0) s += "(" + b + ")"; return r + s; } // drop unused markers static String structure_2(String s, HashSet refd) { List tok = javaTok(s); StringBuilder out = new StringBuilder(); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (t.startsWith("m") && isInteger(t.substring(1)) && !refd.contains(parseInt(t.substring(1)))) continue; out.append(t).append(tok.get(i+1)); } return str(out); } // does not store null values static Map indexByField(Collection 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 volatile StringBuffer local_log = new StringBuffer(); // not redirected static volatile StringBuffer 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; // total mute if set static void print() { print(""); } // slightly overblown signature to return original object... static A print(A o) { if (print_silent) return o; String s = String.valueOf(o) + "\n"; StringBuffer loc = local_log; StringBuffer 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 o; } static void print(long l) { print(String.valueOf(l)); } static void print(char c) { print(String.valueOf(c)); } static void print_append(StringBuffer buf, String s, int max) { synchronized(buf) { buf.append(s); max /= 2; if (buf.length() > max) try { int newLength = max/2; int ofs = buf.length()-newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } } } static void tableColumnMaxWidth(final JTable table, final int columnIdx, final int width) { swingNowOrLater(new Runnable() { public void run() { try { try { /* pcall 1*/ if (inRange(columnIdx, table.getColumnCount())) table.getColumnModel().getColumn(columnIdx).setMaxWidth(width); /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static String randomID(int length) { return makeRandomID(length); } // will create the file or update its last modified timestamp static void touchFile(File file) { try { new RandomAccessFile(mkdirsForFile(file), "rw").close(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static boolean startsWithOneOf(String s, String... l) { for (String x : l) if (startsWith(s, x)) return true; return false; } static Object[] asArray(List l) { return toObjectArray(l); } static Object[] asArray(Class type, List l) { return l.toArray((Object[]) Array.newInstance(type, l.size())); } 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(String title, Object content, boolean showIt) { JFrame frame = new JFrame(title); if (content != null) frame.getContentPane().add(wrap(content)); frame.setBounds(300, 100, 500, 400); if (showIt) frame.setVisible(true); //callOpt(content, "requestFocus"); //exitOnFrameClose(frame); // standard right-click behavior on titles if (isSubstanceLAF()) onTitleRightClick(frame, new Runnable() { public void run() { try { showConsole(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); return frame; } static Object callFunction(Object f, Object... args) { if (f == null) return null; if (f instanceof Runnable) { ((Runnable) f).run(); return null; } else if (f instanceof String) return call(mc(), (String) f, args); else return call(f, "get", args); //else throw fail("Can't call a " + getClassName(f)); } static ArrayList asList(A[] a) { return new ArrayList(Arrays.asList(a)); } static ArrayList asList(int[] a) { ArrayList l = new ArrayList(); for (int i : a) l.add(i); return l; } static ArrayList asList(Collection s) { return s == null ? new ArrayList() : s instanceof ArrayList ? (ArrayList) s : new ArrayList(s); } static String quote(String s) { if (s == null) return "null"; return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\""; } static String quote(long l) { return quote("" + l); } static String quote(char c) { return quote("" + c); } static A assertNotNull(A a) { assertTrue(a != null); return a; } static A assertNotNull(String msg, A a) { assertTrue(msg, a != null); return a; } static String quoteCharacter(char c) { if (c == '\'') return "'\\''"; if (c == '\\') return "'\\\\'"; return "'" + c + "'"; } static boolean isAWTThread() { return SwingUtilities.isEventDispatchThread(); } static void smartAdd(JPanel panel, Object... parts) { for (Object o : parts) { Component c; if (o instanceof String) c = new JLabel((String) o); else c = wrap(o); panel.add(c); } } static boolean isProperlyQuoted(String s) { return s.length() >= 2 && s.startsWith("\"") && s.endsWith("\"") && !s.endsWith("\\\""); } static String strPreserveNull(Object s) { return s == null ? null : str(s); } static Point mousePosition() { return MouseInfo.getPointerInfo().getLocation(); } static JMenuBar addMenuBar(JFrame f) { JMenuBar bar = f.getJMenuBar(); if (bar == null) f.setJMenuBar(bar = new JMenuBar()); return bar; } static String getType(Object o) { return getClassName(o); } static String programID; static String getProgramID() { return nempty(programID) ? formatSnippetID(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)); } // replacement for class JavaTok // maybe incomplete, might want to add floating point numbers // todo also: extended multi-line strings static int javaTok_n, javaTok_elements; static boolean javaTok_opt; static List javaTok(String s) { return javaTok(s, null); } static List javaTok(String s, List existing) { ++javaTok_n; int nExisting = javaTok_opt && existing != null ? existing.size() : 0; List 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; 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; } if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(quickSubstring(s, i, j)); ++n; i = j; if (i >= l) break; c = s.charAt(i); // cc is not needed in rest of loop body cc = s.substring(i, Math.min(i+2, l)); // 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 (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 ++j; if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(quickSubstring(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 javaTok(join(tok), tok); } static boolean javaTok_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 void scrollTableDown(JTable table) { table.scrollRectToVisible(table.getCellRect(table.getRowCount()-1, 0, true)); } static Object newObject(Class c, Object... args) { return nuObject(c, args); } static Object newObject(String className, Object... args) { return nuObject(className, args); } // We'd be really fancy if we filtered out return statements in // inner blocks. static boolean containsReturnWithArgument(String code) { List tok = javaTok(code); for (int i = 1; i+2 < l(tok); i += 2) if (eqOneOf(tok.get(i), "ret", "return") && neq(tok.get(i+2), ";")) return true; return false; } static String onlyAfter(String s, char c) { int i = s.indexOf(c); return i >= 0 ? s.substring(i+1) : ""; } static Class getMainClass() { try { return Class.forName("main"); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Class getMainClass(Object o) { try { return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main"); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Class __javax; static Class getJavaX() { return __javax; } static void set(Object o, String field, Object value) { if (o instanceof Class) set((Class) o, field, value); else try { Field f = set_findField(o.getClass(), field); smartSet(f, o, value); } catch (Exception e) { throw new RuntimeException(e); } } static void set(Class c, String field, Object value) { try { Field f = set_findStaticField(c, field); smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } static Field set_findField(Class c, String field) { for (Field f : c.getDeclaredFields()) if (f.getName().equals(field)) return f; throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } static Field set_findStaticField(Class c, String field) { for (Field f : c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0) return f; throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } static Map cloneMap(Map map) { if (map == null) return litmap(); // assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does. synchronized(map) { return new HashMap(map); } } static Throwable getInnerException(Throwable e) { while (e.getCause() != null) e = e.getCause(); return e; } static Object call(Object o) { return callFunction(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) { try { if (o instanceof Class) { Method m = call_findStaticMethod((Class) o, method, args, false); m.setAccessible(true); return m.invoke(null, args); } else { Method m = call_findMethod(o, method, args, false); m.setAccessible(true); return m.invoke(o, args); } } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } } static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (!m.getName().equals(method)) { if (debug) System.out.println("Method name mismatch: " + method); continue; } if ((m.getModifiers() & Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug)) continue; return m; } c = c.getSuperclass(); } throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + _c.getName()); } static Method call_findMethod(Object o, String method, Object[] args, boolean debug) { Class c = o.getClass(); while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (m.getName().equals(method) && call_checkArgs(m, args, debug)) return m; } c = c.getSuperclass(); } throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName()); } private static boolean call_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 boolean isTrue(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); if (o == null) return false; return callF(o) == Boolean.TRUE; } static Object swing(Object f) { return swingAndWait(f); } static int days() { return Calendar.getInstance().get(Calendar.DAY_OF_MONTH); } // c = Component or something implementing swing() static Component wrap(Object swingable) { Component c = (Component) ( swingable instanceof Component ? swingable : call(swingable, "swing")); if (c instanceof JTable || c instanceof JList || c instanceof JTextArea) return new JScrollPane(c); return c; } static Object callCalc(Object o) { return call(o, "calc"); } static boolean startsWithIgnoreCase(String a, String b) { return a != null && a.regionMatches(true, 0, b, 0, b.length()); } static A nextToLast(List l) { return get(l, l(l)-2); } // class Matches is added by #752 static boolean match3(String pat, String s) { return match3(pat, s, null); } static boolean match3(String pat, String s, Matches matches) { if (s == null) return false; return match3(pat, parse3(s), matches); } static boolean match3(String pat, List toks, Matches matches) { List tokpat = parse3(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; else { if (matches != null) matches.m = m; return true; } } static Class run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } // automatically switches to AWT thread for you // text is optional text below image static JWindow showAnimationInTopRightCorner(final String imageID, final String text) { return (JWindow) swingAndWait(new Object() { Object get() { JLabel label = new JLabel(imageIcon(imageID)); if (nempty(text)) { label.setText(text); label.setVerticalTextPosition(SwingConstants.BOTTOM); label.setHorizontalTextPosition(SwingConstants.CENTER); } return showInTopRightCorner(label); } public String toString() { return "JLabel label = new JLabel(imageIcon(imageID));\r\n if (nempty(text)) {\r\n label.setText(text);\r\n label.setVerticalTextPosition(SwingConstants.BOTTOM);\r\n label.setHorizontalTextPosition(SwingConstants.CENTER);\r\n }\r\n ret showInTopRightCorner(label);"; }}); } static JWindow showAnimationInTopRightCorner(final String imageID) { return showAnimationInTopRightCorner(imageID, ""); } static JWindow showAnimationInTopRightCorner(final String imageID, double seconds) { final JWindow window = showAnimationInTopRightCorner(imageID); swingLater(iround(seconds*1000), new Runnable() { public void run() { try { window.dispose(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); return window; } static boolean isInteger(String s) { return s != null && Pattern.matches("\\-?\\d+", s); } static String getStackTrace(Throwable throwable) { StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); return writer.toString(); } static void makeTableUneditable(JTable table) { for (int c = 0; c < table.getColumnCount(); c++) { Class col_class = table.getColumnClass(c); table.setDefaultEditor(col_class, null); // remove editor } } static File programDir() { return programDir(getProgramID()); } static File programDir(String snippetID) { return new File(javaxDataDir(), formatSnippetID(snippetID)); } static String formatSnippetID(String id) { return "#" + parseSnippetID(id); } static String formatSnippetID(long id) { return "#" + id; } // returns true if a translator had been loaded static synchronized boolean veryQuickJava_refresh() { if (getOpt(mc(), "transpileRaw_trans") == null) return false; setOpt(mc(), "transpileRaw_trans", null); return true; } static int month() { return Calendar.getInstance().get(Calendar.MONTH)+1; } static File toFile(Object o) { if (o instanceof File) return (File) o; if (o instanceof String) return new File((String) o); throw fail("Not a file: " + o); } // optionally convert expression to return statement static String tok_addReturn(List tok) { String lastToken = get(tok, l(tok)-2); //print("addReturn: " + structure(tok) + ", lastToken: " + quote(lastToken)); if (eq(lastToken, "}") || eq(lastToken, ";")) return join(tok); return "ret " + join(tok) + ";"; } static String tok_addReturn(String s) { return tok_addReturn(javaTok(s)); } public static File mkdirsForFile(File file) { File dir = file.getParentFile(); if (dir != null) // is null if file is in current dir dir.mkdirs(); return file; } static void substanceLAF() { substanceLAF(null); } static void substanceLAF(String skinName) { try { /* pcall 1*/ if (!substanceLookAndFeelEnabled()) { Object x = hotwire("#1003448"); if (skinName != null) set(x, "skinName", skinName); runMain(x); JFrame.setDefaultLookAndFeelDecorated(substanceLookAndFeelEnabled()); } /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } } static List emptyList() { return new ArrayList(); //ret Collections.emptyList(); } // first delay = delay static void installTimer(JComponent component, Runnable r, int delay) { installTimer(component, r, delay, delay); } // first delay = delay static void installTimer(JFrame frame, int delay, Runnable r) { installTimer(frame.getRootPane(), r, delay, delay); } // first delay = delay static void installTimer(JComponent component, int delay, Runnable r) { installTimer(component, r, delay, delay); } static void installTimer(final JComponent component, final Runnable r, final int delay, final int firstDelay) { installTimer(component, r, delay, firstDelay, true); } static void installTimer(final JComponent component, final Runnable r, final int delay, final int firstDelay, final boolean repeats) { swingLater(new Runnable() { public void run() { try { final Timer timer = new Timer(delay, new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { r.run(); }}); timer.setInitialDelay(firstDelay); timer.setRepeats(repeats); if (component.isShowing()) timer.start(); component.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { timer.start(); } public void ancestorRemoved(AncestorEvent event) { timer.stop(); } public void ancestorMoved(AncestorEvent event) { } }); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static Object[] asObjectArray(List l) { return toObjectArray(l); } public static String unquote(String s) { if (s == null) return null; if (s.startsWith("[")) { 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.startsWith("\"") /*&& s.endsWith("\"")*/ && s.length() > 1) { String st = s.substring(1, s.endsWith("\"") ? s.length()-1 : s.length()); StringBuilder sb = new StringBuilder(st.length()); for (int i = 0; i < st.length(); i++) { char ch = st.charAt(i); if (ch == '\\') { char nextChar = (i == st.length() - 1) ? '\\' : st .charAt(i + 1); // Octal escape? if (nextChar >= '0' && nextChar <= '7') { String code = "" + nextChar; i++; if ((i < st.length() - 1) && st.charAt(i + 1) >= '0' && st.charAt(i + 1) <= '7') { code += st.charAt(i + 1); i++; if ((i < st.length() - 1) && st.charAt(i + 1) >= '0' && st.charAt(i + 1) <= '7') { code += st.charAt(i + 1); i++; } } sb.append((char) Integer.parseInt(code, 8)); continue; } switch (nextChar) { case '\\': ch = '\\'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\"': ch = '\"'; break; case '\'': ch = '\''; break; // Hex Unicode: u???? case 'u': if (i >= st.length() - 5) { ch = 'u'; break; } int code = Integer.parseInt( "" + st.charAt(i + 2) + st.charAt(i + 3) + st.charAt(i + 4) + st.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(); } else return s; // return original } static String programID() { return getProgramID(); } static JFrame showPackedFrame(String title, Component contents) { return packFrame(showFrame(title, contents)); } static JFrame showPackedFrame(Component contents) { return packFrame(showFrame(contents)); } static int hours() { return Calendar.getInstance().get(Calendar.HOUR_OF_DAY); } 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(Map map) { return map == null || map.isEmpty(); } static String makeRandomID(int length) { Random random = new 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 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 int parseInt(String s) { return empty(s) ? 0 : Integer.parseInt(s); } static String structureOrText(Object o) { return o instanceof String ? (String) o : structure(o); } static void setOpt(Object o, String field, Object value) { if (o instanceof Class) setOpt((Class) o, field, value); else try { Field f = setOpt_findField(o.getClass(), field); if (f != null) smartSet(f, o, value); } catch (Exception e) { throw new RuntimeException(e); } } static void setOpt(Class c, String field, Object value) { try { Field f = setOpt_findStaticField(c, field); if (f != null) smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } static Field setOpt_findField(Class c, String field) { for (Field f : c.getDeclaredFields()) if (f.getName().equals(field)) return f; return null; } static Field setOpt_findStaticField(Class c, String field) { for (Field f : c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0) return f; return null; } static Object getOpt(Object o, String field) { if (o instanceof String) o = getBot ((String) o); if (o == null) return null; if (o instanceof Class) return getOpt((Class) o, field); if (o.getClass().getName().equals("main$DynamicObject")) return ((Map) getOpt_raw(o, "fieldValues")).get(field); if (o instanceof Map) return ((Map) o).get(field); return getOpt_raw(o, field); } static Object getOpt_raw(Object o, String field) { try { Field f = getOpt_findField(o.getClass(), field); if (f == null) return null; f.setAccessible(true); return f.get(o); } catch (Exception e) { throw new RuntimeException(e); } } static Object getOpt(Class c, String field) { try { if (c == null) return null; Field f = getOpt_findStaticField(c, field); if (f == null) return null; f.setAccessible(true); return f.get(null); } catch (Exception e) { throw new RuntimeException(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() & Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } 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 Map synchroHashMap() { return Collections.synchronizedMap(new HashMap()); } static class ELPost { String text; int suggestionIndex; // Which suggestion was taken? String suggester; } static List scanEventLogForPosts(String progID, String dialogName) { return scanEventLogForPosts(getProgramFile(progID, dialogName)); } // dialogDir can also be the log file static List scanEventLogForPosts(File dialogDir) { if (dialogDir == null) return null; List l = scanLog_safeUnstructure(fileFromDir(dialogDir, "event.log")); List data = new ArrayList(); for (int i = 0; i < l(l); i++) try { /* pcall 1*/ List a = l.get(i), prev = get(l, i-1); if (firstIs(a, "Posting")) { Map map = (Map) ( get(a, 2)); String text = getString(map, "Text").trim(); if (eq(text, "!delete")) { removeLast(data); continue; } ELPost post = new ELPost(); post.text = text; try { /* pcall 1*/ if (prev != null && firstIs(prev, "Suggestion chosen")) { Map m = getMap(prev, 2); String suggestion = getString(m, "Suggestion"); if (eq(suggestion, post.text)) { post.suggestionIndex = toInt(get(m, "Row")); post.suggester = getString(m, "Suggester"); } } /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } data.add(post); } /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } return data; } static JMenu getMenuNamed(JMenuBar bar, String name) { int n = bar.getMenuCount(); for (int i = 0; i < n; i++) { JMenu m = bar.getMenu(i); print("Found menu " + i + ": " + m); if (m != null && eq(m.getText(), name)) return m; } return null; } // hopefully covers all cases :) static String safeSubstring(String s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; if (x > s.length()) return ""; if (y < x) y = x; if (y > s.length()) y = s.length(); return s.substring(x, y); } static String safeSubstring(String s, int x) { return safeSubstring(s, x, l(s)); } static int seconds() { return Calendar.getInstance().get(Calendar.SECOND); } static String shorten(String s, int max) { if (s == null) return ""; return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "..."; } static void swingLater(int delay, final Runnable r) { javax.swing.Timer timer = new javax.swing.Timer(delay, new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { r.run(); }}); timer.setRepeats(false); timer.start(); } static void swingLater(Runnable r) { SwingUtilities.invokeLater(r); } public static String join(String glue, Iterable strings) { StringBuilder buf = new StringBuilder(); Iterator i = strings.iterator(); if (i.hasNext()) { buf.append(i.next()); while (i.hasNext()) buf.append(glue).append(i.next()); } return buf.toString(); } public static String join(String glue, String[] strings) { return join(glue, Arrays.asList(strings)); } public static String join(Iterable strings) { return join("", strings); } public static String join(String[] strings) { return join("", strings); } static String dropPrefix(String prefix, String s) { return s.startsWith(prefix) ? s.substring(l(prefix)) : s; } static List codeTokensOnly(List tok) { List l = new ArrayList(); for (int i = 1; i < tok.size(); i += 2) l.add(tok.get(i)); return l; } // currently finds only inner classes of class "main" // returns null on not found // this is the simple version that is not case-tolerant static Class findClass(String name) { try { return Class.forName("main$" + name); } catch (ClassNotFoundException e) { return null; } } static Object safeUnstructure(String s) { return unstructure(s, true); } static JTable showTable(Object data) { return dataToTable_uneditable(data); } static JTable showTable(Object data, String title) { return dataToTable_uneditable(data, title); } static JTable showTable(JTable table, Object data) { return showTable(table, data, autoFrameTitle()); } static JTable showTable(JTable table, Object data, String title) { if (table == null) table = showTable(data, title); else { setFrameTitle(table, title); dataToTable_uneditable(table, data); } return table; } static JTable showTable() { return showTable(new ArrayList>(), new ArrayList()); } static JTable showTable(String title) { return showTable(new ArrayList>(), new ArrayList(), title); } static JTable showTable(List> rows, List cols) { return showTable(rows, cols, autoFrameTitle()); } static JTable showTable(List> rows, List cols, String title) { JFrame frame = new JFrame(title); frame.setBounds(10, 10, 500, 400); centerFrame(frame); JTable tbl = tableWithToolTips(); fillTableWithStrings(tbl, rows, cols); frame.getContentPane().add(new JScrollPane(tbl)); frame.setVisible(true); return tbl; } static boolean isJavaIdentifier(String s) { if (s.length() == 0 || !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 boolean _inCore() { return false; } static JTable dataToTable(Object data) { return dataToTable(showTable(), data); } static JTable dataToTable(Object data, String title) { return dataToTable(showTable(title), data); } static JTable dataToTable(JTable table, Object data) { return dataToTable(table, data, false); } static JTable dataToTable(JTable table, Object data, boolean now) { List> rows = new ArrayList>(); List cols = new ArrayList(); if (data instanceof List) { for (Object x : (List) data) try { /* pcall 1*/ rows.add(dataToTable_makeRow(x, cols)); /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } } else if (data instanceof Map) { Map map = (Map) ( data); for (Object key : map.keySet()) { Object value = map.get(key); rows.add(litlist(structureOrText(key), structureOrText(value))); } } else print("Unknown data type: " + data); if (now) table.setModel(fillTableWithStrings_makeModel(rows, toStringArray(cols))); else fillTableWithStrings(table, rows, cols); return table; } static ThreadLocal loadPage_charset = new ThreadLocal(); static boolean loadPage_allowGzip = true, loadPage_debug; static boolean loadPage_anonymous; // don't send computer ID static int loadPage_verboseness = 100000; public static String loadPageSilently(String url) { try { return loadPageSilently(new URL(loadPage_preprocess(url))); } catch (IOException e) { throw new RuntimeException(e); } } public static String loadPageSilently(URL url) { try { IOException e = null; for (int tries = 0; tries < 60; tries++) try { URLConnection con = url.openConnection(); return loadPage(con, url); } catch (IOException _e) { e = _e; print("Retrying because of: " + e); sleepSeconds(1); } throw e; } catch (IOException e) { throw new RuntimeException(e); } } static String loadPage_preprocess(String url) { if (url.startsWith("tb/")) url = "tinybrain.de:8080/" + url; if (url.indexOf("://") < 0) url = "http://" + url; return url; } public static String loadPage(String url) { try { return loadPage(new URL(loadPage_preprocess(url))); } catch (IOException e) { throw new RuntimeException(e); } } public static String loadPage(URL url) { print("Loading: " + url.toExternalForm()); return loadPageSilently(url); } public static String loadPage(URLConnection con, URL url) throws IOException { try { if (!loadPage_anonymous) { String computerID = getComputerID(); if (computerID != null) con.setRequestProperty("X-ComputerID", computerID); } if (loadPage_allowGzip) con.setRequestProperty("Accept-Encoding", "gzip"); } catch (Throwable e) {} // fails if within doPost String contentType = con.getContentType(); if (contentType == null) throw new IOException("Page could not be read: " + url); //print("Content-Type: " + contentType); String charset = loadPage_charset == null ? null : loadPage_charset.get(); if (charset == null) charset = loadPage_guessCharset(contentType); InputStream in = con.getInputStream(); if ("gzip".equals(con.getContentEncoding())) { if (loadPage_debug) print("loadPage: Using gzip."); in = new GZIPInputStream(in); } Reader r = new InputStreamReader(in, charset); 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(); } static String loadPage_guessCharset(String contentType) { Pattern p = Pattern.compile("text/[a-z]+;\\s+charset=([^\\s]+)\\s*"); Matcher m = p.matcher(contentType); /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */ return m.matches() ? m.group(1) : "ISO-8859-1"; } static Rectangle boundsOnScreen(Component c) { if (c.getParent() instanceof JViewport && c.getParent().getParent() instanceof JScrollPane) c = c.getParent().getParent(); return new Rectangle(c.getLocationOnScreen(), c.getSize()); } static ArrayList litlist(A... a) { return new ArrayList(Arrays.asList(a)); } static boolean isLongConstant(String s) { if (!s.endsWith("L")) return false; s = s.substring(0, l(s)-1); return isInteger(s); } static List toLines(File f) { return toLines(loadTextFile(f)); } public static List toLines(String s) { List lines = new ArrayList(); if (s == null) return lines; int start = 0; while (true) { int i = toLines_nextLineBreak(s, start); if (i < 0) { if (s.length() > start) lines.add(s.substring(start)); break; } lines.add(s.substring(start, i)); if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n') i += 2; else ++i; start = i; } return lines; } private static int toLines_nextLineBreak(String s, int start) { for (int i = start; i < s.length(); i++) { char c = s.charAt(i); if (c == '\r' || c == '\n') return i; } return -1; } static void nohupJavax(String javaxargs) { nohupJavax(javaxargs, ""); } // vm args are ignored if pre-spun VM found... static void nohupJavax(String javaxargs, String vmArgs) { javaxargs = javaxargs.trim(); if (javaxargs.startsWith("#")) javaxargs = javaxargs.substring(1); String snippetID = javaTok(javaxargs).get(1); int idx = javaxargs.indexOf(' '); String args = idx < 0 ? "" : javaxargs.substring(idx+1).trim(); String line; if (args.length() != 0) line = format3("please start program * with arguments *", snippetID, args); else line = format3("please start program *", snippetID); String answer = sendToLocalBotOpt("A pre-spun VM.", line); if (match3("ok", answer)) { print("OK, used pre-spun VM."); } else { if (answer != null) print("> " + answer); print("Using standard nohup."); classicNohupJavax(javaxargs, vmArgs); } } static String baseClassName(String className) { return substring(className, className.lastIndexOf('.')); } static String baseClassName(Object o) { return baseClassName(getClassName(o)); } static List map(Object f, Iterable l) { List x = new ArrayList(); Object mc = mc(); for (Object o : unnull(l)) x.add(callFunction(f, o)); return x; } static List map(Object f, Object[] l) { return map(f, asList(l)); } static WeakReference creator_class; static Class creator() { return creator_class == null ? null : creator_class.get(); } static void fillJMenu(JMenu m, Object... x) { if (x == null) return; for (int i = 0; i < l(x); i++) { Object o = x[i], y = get(x, i+1); if (o instanceof List) fillJMenu(m, asArray((List) o)); else if (eqOneOf(o, "***", "---", "===", "")) m.addSeparator(); else if (o instanceof String && y instanceof Runnable) { m.add(jmenuItem((String) o, (Runnable) y)); ++i; } else if (o instanceof JMenuItem) m.add((JMenuItem) o); // "call" might use wrong method else if (o instanceof String || o instanceof Action || o instanceof Component) call(m, "add", o); else print("Unknown menu item: " + o); } } static int max(int a, int b) { return Math.max(a, b); } 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 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 byte max(byte[] c) { byte x = -128; for (byte d : c) if (d > x) x = d; return x; } static void restart() { nohupJavax(programID()); System.exit(0); } static Object quickExport(Object o, Object dest) { try { return quickExport_impl(o, dest, new IdentityHashMap()); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Object quickExport_impl(Object o, Object dest, IdentityHashMap seen) { try { if (o == null || o instanceof String || o instanceof Number) return o; Object oo = seen.get(o); if (oo != null) return oo; if (o instanceof List) { List l = (List) ( o); List destO = new ArrayList(l.size()); seen.put(o, destO); for (int i = 0; i < l.size(); i++) destO.add(quickExport_impl(l.get(i), dest, seen)); return destO; } if (o instanceof Map) { Map m = (Map) ( o); Map destO = new HashMap(); seen.put(o, destO); for (Object e : ((Map) o).entrySet()) destO.put( quickExport_impl(((Map.Entry) e).getKey(), dest, seen), quickExport_impl(((Map.Entry) e).getValue(), dest, seen)); return destO; } String className = o.getClass().getName(); if (className.startsWith("main$") && !isAnonymousClassName(className)) { Class destClass = getClass(dest, className); //print(o.getClass() + " => " + destClass); if (o.getClass() == destClass) return o; // no export necessary // actually make a new object(), copy fields Object destO = nuObject(destClass); seen.put(o, destO); // TODO: superclasses Field[] fields = o.getClass().getDeclaredFields(); for (Field field : fields) { if ((field.getModifiers() & Modifier.STATIC) != 0) continue; field.setAccessible(true); Object value = field.get(o); setOpt(destO, field.getName(), quickExport_impl(value, dest, seen)); } return destO; } // assume it's a shared library object return o; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static long parseLong(String s) { if (s == null) return 0; return Long.parseLong(dropSuffix("L", s)); } static long parseLong(Object s) { return Long.parseLong((String) s); } static JTextArea newTypeWriterTextArea() { JTextArea textArea = new JTextArea(); textArea.setFont(typeWriterFont()); return textArea; } static JTextArea newTypeWriterTextArea(String text) { JTextArea textArea = newTypeWriterTextArea(); textArea.setText(text); return textArea; } static String formatInt(int i, int digits) { return padLeft(str(i), '0', digits); } static void hotwire_copyOver(Class c) { synchronized(StringBuffer.class) { for (String field : litlist("print_log", "print_silent", "androidContext")) { Object o = getOpt(mc(), field); if (o != null) setOpt(c, field, o); } Object mainBot = getMainBot(); if (mainBot != null) setOpt(c, "mainBot", mainBot); setOpt(c, "creator_class", new WeakReference(mc())); } } static RGBImage loadImage(String snippetIDOrURL) { return new RGBImage(loadBufferedImage(snippetIDOrURL)); } // extended over Class.isInstance() to handle primitive types 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 int minutes() { return Calendar.getInstance().get(Calendar.MINUTE); } static List concatLists(List... lists) { List l = new ArrayList(); for (List list : lists) if (list != null) l.addAll(list); return l; } static List concatLists(Collection> lists) { List l = new ArrayList(); for (List list : lists) if (list != null) l.addAll(list); return l; } static Object nuObject(String className, Object... args) { try { return nuObject(Class.forName(className), args); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Object nuObject(Object realm, String className, Object... args) { return nuObject(_getClass(realm, className), args); } static A nuObject(Class c, Object... args) { try { Constructor m = nuObject_findConstructor(c, args); m.setAccessible(true); return (A) m.newInstance(args); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__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 new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName()); } static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) { if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } static String getClassName(Object o) { return o == null ? "null" : o.getClass().getName(); } static boolean confirmOKCancel(final Component owner, final String msg) { return isTrue(swingAndWait(new Object() { Object get() { return JOptionPane.showConfirmDialog(owner, msg, "JavaX", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION ; } public String toString() { return "JOptionPane.showConfirmDialog(owner,\r\n msg, \"JavaX\", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION"; }})); } static List collect(Collection c, String field) { return collectField(c, field); } static AbstractAction abstractAction(String name, final Runnable r) { return new AbstractAction(name) { public void actionPerformed(ActionEvent evt) { r.run(); } }; } static boolean inRange(int x, int n) { return x >= 0 && x < n; } static double parseDouble(String s) { return Double.parseDouble(s); } 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 ImageIcon imageIcon(String imageID) { try { return new ImageIcon(loadBinarySnippet(imageID).toURI().toURL()); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} 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)); } public static String loadTextFile(String fileName) { try { return loadTextFile(fileName, null); } catch (IOException e) { throw new RuntimeException(e); } } public static String loadTextFile(String fileName, String defaultContents) throws IOException { if (!new File(fileName).exists()) return defaultContents; FileInputStream fileInputStream = new FileInputStream(fileName); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); return loadTextFile(inputStreamReader); } public static String loadTextFile(File fileName) { try { return loadTextFile(fileName, null); } catch (IOException e) { throw new RuntimeException(e); } } public static String loadTextFile(File fileName, String defaultContents) throws IOException { try { return loadTextFile(fileName.getPath(), defaultContents); } catch (IOException e) { throw new RuntimeException(e); } } public static String loadTextFile(Reader reader) throws IOException { StringBuilder builder = new StringBuilder(); try { char[] buffer = new char[1024]; int n; while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n); } finally { reader.close(); } return builder.toString(); } // mainJava is a complete program, but without the !752/!759 at the top // returns link to main class static Class veryQuickJava(String mainJava) { return veryQuickJava2(mainJava); // It's just better. } static String dropSuffix(String suffix, String s) { return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s; } static String getProgramName_cache; static synchronized String getProgramName() { if (getProgramName_cache == null) getProgramName_cache = getSnippetTitle(getProgramID()); return getProgramName_cache; } static int moveToTopRightCorner_inset = 20; static void moveToTopRightCorner(Window w) { w.setLocation(getScreenSize().width-w.getWidth()-moveToTopRightCorner_inset, moveToTopRightCorner_inset); } static JFrame frameIcon(JFrame frame, String imageID) { return setFrameIconLater(frame, imageID); } static boolean startsWith(String a, String b) { return a != null && a.startsWith(b); } static boolean startsWith(List a, List b) { if (a == null || l(b) > l(a)) return false; for (int i = 0; i < l(b); i++) if (neq(a.get(i), b.get(i))) return false; return true; } static void onTitleRightClick(final JFrame frame, final Runnable r) { swingLater(new Runnable() { public void run() { try { if (!isSubstanceLAF()) print("Can't add title right click!"); else { JComponent titleBar = getTitlePaneComponent(frame); titleBar.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { if (evt.getButton() != MouseEvent.BUTTON1) r.run(); } }); } } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static Font typeWriterFont() { return new Font("Courier", Font.PLAIN, 14); } 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 JWindow showInTopRightCorner(Component c) { JWindow w = new JWindow(); w.add(c); w.pack(); moveToTopRightCorner(w); w.setVisible(true); return w; } static File loadBinarySnippet(String snippetID) { try { long id = parseSnippetID(snippetID); File f = DiskSnippetCache_getLibrary(id); if (f == null) { byte[] data = loadDataSnippetImpl(snippetID); DiskSnippetCache_putLibrary(id, data); f = DiskSnippetCache_getLibrary(id); } return f; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static String quickSubstring(String s, int i, int j) { if (i == j) return ""; return s.substring(i, j); } static void showConsole() { JFrame frame = consoleFrame(); if (frame != null) frame.setVisible(true); } static Object mainBot; static Object getMainBot() { return mainBot; } static void centerFrame(JFrame frame) { frame.setLocationRelativeTo(null); // magic trick } static List collectField(Collection c, String field) { List l = new ArrayList(); for (Object a : c) l.add(getOpt(a, field)); return l; } static String[] toStringArray(List list) { return list.toArray(new String[list.size()]); } static String[] toStringArray(Object o) { if (o instanceof String[]) return (String[]) o; else if (o instanceof List) return toStringArray((List) o); else throw fail("Not a list or array: " + structure(o)); } static boolean loadBufferedImage_useImageCache = true; static BufferedImage loadBufferedImage(String snippetIDOrURL) { try { if (isURL(snippetIDOrURL)) return ImageIO.read(new URL(snippetIDOrURL)); if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL); String snippetID = "" + parseSnippetID(snippetIDOrURL); try { // TODO: androidify File dir = new File(System.getProperty("user.home"), ".tinybrain/image-cache"); 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(snippetID); System.err.println("Loading image: " + imageURL); BufferedImage image = ImageIO.read(new URL(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 (IOException e) { throw new RuntimeException(e); } } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static BufferedImage loadBufferedImage(File file) { try { return ImageIO.read(file); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static boolean isAnonymousClassName(String s) { for (int i = 0; i < l(s); i++) if (s.charAt(i) == '$' && Character.isDigit(s.charAt(i+1))) return true; return false; } // 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()) { /*if (debug) print("Size mismatch: " + structure(pat) + " vs " + structure(tok));*/ return null; } for (int i = 1; i < pat.size(); i += 2) { String p = pat.get(i), t = tok.get(i); /*if (debug) print("Checking " + p + " against " + t);*/ if (eq(p, "*")) result.add(t); else if (!equalsIgnoreCase(unquote(p), unquote(t))) // bold change - match quoted and unquoted now return null; } return result.toArray(new String[result.size()]); } 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 void callMain(Object c, String... args) { callOpt(c, "main", new Object[] {args}); } 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 { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static void dataToTable_dynSet(List l, int i, String s) { while (i >= l.size()) l.add(""); l.set(i, s); } static List dataToTable_makeRow(Object x, List cols) { if (instanceOf(x, "DynamicObject")) x = get_raw(x, "fieldValues"); if (x instanceof Map) { Map m = (Map) ( x); List row = new ArrayList(); for (Object _field : m.keySet()) { String field = (String) ( _field); Object value = m.get(field); int col = cols.indexOf(field); if (col < 0) { cols.add(field); col = cols.size()-1; } dataToTable_dynSet(row, col, structureOrText(value)); } return row; } return litlist(structureOrText(x)); } static void runMain(Object c, String... args) { callMain(c, args); } static JFrame setFrameIconLater(final JFrame frame, final String imageID) { if (frame != null) { /*nt*/ Thread _t_2 = new Thread("Loading Icon") { public void run() { /* in run */ try { /* pcall 1*/ /* in thread */ final Image i = imageIcon(imageID).getImage(); swingLater(new Runnable() { public void run() { try { frame.setIconImage(i); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); /* in thread */ /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } /* in run */ } }; _t_2.start(); } return frame; } static File fileFromDir(File f, String name) { return f.isDirectory() ? new File(f, name) : f; } static String padLeft(String s, char c, int n) { return rep(c, n-l(s)) + s; } static boolean veryQuickJava_silent = true; // mainJava is a complete program, but without the !752/!759 at the top // returns link to main class static Class veryQuickJava2(String mainJava) { transpileRaw_silent = veryQuickJava_silent; String src = transpileRaw(mainJava); // transpiled, with lib references List libs = new ArrayList(); src = findTranslators2(src, libs); //print("Libs found: " + struct(libs)); return hotwireCore(concatLists(ll(javaCompile(src, join(" ", libs))), loadLibraries(libs))); } static void fillTableWithStrings(final JTable table, List> rows, List colNames) { fillTableWithStrings(table, rows, toStringArray(colNames)); } // thread-safe static void fillTableWithStrings(final JTable table, List> rows, String... colNames) { final DefaultTableModel model = fillTableWithStrings_makeModel(rows, colNames); swingNowOrLater(new Runnable() { public void run() { try { setTableModel(table, model); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static DefaultTableModel fillTableWithStrings_makeModel(List> rows, String... colNames) { Object[][] data = new Object[rows.size()][]; int w = 0; for (int i = 0; i < rows.size(); i++) { List l = rows.get(i); Object[] r = new Object[l.size()]; for (int j = 0; j < l.size(); j++) r[j] = l.get(j); data[i] = r; w = Math.max(w, l.size()); } Object[] columnNames = new Object[w]; for (int i = 0; i < w; i++) columnNames[i] = i < l(colNames) ? colNames[i] : "?"; return new DefaultTableModel(data, columnNames); } static void classicNohupJavax(String javaxargs) { classicNohupJavax(javaxargs, ""); } static void classicNohupJavax(String javaxargs, String vmArgs) { try { int x = latestInstalledJavaX(); File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar"); if (!xfile.isFile()) { String url = "http://tinybrain.de/x30.jar"; byte[] data = loadBinaryPage(url); if (data.length < 1000000) throw fail("Could not load " + url); saveBinaryFile(xfile.getPath(), data); } String jarPath = xfile.getPath(); if (javaxargs.startsWith("#")) javaxargs = javaxargs.substring(1); nohup("java " + vmArgs + " -jar " + (isWindows() ? winQuote(jarPath) : bashQuote(jarPath)) + " " + javaxargs); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Object getBot(String botID) { return callOpt(getMainBot(), "getBot", botID); } static boolean isSubstanceLAF() { return substanceLookAndFeelEnabled(); } static boolean substanceLookAndFeelEnabled() { return startsWith(getLookAndFeel(), "org.pushingpixels."); } static int packFrame_minw = 150, packFrame_minh = 50; static JFrame packFrame(JFrame frame) { frame.pack(); frame.setSize( max(frame.getWidth(), packFrame_minw), max(frame.getHeight(), packFrame_minh)); return frame; } static JMenuItem jmenuItem(String text, final Runnable r) { JMenuItem mi = new JMenuItem(text); mi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { r.run(); }}); return mi; } static TableWithTooltips tableWithToolTips() { return tableWithTooltips(); } static String getComputerID() { try { return computerID(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static List parse3(String s) { return dropPunctuation(javaTokPlusPeriod(s)); } static void assertTrue(Object o) { assertEquals(true, 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 int iround(double d) { return (int) Math.round(d); } static String programTitle() { return getProgramName(); } 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 { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static boolean eqOneOf(Object o, Object... l) { for (Object x : l) if (eq(o, x)) return true; return false; } static void sleepSeconds(double s) { if (s > 0) sleep(round(s*1000)); } 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 Object[] toObjectArray(List list) { return list.toArray(new Object[list.size()]); } static Dimension getScreenSize() { return Toolkit.getDefaultToolkit().getScreenSize(); } static int toInt(Object o) { if (o == null) return 0; if (o instanceof Number) return ((Number) o).intValue(); if (o instanceof String) return parseInt((String) o); throw fail("woot not int: " + getClassName(o)); } static void smartSet(Field f, Object o, Object value) throws Exception { f.setAccessible(true); // take care of common case (long to int) if (f.getType() == int.class && value instanceof Long) value = ((Long) value).intValue(); f.set(o, value); } static String sendToLocalBotOpt(String bot, String text) { if (bot == null) return null; DialogIO channel = findBot(bot); if (channel == null) { print(quote(bot) + " not found, skipping send: " + quote(text)); return null; } try { channel.readLine(); print(bot + "> " + text); channel.sendLine(text); String s = channel.readLine(); print(bot + "< " + s); return s; } catch (Throwable e) { e.printStackTrace(); return null; } finally { channel.close(); } } static boolean isURL(String s) { return s.startsWith("http://") || s.startsWith("https://"); } public static boolean isWindows() { return System.getProperty("os.name").contains("Windows"); } static boolean equalsIgnoreCase(String a, String b) { return a == null ? b == null : a.equalsIgnoreCase(b); } /** possibly improvable */ static String bashQuote(String text) { if (text == null) return null; return "\"" + text .replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\n", "\\n") .replace("\r", "\\r") + "\""; } static String bashQuote(File f) { return bashQuote(f.getAbsolutePath()); } static Object transpileRaw_trans; static Object transpileRaw_silent = true; static synchronized String transpileRaw(String mainJava) { if (transpileRaw_trans == null) // Note: we sync the whole main class on this transpileRaw_trans = hotwire("#759"); setOpt(transpileRaw_trans, "print_silent", transpileRaw_silent); set(transpileRaw_trans, "mainJava", mainJava); callMain(transpileRaw_trans); return (String) get(transpileRaw_trans, "mainJava"); } static JComponent getTitlePaneComponent(Window window) { if (!substanceLookAndFeelEnabled()) return null; JRootPane rootPane = null; if (window instanceof JFrame) { JFrame f = (JFrame) window; rootPane = f.getRootPane(); } if (window instanceof JDialog) { JDialog d = (JDialog) window; rootPane = d.getRootPane(); } if (rootPane != null) { Object /*SubstanceRootPaneUI*/ ui = rootPane.getUI(); return (JComponent) call(ui, "getTitlePane"); } return null; } static void setTableModel(JTable table, TableModel model) { int i = table.getSelectedRow(); table.setModel(model); if (i >= 0 && i < model.getRowCount()) table.setRowSelectionInterval(i, i); } // probably better than findTranslators (uses tokens) // removes invocations from src static String findTranslators2(String src, List libsOut) { List tok = javaTok(src); int i; while ((i = jfind(tok, "!")) >= 0) { setAdd(libsOut, tok.get(i+2)); clearTokens(tok, i, i+3); } return join(tok); } static void sleep(long ms) { try { Thread.sleep(ms); } catch (Exception e) { throw new RuntimeException(e); } } static void sleep() { try { print("Sleeping."); synchronized(main.class) { main.class.wait(); } } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // Data files are immutable, use centralized cache public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException { File file = new File(getGlobalCache(), "data_" + snippetID + ".jar"); return file.exists() ? file : null; } public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data); } static byte[] loadDataSnippetImpl(String snippetID) throws IOException { byte[] data; try { URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + parseSnippetID(snippetID) + "&contentType=application/binary"); System.err.println("Loading library: " + url); try { data = loadBinaryPage(url.openConnection()); } catch (IOException e) { data = null; } if (data == null || data.length == 0) { url = new URL("http://data.tinybrain.de/blobs/" + parseSnippetID(snippetID)); System.err.println("Loading library: " + url); data = loadBinaryPage(url.openConnection()); } System.err.println("Bytes loaded: " + data.length); } catch (FileNotFoundException e) { throw new IOException("Binary snippet #" + snippetID + " not found or not public"); } return data; } static Map findBot_cache = new TreeMap(); static int findBot_timeout = 5000; static DialogIO findBot(String searchPattern) { // first split off sub-bot suffix String subBot = null; int i = searchPattern.indexOf('/'); if (i >= 0 && (isJavaIdentifier(searchPattern.substring(0, i)) || isInteger(searchPattern.substring(0, i)))) { subBot = searchPattern.substring(i+1); searchPattern = searchPattern.substring(0, i); if (!isInteger(searchPattern)) searchPattern = "Multi-Port at " + searchPattern + "."; } // assume it's a port if it's an integer if (isInteger(searchPattern)) return talkToSubBot(subBot, talkTo(parseInt(searchPattern))); if (eq(searchPattern, "remote")) return talkToSubBot(subBot, talkTo("second.tinybrain.de", 4999)); Integer port = findBot_cache.get(searchPattern); if (port != null) try { DialogIO io = talkTo("localhost", port); io.waitForLine(/*findBot_timeout*/); // TODO: implement String line = io.readLineNoBlock(); if (indexOfIgnoreCase(line, searchPattern) == 0) { call(io, "pushback", line); // put hello string back in return talkToSubBot(subBot, io); } } catch (Exception e) { e.printStackTrace(); } List bots = quickBotScan(); // find top-level bots for (ProgramScan.Program p : bots) { if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) { // strict matching - start of hello string only, but case-insensitive findBot_cache.put(searchPattern, p.port); return talkToSubBot(subBot, talkTo("localhost", p.port)); } } // find sub-bots for (ProgramScan.Program p : bots) { String botName = firstPartOfHelloString(p.helloString); boolean isVM = startsWithIgnoreCase(p.helloString, "This is a JavaX VM."); boolean shouldRecurse = startsWithIgnoreCase(botName, "Multi-Port") || isVM; if (shouldRecurse) try { Map subBots = (Map) unstructure(sendToLocalBot(p.port, "list bots")); for (Number vport : subBots.keySet()) { String name = subBots.get(vport); if (startsWithIgnoreCase(name, searchPattern)) return talkToSubBot(vport.longValue(), talkTo("localhost", p.port)); } } catch (Exception e) { e.printStackTrace(); } } return null; } /** possibly improvable */ public static String winQuote(String text) { if (text == null) return null; return "\"" + text .replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\n", "\\n") .replace("\r", "\\r") + "\""; } static boolean instanceOf(Object o, String className) { if (o == null) return false; String c = o.getClass().getName(); return eq(c, className) || eq(c, "main$" + className); } static String _computerID; public static String computerID() { try { if (_computerID == null) { File file = new File(userHome(), ".tinybrain/computer-id"); _computerID = loadTextFile(file.getPath(), null); if (_computerID == null) { _computerID = makeRandomID(12); saveTextFile(file.getPath(), _computerID); } } return _computerID; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} 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 boolean isNonNegativeInteger(String s) { return s != null && Pattern.matches("\\d+", s); } static String classNameToVM(String name) { return name.replace(".", "$"); } static String snippetImageURL(String snippetID) { long id = parseSnippetID(snippetID); String url; if (id == 1000010 || id == 1000012) url = "http://tinybrain.de:8080/tb/show-blobimage.php?id=" + id; else url = "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=image/png"; return url; } // 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(); 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 == '\u201C' || c == '\u201D') c = '"'; // normalize quotes if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { char _c = s.charAt(j); if (_c == '\u201C' || _c == '\u201D') _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; } /** writes safely (to temp file, then rename) */ public static void saveBinaryFile(String fileName, byte[] contents) throws IOException { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = new FileOutputStream(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); } static void saveBinaryFile(File fileName, byte[] contents) { try { saveBinaryFile(fileName.getPath(), contents); } catch (IOException e) { throw new RuntimeException(e); } } static List loadLibraries(List snippetIDs) { return map("loadLibrary", snippetIDs); } static JFrame consoleFrame() { return (JFrame) getOpt(get(getJavaX(), "console"), "frame"); } static Class hotwireCore(List urlsOrFiles) { List urls = map("toURL", urlsOrFiles); return hotwireCore((URL[]) asArray(URL.class, urls)); } static Class hotwireCore(URL... urls) { try { // make class loader URLClassLoader classLoader = new URLClassLoader(urls); // load & return main class Class theClass = classLoader.loadClass("main"); if (!_inCore()) hotwire_copyOver(theClass); return theClass; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static String _userHome; static String userHome() { if (_userHome == null) { if (isAndroid()) _userHome = "/storage/sdcard0/"; else _userHome = System.getProperty("user.home"); //System.out.println("userHome: " + _userHome); } return _userHome; } static File userHome(String path) { return new File(userDir(), path); } static A assertEquals(Object x, A y) { return assertEquals(null, x, y); } static A assertEquals(String msg, Object x, A y) { if (!(x == null ? y == null : x.equals(y))) throw fail((msg != null ? msg + ": " : "") + structure(x) + " != " + structure(y)); return y; } static boolean isIdentifier(String s) { return isJavaIdentifier(s); } static String getLookAndFeel() { return getClassName(UIManager.getLookAndFeel()); } static int latestInstalledJavaX() { File[] files = new File(userHome(), ".javax").listFiles(); int v = 0; if (files != null) for (File f : files) { Matcher m = Pattern.compile("x(\\d\\d\\d?)\\.jar").matcher(f.getName()); if (m.matches()) v = Math.max(v, Integer.parseInt(m.group(1))); } return v; } public static File nohup(String cmd) throws IOException { File outFile = File.createTempFile("nohup_" + nohup_sanitize(cmd), ".out"); nohup(cmd, outFile, false); return outFile; } static String nohup_sanitize(String s) { return s.replaceAll("[^a-zA-Z0-9\\-_]", ""); } /** outFile takes stdout and stderr. */ public static void nohup(String cmd, File outFile, boolean append) throws IOException { String command = nohup_makeNohupCommand(cmd, outFile, append); File scriptFile = File.createTempFile("_realnohup", isWindows() ? ".bat" : ""); System.out.println("[Nohup] " + command); try { //System.out.println("[RealNohup] Script file: " + scriptFile.getPath()); saveTextFile(scriptFile.getPath(), command); String[] command2; if (isWindows()) command2 = new String[] {"cmd", "/c", "start", "/b", scriptFile.getPath() }; else command2 = new String[] {"/bin/bash", scriptFile.getPath() }; Process process = Runtime.getRuntime().exec(command2); try { process.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e); } int value = process.exitValue(); //System.out.println("exit value: " + value); } finally { if (!isWindows()) scriptFile.delete(); } } public static String nohup_makeNohupCommand(String cmd, File outFile, boolean append) { mkdirsForFile(outFile); String command; if (isWindows()) command = cmd + (append ? " >>" : " >") + winQuote(outFile.getPath()) + " 2>&1"; else command = "nohup " + cmd + (append ? " >>" : " >") + bashQuote(outFile.getPath()) + " 2>&1 &"; return command; } static List dropPunctuation_keep = litlist("*", "<", ">"); 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 byte[] loadBinaryPage(String url) throws IOException { return loadBinaryPage(new URL(url).openConnection()); } public static byte[] loadBinaryPage(URLConnection con) throws IOException { //setHeaders(con); ByteArrayOutputStream buf = new ByteArrayOutputStream(); InputStream inputStream = con.getInputStream(); int n = 0; while (true) { int ch = inputStream.read(); if (ch < 0) break; buf.write(ch); if (++n % 100000 == 0) System.err.println(" " + n + " bytes loaded."); } inputStream.close(); return buf.toByteArray(); } static File javaCompile(String src) { return javaCompile(src, ""); } // returns path to classes dir static synchronized File javaCompile(String src, String dehlibs) { String javaTarget = null; // use default target //print("Compiling " + l(src) + " chars"); Class j = getJavaX(); if (javaTarget != null) setOpt(j, "javaTarget", javaTarget); //setOpt(j, "verbose", true); File srcDir = (File) ( call(j, "TempDirMaker_make")); String className = getNameOfPublicClass(javaTok(src)); String fileName = className + ".java"; File mainJava = new File(srcDir, fileName); //print("main java: " + mainJava.getAbsolutePath()); saveTextFile(mainJava, src); File classesDir = (File) call(j, "TempDirMaker_make"); List libraries = new ArrayList(); Matcher m = Pattern.compile("\\d+").matcher(dehlibs); while (m.find()) { String libID = m.group(); //print("libID=" + quote(libID)); assertTrue(isSnippetID(libID)); libraries.add(loadLibrary(libID)); } try { // This seems to be empty in case of success with Eclipse compiler. String compilerOutput = (String) ( call(j, "compileJava", srcDir, libraries, classesDir)); if (nempty(compilerOutput)) print("Compiler said: " + quote(compilerOutput)); // sanity test if (!new File(classesDir, className + ".class").exists()) throw fail("No class generated (" + className + ")"); } catch (Exception e) { //e.printStackTrace(); throw fail("Compile Error\n" + getOpt(j, "javaCompilerOutput")); } return classesDir; } static long round(double d) { return Math.round(d); } static DialogIO talkToSubBot(final long vport, final DialogIO io) { return talkToSubBot(String.valueOf(vport), io); } static DialogIO talkToSubBot(final String subBot, final DialogIO io) { if (subBot == null) return io; return new DialogIO() { // delegate all but sendLine boolean isStillConnected() { return io.isStillConnected(); } String readLineImpl() { return io.readLineImpl(); } boolean isLocalConnection() { return io.isLocalConnection(); } Socket getSocket() { return io.getSocket(); } void close() { io.close(); } void sendLine(String line) { io.sendLine(format3("please forward to bot *: *", subBot, line)); } }; } static URL toURL(Object o) { try { if (o instanceof URL) return (URL) o; if (o instanceof String) return new URL((String) o); if (o instanceof File) return fileToURL((File) o); throw fail("Can't convert to URL: " + o); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static File getGlobalCache() { File file = new File(userHome(), ".tinybrain/snippet-cache"); file.mkdirs(); return file; } static String firstPartOfHelloString(String s) { int i = s.lastIndexOf('/'); return i < 0 ? s : rtrim(s.substring(0, i)); } static String getNameOfPublicClass(List tok) { for (List c : allClasses(tok)) if (hasModifier(c, "public")) return getClassDeclarationName(c); return null; } static void clearTokens(List tok) { clearAllTokens(tok); } static void clearTokens(List tok, int i, int j) { clearAllTokens(tok, i, j); } static List quickBotScan() { return ProgramScan.quickBotScan(); } static List quickBotScan(int[] preferredPorts) { return ProgramScan.quickBotScan(preferredPorts); } static List quickBotScan(String searchPattern) { List l = new ArrayList(); for (ProgramScan.Program p : ProgramScan.quickBotScan()) if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) l.add(p); return l; } static List nlTok(String s) { return javaTokPlusPeriod(s); } static int jfind(List tok, String in) { List tokin = javaTok(in); jfind_preprocess(tokin); return findCodeTokens(tok, false, toStringArray(codeTokensOnly(tokin))); } static void jfind_preprocess(List tok) { for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, litlist("<", "", type, "", ">"), litlist("<" + type + ">")); } static DialogIO talkTo(int port) { return talkTo("localhost", port); } static int talkTo_defaultTimeout = 10000; static DialogIO talkTo(String ip, int port) { try { final Socket s = new Socket(); s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout); //print("Talking to " + ip + ":" + port); final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8"); final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8")); return new DialogIO() { boolean isLocalConnection() { return s.getInetAddress().isLoopbackAddress(); } boolean isStillConnected() { return !(eos || s.isClosed()); } void sendLine(String line) { try { w.write(line + "\n"); w.flush(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} String readLineImpl() { try { return in.readLine(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} void close() { try { s.close(); } catch (IOException e) { // whatever } } Socket getSocket() { return s; } }; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static String sendToLocalBot(String bot, String text, Object... args) { text = format3(text, args); DialogIO channel = findBot(bot); if (channel == null) throw fail(quote(bot) + " not found"); try { channel.readLine(); print(bot + "> " + shorten(text, 80)); channel.sendLine(text); String s = channel.readLine(); print(bot + "< " + shorten(s, 80)); return s; } catch (Throwable e) { e.printStackTrace(); return null; } finally { channel.close(); } } static String sendToLocalBot(int port, String text, Object... args) { text = format3(text, args); DialogIO channel = talkTo(port); try { channel.readLine(); print(port + "> " + shorten(text, 80)); channel.sendLine(text); String s = channel.readLine(); print(port + "< " + shorten(s, 80)); return s; } catch (Throwable e) { e.printStackTrace(); return null; } finally { if (channel != null) channel.close(); } } // works on lists and strings and null static int indexOfIgnoreCase(Object a, Object b) { if (a == null) return -1; if (a instanceof String) { Matcher m = Pattern.compile((String) b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher((String) a); if (m.find()) return m.start(); else return -1; } if (a instanceof List) { for (int i = 0; i < ((List) a).size(); i++) { Object o = ((List) a).get(i); if (o != null && ((String) o).equalsIgnoreCase((String) b)) return i; } return -1; } throw fail("Unknown type: " + a); } static File loadLibrary(String snippetID) { return loadBinarySnippet(snippetID); } static String repeat(char c, int n) { n = 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) { List l = new ArrayList(); for (int i = 0; i < n; i++) l.add(a); return l; } static File userDir() { return new File(userHome()); } static File userDir(String path) { return new File(userHome(), path); } static boolean isAndroid() { return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0; } static String getClassDeclarationName(List c) { for (int i = 1; i+2 < c.size(); i += 2) if (eqOneOf(c.get(i), "class", "interface")) return c.get(i+2); return null; } static URL fileToURL(File f) { try { return f.toURI().toURL(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // lists returned are actual CNC (N/C/N/.../C/N) - and connected to // original list // only returns the top level classes static List> allClasses(List tok) { List> l = new ArrayList(); for (int i = 1; i < tok.size(); i += 2) { if (eqOneOf(tok.get(i), "class", "interface") && (i == 1 || !tok.get(i-2).equals("."))) { int j = i; while (j < tok.size() && !tok.get(j).equals("{")) j += 2; j = findEndOfBlock(tok, j)+1; i = leftScanModifiers(tok, i); l.add(tok.subList(i-1, Math.min(tok.size(), j))); i = j-2; } } return l; } static List> allClasses(String text) { return allClasses(javaTok(text)); } 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; // It's inefficient :D for (int j = 0; j < l(x); j++) l.remove(i); l.addAll(i, y); i += l(y); } return l; } // scans a Java construct (class, method) and checks its modifiers static boolean hasModifier(List tok, String modifier) { for (int i = 1; i < tok.size() && getJavaModifiers().contains(tok.get(i)); i += 2) if (tok.get(i).equals(modifier)) return true; return false; } 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 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 List findCodeTokens_specials = litlist("*", "", "", "", "\\*"); static boolean findCodeTokens_debug; static int findCodeTokens_indexed, findCodeTokens_unindexed; static int findCodeTokens_bails, findCodeTokens_nonbails; static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) { if (findCodeTokens_debug) { if (eq(getClassName(tok), "main$IndexedList2")) findCodeTokens_indexed++; else findCodeTokens_unindexed++; } // bail out early if first token not found (works great with IndexedList) if (!findCodeTokens_specials.contains(tokens[0]) && !tok.contains(tokens[0] /*, startIdx << no signature in List for this, unfortunately */)) { ++findCodeTokens_bails; return -1; } ++findCodeTokens_nonbails; outer: for (int i = startIdx | 1; i+tokens.length*2-2 < tok.size(); i += 2) { for (int j = 0; j < tokens.length; j++) { String p = tokens[j], t = tok.get(i+j*2); boolean match; if (eq(p, "*")) match = true; else if (eq(p, "")) match = isQuoted(t); else if (eq(p, "")) match = isIdentifier(t); else if (eq(p, "")) match = isInteger(t); else if (eq(p, "\\*")) match = eq("*", t); else match = ignoreCase ? eqic(p, t) : eq(p, t); if (!match) continue outer; } if (condition == null || checkCondition(condition, tok, i-1)) // pass N index return i; } return -1; } public static String rtrim(String s) { 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; } 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; } // supports the usual quotings (', ", variable length double brackets) static boolean isQuoted(String s) { if (s.startsWith("'") || s.startsWith("\"")) return true; if (!s.startsWith("[")) return false; int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; return i < s.length() && s.charAt(i) == '['; //return Pattern.compile("^\\[=*\\[").matcher(s).find(); } static boolean checkCondition(Object condition, Object... args) { return isTrue(call(condition, "check", args)); } static int leftScanModifiers(List tok, int i) { List mod = getJavaModifiers(); while (i > 1 && mod.contains(tok.get(i-2))) i -= 2; return i; } static List getJavaModifiers_list = litlist("static", "abstract", "public", "private", "protected", "final", "native", "volatile", "synchronized", "transient"); static List getJavaModifiers() { return getJavaModifiers_list; } // i must point at the opening bracket ("{") // index returned is index of closing bracket + 1 static int findEndOfBlock(List cnc, int i) { int j = i+2, level = 1; while (j < cnc.size()) { if (cnc.get(j).equals("{")) ++level; else if (cnc.get(j).equals("}")) --level; if (level == 0) return j+1; ++j; } return cnc.size(); } // should be thread-safe by nature // compare efficiently due to md5 caching // tested with A = S static class ImmL extends AbstractList { List l = new ArrayList(); int hash; String md5; ImmL() {} ImmL(List _l) { l.addAll(_l); } // List methods public int size() { return l.size(); } public A get(int i) { return l.get(i); } public synchronized int hashCode() { if (hash == 0) hash = l.hashCode(); return hash; } public boolean equals(Object o) { if (o instanceof ImmL && neq(md5(), ((ImmL) o).md5())) return false; return super.equals(o); } public synchronized String md5() { if (md5 == null) md5 = main.md5(structure(l)); return md5; } } static class Gen { String name; Object func; Gen() {} Gen(String name, Object func) { this.func = func; this.name = name;} public String toString() { return name; } } static class Var { A v; Var() {} Var(A v) { this.v = v;} synchronized void set(A a) { v = a; } synchronized A get() { return v; } } static class ProgramScan { static int threads = isWindows() ? 500 : 10; static int timeout = 5000; // hmm... static String ip = "127.0.0.1"; // This range is not used anymore anyway static int quickScanFrom = 10000, quickScanTo = 10999; static int maxNumberOfVMs_android = 4; // Android will always only have one if we don't screw up static int maxNumberOfVMs_nonAndroid = 50; // 100; static int maxNumberOfVMs; static boolean verbose; static class Program { int port; String helloString; Program(int port, String helloString) { this.helloString = helloString; this.port = port;} } static List scan() { try { return scan(1, 65535); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static List scan(int fromPort, int toPort) { return scan(fromPort, toPort, new int[0]); } static List scan(int fromPort, int toPort, int[] preferredPorts) { try { Set preferredPortsSet = new HashSet(asList(preferredPorts)); int scanSize = toPort-fromPort+1; String name = toPort < 10000 ? "bot" : "program"; int threads = isWindows() ? min(500, scanSize) : min(scanSize, 10); final ExecutorService es = Executors.newFixedThreadPool(threads); if (verbose) print(firstToUpper(name) + "-scanning " + ip + " with timeout " + timeout + " ms in " + threads + " threads."); startTiming(); List> futures = new ArrayList>(); for (int port : preferredPorts) futures.add(checkPort(es, ip, port, timeout)); for (int port = fromPort; port <= toPort; port++) if (!preferredPortsSet.contains(port)) futures.add(checkPort(es, ip, port, timeout)); es.shutdown(); List programs = new ArrayList(); for (final Future f : futures) { Program p = f.get(); if (p != null) programs.add(p); } stopTiming("Port Scan " + scanSize + ": "); if (verbose) print("Found " + programs.size() + " " + name + "(s) on " + ip); return programs; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Future checkPort(final ExecutorService es, final String ip, final int port, final int timeout) { return es.submit(new Callable() { @Override public Program call() { try { Socket socket = new Socket(); socket.setSoTimeout(timeout); socket.connect(new InetSocketAddress(ip, port), timeout); //if (verbose) print("Connected to " + ip + ":" + port); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream(), "UTF-8")); String hello = or(in.readLine(), "?"); socket.close(); return new Program(port, hello); } catch (Exception ex) { return null; } } }); } static List quickScan() { return scan(quickScanFrom, quickScanTo); } static List quickBotScan() { return quickBotScan(new int[0]); } static List quickBotScan(int[] preferredPorts) { if (maxNumberOfVMs == 0) maxNumberOfVMs = isAndroid() ? maxNumberOfVMs_android : maxNumberOfVMs_nonAndroid; return scan(4999, 5000+maxNumberOfVMs-1, preferredPorts); } } static abstract class DialogIO { String line; boolean eos; abstract String readLineImpl(); abstract boolean isStillConnected(); abstract void sendLine(String line); abstract boolean isLocalConnection(); abstract Socket getSocket(); abstract void close(); int getPort() { return getSocket().getPort(); } boolean helloRead; String readLineNoBlock() { String l = line; line = null; return l; } boolean waitForLine() { try { if (line != null) return true; //print("Readline"); line = readLineImpl(); //print("Readline done: " + line); if (line == null) eos = true; return line != null; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} String readLine() { waitForLine(); helloRead = true; return readLineNoBlock(); } String ask(String s, Object... args) { if (!helloRead) readLine(); if (args.length != 0) s = format3(s, args); sendLine(s); return readLine(); } String askLoudly(String s, Object... args) { if (!helloRead) readLine(); if (args.length != 0) s = format3(s, args); print("> " + s); sendLine(s); String answer = readLine(); print("< " + answer); return answer; } void pushback(String l) { if (line != null) throw fail(); line = l; helloRead = false; } } static abstract class DialogHandler { abstract void run(DialogIO io); } static class Matches { String[] m; String get(int i) { return i < m.length ? m[i] : null; } String unq(int i) { return unquote(get(i)); } String fsi(int i) { return formatSnippetID(unq(i)); } String fsi() { return fsi(0); } 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)); } } // Now uses TreeMap for nicer sorting (i.e., A must be a orderable type) static class MultiSet { Map map = new TreeMap(); public MultiSet(boolean useTreeMap) { if (!useTreeMap) map = new HashMap(); } public MultiSet() { } public MultiSet(Collection c) { addAll(c); } public void add(A key) { add(key, 1); } public void addAll(Collection c) { if (c != null) for (A a : c) add(a); } public void add(A key, int count) { if (map.containsKey(key)) map.put(key, map.get(key)+count); else map.put(key, count); } public int get(A key) { return key != null && map.containsKey(key) ? map.get(key) : 0; } public boolean contains(A key) { return map.containsKey(key); } public void remove(A key) { Integer i = map.get(key); if (i != null && i > 1) map.put(key, i - 1); else map.remove(key); } public List getTopTen() { return getTopTen(10); } public List getTopTen(int maxSize) { List list = getSortedListDescending(); return list.size() > maxSize ? list.subList(0, maxSize) : list; } public List getSortedListDescending() { List list = new ArrayList(map.keySet()); Collections.sort(list, new Comparator() { public int compare(A a, A b) { return map.get(b).compareTo(map.get(a)); } }); return list; } public int getNumberOfUniqueElements() { return map.size(); } public Set asSet() { return map.keySet(); } public A getMostPopularEntry() { int max = 0; A a = null; for (Map.Entry entry : map.entrySet()) { if (entry.getValue() > max) { max = entry.getValue(); a = entry.getKey(); } } return a; } public void removeAll(A key) { map.remove(key); } public int size() { int size = 0; for (int i : map.values()) size += i; return size; } public MultiSet mergeWith(MultiSet set) { MultiSet result = new MultiSet(); for (A a : set.asSet()) { result.add(a, set.get(a)); } return result; } public boolean isEmpty() { return map.isEmpty(); } public String toString() { return structure(this); } public void clear() { map.clear(); } } static class RGB { public final float r, g, b; 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(double brightness) { this.r = this.g = this.b = (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) { r = Integer.parseInt(hex.substring(0, 2), 16)/255f; g = Integer.parseInt(hex.substring(2, 4), 16)/255f; b = Integer.parseInt(hex.substring(4, 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))); } public int asInt() { 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(); } } static class RGBImage { private BufferedImage bufferedImage; private File file; private int width, height; private int[] pixels; // color returned when getPixel is called with out-of-bounds position private int background = 0xFFFFFF; public RGBImage(BufferedImage image) { this(image, null); } public 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 */ public RGBImage(String file) throws IOException { this(new File(file)); } public RGBImage(Dimension size, Color color) { this(size.width, size.height, color); } public 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; } public RGBImage(int width, int height, int[] pixels) { this.width = width; this.height = height; this.pixels = pixels; } public 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); } public 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; } public RGBImage(RGBImage image) { this(image.width, image.height, copyPixels(image.pixels)); } public RGBImage(int width, int height, Color color) { this(width, height, new RGB(color)); } public RGBImage(File file) throws IOException { this(javax.imageio.ImageIO.read(file)); } 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 background; } 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(background); } /** alias of getRGB - I kept typing getPixel instead of getRGB all the time, so I finally created it */ public RGB getPixel(int x, int y) { return getRGB(x, y); } public int getWidth() { return width; } public int getHeight() { 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; } public RGBImage clip(Rectangle r) { r = fixClipRect(r); 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; } 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)); } public void setPixel(int x, int y, int rgb) { if (x >= 0 && y >= 0 && x < width && y < height) pixels[y*width+x] = rgb; } public RGBImage copy() { return new RGBImage(this); } public boolean inRange(int x, int y) { return x >= 0 && y >= 0 && x < width && y < height; } public int getBackground() { return background; } public void setBackground(int background) { this.background = background; } 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; } } abstract static class Surface extends JPanel { public Object AntiAlias = RenderingHints.VALUE_ANTIALIAS_ON; public Object Rendering = RenderingHints.VALUE_RENDER_SPEED; public AlphaComposite composite; public Paint texture; public BufferedImage bimg; public int imageType; public String name; public boolean clearSurface = true; // Demos using animated gif's that implement ImageObserver set dontThread. public boolean dontThread; protected long sleepAmount = 50; // max20 fps private long orig, start, frame; private Toolkit toolkit; private boolean perfMonitor, outputPerf; private int biw, bih; private boolean clearOnce; private boolean toBeInitialized = true; public Surface() { setDoubleBuffered(false); toolkit = getToolkit(); name = this.getClass().getName(); name = name.substring(name.indexOf(".", 7)+1); setImageType(0); // To launch an individual demo with the performance str output : // java -Djava2demo.perf= -cp Java2Demo.jar demos.Clipping.ClipAnim try { if (System.getProperty("java2demo.perf") != null) { perfMonitor = outputPerf = true; } } catch (Exception ex) { } } /*protected Image getImage(String name) { return DemoImages.getImage(name, this); } protected Font getFont(String name) { return DemoFonts.getFont(name); }*/ public int getImageType() { return imageType; } public void setImageType(int imgType) { if (imgType == 0) { imageType = 1; } else { imageType = imgType; } bimg = null; } public void setAntiAlias(boolean aa) { AntiAlias = aa ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF; } public void setRendering(boolean rd) { Rendering = rd ? RenderingHints.VALUE_RENDER_QUALITY : RenderingHints.VALUE_RENDER_SPEED; } public void setTexture(Object obj) { if (obj instanceof GradientPaint) { texture = new GradientPaint(0, 0, Color.white, getSize().width*2, 0, Color.green); } else { texture = (Paint) obj; } } public void setComposite(boolean cp) { composite = cp ? AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f) : null; } public void setMonitor(boolean pm) { perfMonitor = pm; } public void setSleepAmount(long amount) { sleepAmount = amount; } public long getSleepAmount() { return sleepAmount; } public BufferedImage createBufferedImage(Graphics2D g2, int w, int h, int imgType) { BufferedImage bi = null; if (imgType == 0) { bi = (BufferedImage) g2.getDeviceConfiguration(). createCompatibleImage(w, h); } else if (imgType > 0 && imgType < 14) { bi = new BufferedImage(w, h, imgType); } else if (imgType == 14) { bi = createBinaryImage(w, h, 2); } else if (imgType == 15) { bi = createBinaryImage(w, h, 4); } else if (imgType == 16) { bi = createSGISurface(w, h, 32); } else if (imgType == 17) { bi = createSGISurface(w, h, 16); } biw = w; bih = h; return bi; } // Lookup tables for BYTE_BINARY 1, 2 and 4 bits. static byte[] lut1Arr = new byte[] {0, (byte)255 }; static byte[] lut2Arr = new byte[] {0, (byte)85, (byte)170, (byte)255}; static byte[] lut4Arr = new byte[] {0, (byte)17, (byte)34, (byte)51, (byte)68, (byte)85,(byte) 102, (byte)119, (byte)136, (byte)153, (byte)170, (byte)187, (byte)204, (byte)221, (byte)238, (byte)255}; private BufferedImage createBinaryImage(int w, int h, int pixelBits) { int bytesPerRow = w * pixelBits / 8; if (w * pixelBits % 8 != 0) { bytesPerRow++; } byte[] imageData = new byte[h * bytesPerRow]; IndexColorModel cm = null; switch (pixelBits) { case 1: cm = new IndexColorModel(pixelBits, lut1Arr.length, lut1Arr, lut1Arr, lut1Arr); break; case 2: cm = new IndexColorModel(pixelBits, lut2Arr.length, lut2Arr, lut2Arr, lut2Arr); break; case 4: cm = new IndexColorModel(pixelBits, lut4Arr.length, lut4Arr, lut4Arr, lut4Arr); break; default: {new Exception("Invalid # of bit per pixel").printStackTrace();} } DataBuffer db = new DataBufferByte(imageData, imageData.length); WritableRaster r = Raster.createPackedRaster(db, w, h, pixelBits, null); return new BufferedImage(cm, r, false, null); } private BufferedImage createSGISurface(int w, int h, int pixelBits) { int rMask32 = 0xFF000000; int rMask16 = 0xF800; int gMask32 = 0x00FF0000; int gMask16 = 0x07C0; int bMask32 = 0x0000FF00; int bMask16 = 0x003E; DirectColorModel dcm = null; DataBuffer db = null; WritableRaster wr = null; switch (pixelBits) { case 16: short[] imageDataUShort = new short[w * h]; dcm = new DirectColorModel(16, rMask16, gMask16, bMask16); db = new DataBufferUShort(imageDataUShort, imageDataUShort.length); wr = Raster.createPackedRaster(db, w, h, w, new int[] {rMask16, gMask16, bMask16}, null); break; case 32: int[] imageDataInt = new int[w * h]; dcm = new DirectColorModel(32, rMask32, gMask32, bMask32); db = new DataBufferInt(imageDataInt, imageDataInt.length); wr = Raster.createPackedRaster(db, w, h, w, new int[] {rMask32, gMask32, bMask32}, null); break; default: {new Exception("Invalid # of bit per pixel").printStackTrace();} } return new BufferedImage(dcm, wr, false, null); } public Graphics2D createGraphics2D(int width, int height, BufferedImage bi, Graphics g) { Graphics2D g2 = null; if (bi != null) { g2 = bi.createGraphics(); } else { g2 = (Graphics2D) g; } g2.setBackground(getBackground()); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, AntiAlias); g2.setRenderingHint(RenderingHints.KEY_RENDERING, Rendering); if (clearSurface || clearOnce) { g2.clearRect(0, 0, width, height); clearOnce = false; } if (texture != null) { // set composite to opaque for texture fills g2.setComposite(AlphaComposite.SrcOver); g2.setPaint(texture); g2.fillRect(0, 0, width, height); } if (composite != null) { g2.setComposite(composite); } return g2; } public abstract void render(int w, int h, Graphics2D g); /** * It's possible to turn off double-buffering for just the repaint * calls invoked directly on the non double buffered component. * This can be done by overriding paintImmediately() (which is called * as a result of repaint) and getting the current RepaintManager and * turning off double buffering in the RepaintManager before calling * super.paintImmediately(g). */ public void paintImmediately(int x,int y,int w, int h) { RepaintManager repaintManager = null; boolean save = true; if (!isDoubleBuffered()) { repaintManager = RepaintManager.currentManager(this); save = repaintManager.isDoubleBufferingEnabled(); repaintManager.setDoubleBufferingEnabled(false); } super.paintImmediately(x, y, w, h); if (repaintManager != null) { repaintManager.setDoubleBufferingEnabled(save); } } public void paint(Graphics g) { Dimension d = getSize(); if (imageType == 1) bimg = null; else if (bimg == null || biw != d.width || bih != d.height) { bimg = createBufferedImage((Graphics2D)g, d.width, d.height, imageType-2); clearOnce = true; toBeInitialized = true; } if (toBeInitialized) { toBeInitialized = false; startClock(); } Graphics2D g2 = createGraphics2D(d.width, d.height, bimg, g); render(d.width, d.height, g2); g2.dispose(); if (bimg != null) { g.drawImage(bimg, 0, 0, null); toolkit.sync(); } } public void startClock() { orig = System.currentTimeMillis(); start = orig; frame = 0; } private static final int REPORTFRAMES = 30; public static void setAlpha(Graphics2D g, float alpha) { g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); } } static class ImageSurface extends Surface { private BufferedImage image; private double zoomX = 1, zoomY = 1; private Rectangle selection; public ImageSurface() { this(new RGBImage(1, 1, new int[] { 0xFFFFFF })); } public ImageSurface(RGBImage image) { this(image.getBufferedImage()); } public ImageSurface(BufferedImage image) { clearSurface = false; this.image = image; /*addMouseMotionListener(new MouseAdapter() { public void mouseMoved(MouseEvent e) { getMousePosition() } });*/ } public ImageSurface(RGBImage image, double zoom) { this(image); setZoom(zoom); } public void render(int w, int h, Graphics2D g) { g.setColor(Color.white); g.fillRect(0, 0, w, h); if (image != null) g.drawImage(image, 0, 0, getZoomedWidth(), getZoomedHeight(), null); if (selection != null) { // drawRect is inclusive, selection is exclusive, so... whatever, tests show it's cool. drawSelectionRect(g, selection, Color.green, Color.white); } } public void drawSelectionRect(Graphics2D g, Rectangle selection, Color green, Color white) { g.setColor(green); int top = (int) (selection.y * zoomY); int bottom = (int) ((selection.y+selection.height) * zoomY); int left = (int) (selection.x * zoomX); int right = (int) ((selection.x+selection.width) * zoomX); g.drawRect(left-1, top-1, right-left+1, bottom-top+1); g.setColor(white); g.drawRect(left - 2, top - 2, right - left + 3, bottom - top + 3); } public void setZoom(double zoom) { setZoom(zoom, zoom); } public void setZoom(double zoomX, double zoomY) { this.zoomX = zoomX; this.zoomY = zoomY; revalidate(); repaint(); } public Dimension getMinimumSize() { int w = getZoomedWidth(); int h = getZoomedHeight(); Dimension min = super.getMinimumSize(); return new Dimension(Math.max(w, min.width), Math.max(h, min.height)); } private int getZoomedHeight() { return (int) (image.getHeight() * zoomY); } private int getZoomedWidth() { return (int) (image.getWidth() * zoomX); } public void setImage(RGBImage image) { setImage(image.getBufferedImage()); } public void setImage(BufferedImage image) { this.image = image; revalidate(); repaint(); } public BufferedImage getImage() { return image; } public double getZoomX() { return zoomX; } public double getZoomY() { return zoomY; } public Dimension getPreferredSize() { return new Dimension(getZoomedWidth(), getZoomedHeight()); } /** returns a scrollpane with the scroll-mode prevent-garbage-drawing fix applied */ public JScrollPane makeScrollPane() { JScrollPane scrollPane = new JScrollPane(this); scrollPane.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE); return scrollPane; } public void zoomToDisplaySize() { if (image == null) return; Dimension display = getDisplaySize(); double xRatio = display.width/(double) image.getWidth(); double yRatio = display.height/(double) image.getHeight(); setZoom(Math.min(xRatio, yRatio)); revalidate(); } /** tricky magic to get parent scroll pane */ private Dimension getDisplaySize() { Container c = getParent(); while (c != null) { if (c instanceof JScrollPane) return c.getSize(); c = c.getParent(); } return getSize(); } public void setSelection(Rectangle r) { selection = r; repaint(); } public Rectangle getSelection() { return selection; } public RGBImage getRGBImage() { return new RGBImage(getImage()); } } static long stopTiming_defaultMin = 10; static long startTiming_startTime; static void startTiming() { startTiming_startTime = now(); } static void stopTiming() { stopTiming(null); } static void stopTiming(String text) { stopTiming(text, stopTiming_defaultMin); } static void stopTiming(String text, long minToPrint) { long time = now()-startTiming_startTime; if (time >= minToPrint) { text = or2(text, "Time: "); print(text + time + " ms"); } } static void revalidate(Component c) { if (c == null) return; // magic combo to actually relayout and repaint c.revalidate(); c.repaint(); } static BufferedReader readLine_reader; static String readLine() { return (String) call(getJavaX(), "readLine"); } static void swingNowOrLater(Runnable r) { if (isAWTThread()) r.run(); else swingLater(r); } 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(Collection l) { TreeSet set = new TreeSet(); for (String o : l) if (o != null) set.add(o); return set; } static boolean equals(Object a, Object b) { return a == null ? b == null : a.equals(b); } static String md5(String text) { try { if (text == null) return "-"; return bytesToHex(md5_impl(text.getBytes("UTF-8"))); // maybe different than the way PHP does it... } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__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 e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } } static String md5(File file) { try { return md5(loadBinaryFile(file)); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static int asInt(Object o) { return toInt(o); } static A or(A a, A b) { return a != null ? a : b; } static String firstToUpper(String s) { if (s.length() == 0) return s; return Character.toUpperCase(s.charAt(0)) + s.substring(1); } 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 or2(String a, String b) { return nempty(a) ? a : b; } public static byte[] loadBinaryFile(String fileName) throws IOException { 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(); } public static byte[] loadBinaryFile(File file) throws IOException { return loadBinaryFile(file.getPath()); } }