> rows, List cols, String title) {
JTable tbl = sexyTable();
fillTableWithStrings(tbl, rows, cols);
showFrame(title, tbl);
return tbl;
}
static TableWithTooltips tableWithToolTips() {
return tableWithTooltips();
}
static JPanel scrollable_trackWidth(final Component component) {
class P extends SingleComponentPanel implements Scrollable {
P() { super(component); }
public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); }
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 20; }
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return (direction == SwingConstants.HORIZONTAL ? visibleRect.width : visibleRect.height)*5/6;
}
public boolean getScrollableTracksViewportWidth() { return true; }
public boolean getScrollableTracksViewportHeight() { return false; }
}
return swing(new F0() { P get() { try { return new P() ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "new P"; }});
}
static TimerTask timerTask(final Object r, final java.util.Timer timer) {
return new TimerTask() {
public void run() {
if (!licensed())
timer.cancel();
else
pcallF(r);
}
};
}
static TimerTask timerTask(final Object r) {
return new TimerTask() {
public void run() {
ping();
pcallF(r);
}
};
}
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = newWeakHashMap();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions ) ping_impl();
return true;
}
// returns true when it slept
static boolean ping_impl() { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
Object action;
synchronized(ping_actions) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static A setFrameTitle(A c, String title) {
Frame f = getAWTFrame(c);
if (f == null)
showFrame(title, c);
else
f.setTitle(title);
return c;
}
static A setFrameTitle(String title, A c) {
return setFrameTitle(c, title);
}
// magically find a field called "frame" in main class :-)
static JFrame setFrameTitle(String title) {
Object f = getOpt(mc(), "frame");
if (f instanceof JFrame)
return setFrameTitle((JFrame) f, title);
return null;
}
static 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 {
rows.add(dataToTable_makeRow(x, cols));
} catch (Throwable __e) { printStackTrace2(__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)
setTableModel(table, fillTableWithData_makeModel(rows, toStringArray(cols)));
else
fillTableWithData(table, rows, cols);
return table;
}
static JComponent showTitledForm(String title, Object... _parts) {
return showFormTitled(title, _parts);
}
// RSyntaxTextArea
// AutoComplete
// RSTAUI
static RSyntaxTextArea javaxSyntaxTextArea() {
return swing(new F0() { RSyntaxTextArea get() { try {
RSyntaxTextArea textArea = new RSyntaxTextArea(1, 10);
new NumPadFixingInputMap().replaceOn(textArea);
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
textArea.setTabSize(2);
textArea.setTabsEmulated(true);
textArea.setCodeFoldingEnabled(true);
textArea.setMarkOccurrences(true);
return textArea;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "RSyntaxTextArea textArea = new RSyntaxTextArea(1, 10);\r\n new NumPadFixingI..."; }});
}
static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static float max(float[] c) {
if (c.length == 0) return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x) x = d;
return x;
}
static List tlft(String s) { return toLinesFullTrim(s); }
static List tlft(File f) { return toLinesFullTrim(f); }
static volatile boolean disableCertificateValidation_attempted;
static void disableCertificateValidation() { try {
if (disableCertificateValidation_attempted) return;
disableCertificateValidation_attempted = true;
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}};
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) { return true; }
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Throwable __e) { printStackTrace2(__e); }
} catch (Exception __e) { throw rethrow(__e); } }
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;
}
// action can be Runnable or a function name
static JButton newButton(final String text, final Object action) {
return swing(new F0() { JButton get() { try {
JButton btn = new JButton(text);
// submitButtonOnEnter(btn); // test this first
if (action != null)
btn.addActionListener(actionListener(action, btn));
return btn;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JButton btn = new JButton(text);\r\n // submitButtonOnEnter(btn); // test th..."; }});
}
// Try to get the quoting right...
static String smartJoin(String[] args) {
if (args.length == 1) return args[0];
String[] a = new String[args.length];
for (int i = 0; i < a.length; i++)
a[i] = !isJavaIdentifier(args[i]) && !isQuoted(args[i]) ? quote(args[i]) : args[i];
return join(" ", a);
}
static String smartJoin(List args) {
return smartJoin(toStringArray(args));
}
static final boolean loadPageThroughProxy_enabled = false;
static String loadPageThroughProxy(String url) {
return null;
}
static TreeSet treeSet() {
return new TreeSet();
}
static void messageBox(final String msg) {
if (headless()) print(msg);
else { swing(new Runnable() { public void run() { try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES..."; }}); }
}
static void messageBox(Throwable e) {
showConsole();
printStackTrace(e);
messageBox(hideCredentials(innerException(e)));
}
static Object first(Object list) {
return empty((List) list) ? null : ((List) list).get(0);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static A pcallF(F0 f) { try {
return f == null ? null : f.get();
} catch (Throwable __e) { return null; } }
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static List mechList_opt(String name) {
return mechList_opt_tlft(name);
}
static Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null) return e;
while (e.getClass() == RuntimeException.class
&& e.getCause() != null && eq(e.getMessage(), str(e.getCause())))
e = e.getCause();
return e;
}
static JPanel jFullCenter(final Component c) {
return swing(new F0() { JPanel get() { try {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(c);
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new GridBagLayout);\r\n panel.add(c);\r\n ret panel;"; }});
}
static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static JLabel jcenteredlabel(String text) {
return jcenteredLabel(text);
}
static JLabel jcenteredlabel() {
return jcenteredLabel();
}
static Map parseDoubleArrowMap(Map map, List l) {
for (String s : l) {
List x = splitAtDoubleArrow_bothDirections(s);
if (l(x) == 2) map.put(first(x), second(x));
}
return map;
}
static void multiMapPut(Map> map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
// 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 JButton setButtonImage(BufferedImage img, JButton btn) {
btn.setIcon(imageIcon(img));
return btn;
}
static JButton setButtonImage(JButton btn, BufferedImage img) {
return setButtonImage(img, btn);
}
static class tablePopupMenu_Maker {
List menuMakers = new ArrayList();
}
static Map tablePopupMenu_map = new WeakHashMap();
static ThreadLocal tablePopupMenu_mouseEvent = new ThreadLocal();
static ThreadLocal tablePopupMenu_first = new ThreadLocal();
// menuMaker = voidfunc(JPopupMenu, int row)
static void tablePopupMenu(final JTable table, final Object menuMaker) {
final boolean first = isTrue(getAndClearThreadLocal(tablePopupMenu_first));
swingNowOrLater(new Runnable() { public void run() { try {
tablePopupMenu_Maker maker = tablePopupMenu_map.get(table);
if (maker == null) {
tablePopupMenu_map.put(table, maker = new tablePopupMenu_Maker());
final tablePopupMenu_Maker _maker = maker;
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) { displayMenu(e); }
public void mouseReleased(MouseEvent e) { displayMenu(e); }
void displayMenu(MouseEvent e) {
if (e.isPopupTrigger()) {
JPopupMenu menu = new JPopupMenu();
int row = table.rowAtPoint(e.getPoint());
if (table.getSelectedRowCount() < 2)
table.setRowSelectionInterval(row, row);
int emptyCount = menu.getComponentCount();
tablePopupMenu_mouseEvent.set(e);
for (Object menuMaker : _maker.menuMakers)
pcallF(menuMaker, menu, row);
// show menu if any items in it
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
if (first)
maker.menuMakers.add(0, menuMaker);
else
maker.menuMakers.add(menuMaker);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tablePopupMenu_Maker maker = tablePopupMenu_map.get(table);\r\n if (maker ==..."; }});
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static Object rawTableCell(JTable tbl, int row, int col) {
return getTableCell(tbl, row, col);
}
static boolean isMainProgram() {
return creator() == null;
}
static void sleepSeconds(double s) {
if (s > 0) sleep(round(s*1000));
}
static int withTopMargin_defaultWidth = 6;
static JPanel withTopMargin(Component c) {
return withTopMargin(withTopMargin_defaultWidth, c);
}
static JPanel withTopMargin(final int w, final Component c) {
return swing(new F0() { JPanel get() { try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0));
p.add(c);
return p;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat..."; }});
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static Set keys(MultiMap mm) {
return mm.keySet();
}
static JFrame getFrame(final Object _o) {
return swing(new F0() { JFrame get() { try {
Object o = _o;
if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JFrame) return (JFrame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; }});
}
static JPanel centerAndSouth(final Component c, final Component s) {
return swing(new F0() { JPanel get() { try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
if (s != null) panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT..."; }});
}
static boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static void copyImageToClipboard(Image img) {
TransferableImage trans = new TransferableImage(img);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents( trans, null);
print("Copied image to clipboard (" + img.getWidth(null) + "*" + img.getHeight(null) + " px)");
}
// returns l(s) if not found
static int smartIndexOf(String s, String sub, int i) {
if (s == null) return 0;
i = s.indexOf(sub, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static int smartIndexOf(String s, int i, char c) {
return smartIndexOf(s, c, i);
}
static int smartIndexOf(String s, char c, int i) {
if (s == null) return 0;
i = s.indexOf(c, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static int smartIndexOf(String s, String sub) {
return smartIndexOf(s, sub, 0);
}
static int smartIndexOf(String s, char c) {
return smartIndexOf(s, c, 0);
}
static int smartIndexOf(List l, A sub) {
return smartIndexOf(l, sub, 0);
}
static int smartIndexOf(List l, int start, A sub) {
return smartIndexOf(l, sub, start);
}
static int smartIndexOf(List l, A sub, int start) {
int i = indexOf(l, sub, start);
return i < 0 ? l(l) : i;
}
static String uploadMechMap(String listName, Map map) {
// TODO: honor list format
return botEditMechList(listName, formatDoubleArrowMap(map));
}
static long sysNow() {
return System.nanoTime()/1000000;
}
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 Object sleepQuietly_monitor = new Object();
static void sleepQuietly() { try {
assertFalse(isAWTThread());
synchronized(sleepQuietly_monitor) { sleepQuietly_monitor.wait(); }
} catch (Exception __e) { throw rethrow(__e); } }
static boolean preferCached = false;
static boolean loadSnippet_debug = false;
static ThreadLocal loadSnippet_silent = new ThreadLocal();
static int loadSnippet_timeout = 30000;
static String loadSnippet(String snippetID) { try {
if (snippetID == null) return null;
return loadSnippet(parseSnippetID(snippetID), preferCached);
} catch (Exception __e) { throw rethrow(__e); } }
static String loadSnippet(String snippetID, boolean preferCached) throws IOException {
return loadSnippet(parseSnippetID(snippetID), preferCached);
}
public static String loadSnippet(long snippetID) { try {
return loadSnippet(snippetID, preferCached);
} catch (Exception __e) { throw rethrow(__e); } }
public static String loadSnippet(long snippetID, boolean preferCached) throws IOException {
String text;
// boss bot disabled for now for shorter transpilations
/*text = getSnippetFromBossBot(snippetID);
if (text != null) return text;*/
initSnippetCache();
text = DiskSnippetCache_get(snippetID);
if (preferCached && text != null)
return text;
try {
if (loadSnippet_debug && text != null) System.err.println("md5: " + md5(text));
String url = tb_mainServer() + "/getraw.php?id=" + snippetID + "&utf8=1";
if (nempty(text)) url += "&md5=" + md5(text);
url += standardCredentials();
String text2 = loadSnippet_loadFromServer(url);
boolean same = eq(text2, "==*#*==");
if (loadSnippet_debug) print("loadSnippet: same=" + same);
if (!same) text = text2;
} catch (RuntimeException e) {
e.printStackTrace();
throw new IOException("Snippet #" + snippetID + " not found or not public");
}
try {
initSnippetCache();
DiskSnippetCache_put(snippetID, text);
} catch (IOException e) {
System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")");
}
return text;
}
static File DiskSnippetCache_dir;
public static void initDiskSnippetCache(File dir) {
DiskSnippetCache_dir = dir;
dir.mkdirs();
}
public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
}
private static File DiskSnippetCache_getFile(long snippetID) {
return new File(DiskSnippetCache_dir, "" + snippetID);
}
public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
}
public static File DiskSnippetCache_getDir() {
return DiskSnippetCache_dir;
}
public static void initSnippetCache() {
if (DiskSnippetCache_dir == null)
initDiskSnippetCache(getGlobalCache());
}
static String loadSnippet_loadFromServer(String url) {
Integer oldTimeout = setThreadLocal(loadPage_forcedTimeout_byThread, loadSnippet_timeout);
try {
return isTrue(loadSnippet_silent.get()) ? loadPageSilently(url) : loadPage(url);
} finally {
loadPage_forcedTimeout_byThread.set(oldTimeout);
}
}
static int 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 int toInt(long l) {
if (l != (int) l) throw fail("Too large for int: " + l);
return (int) l;
}
static A or(A a, A b) {
return a != null ? a : b;
}
static String tb_mainServer_default = "http://tinybrain.de:8080";
static Object tb_mainServer_override; // func -> S
static String tb_mainServer() {
if (tb_mainServer_override != null) return (String) callF(tb_mainServer_override);
return trim(loadTextFile(tb_mainServer_file(),
tb_mainServer_default));
}
static File tb_mainServer_file() {
return getProgramFile("#1001638", "mainserver.txt");
}
static boolean tb_mainServer_isDefault() {
return eq(tb_mainServer(), tb_mainServer_default);
}
static Map weakHashMap() {
return newWeakHashMap();
}
static String getProgramName_cache;
static String getProgramName() {
Lock __364 = downloadLock(); lock(__364); try {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitleOpt(programID());
return getProgramName_cache;
} finally { unlock(__364); } }
static void _onLoad_getProgramName() {
{ Thread _t_0 = new Thread() {
public void run() { try { getProgramName(); } catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
}
static A swingConstruct(final Class c, final Object... args) {
return swing(new F0() { A get() { try { return nuObject(c, args) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "nuObject(c, args)"; }});
}
static A disposeWindowAfter(int delay, final A w) {
if (w != null)
swingLater(delay, new Runnable() { public void run() { try {
w.dispose();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "w.dispose();"; }});
return w;
}
static A disposeWindowAfter(A w, double seconds) {
return disposeWindowAfter(toMS_int(seconds), w);
}
static class wrapAsActivity_R implements Runnable {
Object r;
wrapAsActivity_R() {}
wrapAsActivity_R(Object r) {
this.r = r;}
public void run() {
AutoCloseable __388 = tempActivity(r); try {
callF(r);
} finally { _close(__388); }}
}
static wrapAsActivity_R wrapAsActivity(final Object r) {
return r instanceof wrapAsActivity_R ? ((wrapAsActivity_R) r) : new wrapAsActivity_R(r);
}
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 Throwable printStackTrace(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
return e;
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
/*static void printStackTrace(S indent, Throwable e) {
if (endsWithLetter(indent)) indent += " ";
printIndent(indent, getStackTrace(e));
}*/
static List splitAtDoubleArrow_bothDirections(String s) {
return splitAtDoubleArrow_bothDirections(javaTok(s));
}
static List splitAtDoubleArrow_bothDirections(List tok) {
List l = splitAtDoubleArrow(tok);
if (l(l) != 2) l = reversedList(splitAtDoubleLeftArrow(tok));
return l;
}
static void showConsole() {
showFrame(consoleFrame());
}
static void setTableModel(JTable table, TableModel model) {
Map widths = tableColumnWidthsByName(table);
int[] i = table.getSelectedRows();
table.setModel(model);
int n = model.getRowCount();
ListSelectionModel sel = table.getSelectionModel();
for (int j = 0; j < i.length; j++)
if (i[j] < n)
sel.addSelectionInterval(i[j], i[j]);
tableSetColumnPreferredWidths(table, widths);
}
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
static volatile boolean licensed_yes = true;
static boolean licensed() {
ping();
return licensed_yes;
}
static void licensed_off() {
licensed_yes = false;
}
static List listMinus(Collection l, Object... stuff) {
List l2 = cloneList(l);
for (Object o : stuff)
l2.remove(o);
return l2;
}
static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() { public void close() {
tl.set(prev);
}};
}
static boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static Boolean isHeadless_cache;
static boolean isHeadless() {
if (isHeadless_cache != null) return isHeadless_cache;
if (isAndroid()) return isHeadless_cache = true;
if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true;
// Also check if AWT actually works.
// If DISPLAY variable is set but no X server up, this will notice.
try {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) { return isHeadless_cache = true; }
}
static Class javax() {
return getJavaX();
}
// supports the usual quotings (", variable length double brackets) except ' quoting
static boolean isQuoted(String s) {
if (isNormalQuoted(s)) return true; // use the exact version
return isMultilineQuoted(s);
}
// f: func(key, value) -> entry
static List mapMapToList(Map map, Object f) {
return map(map, f);
}
static List mapMapToList(Object f, Map map) {
return map(f, map);
}
static boolean hasMethod(Object o, String method, Object... args) {
return findMethod(o, method, args) != null;
}
static String prependIfNempty(String prefix, String s) {
return empty(s) ? s : prefix + s;
}
/** writes safely (to temp file, then rename) */
static File saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists()) try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) { printStackTrace(e); }
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
return file;
} finally {
action.done();
}
}
static File saveTextFile(File fileName, String contents) { try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) { throw rethrow(__e); } }
static List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j-i
&& s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static File infoBoxesLogFile() {
return new File(javaxDataDir(), "Logs/infoBoxes.txt");
}
static Random random_random = new Random();
static int random(int n) {
return n <= 0 ? 0 : random_random.nextInt(n);
}
static double random(double max) {
return random()*max;
}
static double random() {
return random_random.nextInt(100001)/100000.0;
}
static double random(double min, double max) {
return min+random()*(max-min);
}
// min <= value < max
static int random(int min, int max) {
return min+random(max-min);
}
static A random(List l) {
return oneOf(l);
}
static A random(Collection c) {
if (c instanceof List) return random((List) c);
int i = random(l(c));
return collectionGet(c, i);
}
static String lines(Collection lines) { return fromLines(lines); }
static List lines(String s) { return toLines(s); }
static void logQuotedWithDate(String s) {
logQuotedWithTime(s);
}
static void logQuotedWithDate(String logFile, String s) {
logQuotedWithTime(logFile, s);
}
static void logQuotedWithDate(File logFile, String s) {
logQuotedWithTime(logFile, s);
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static File javaxCodeDir_dir; // can be set to work on different base dir
static File javaxCodeDir() {
return javaxCodeDir_dir != null ? javaxCodeDir_dir : new File(userHome(), "JavaX-Code");
}
static void swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
timer.setRepeats(false);
timer.start();
}
static void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
static void lock(Lock lock) { try {
ping();
lock.lockInterruptibly();
ping();
} catch (Exception __e) { throw rethrow(__e); } }
static void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static ReentrantLock lock() {
return fairLock();
}
// TODO: does not detect set type (hash/tree) when it's synchronized
static Set cloneSet(Set set) {
// assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does.
synchronized(set) {
return set instanceof TreeSet ? new TreeSet(set) : new HashSet(set);
}
}
// contains voidfunc(childClass)
static ThreadLocal makeAndCall_initChild = new ThreadLocal();
static Object makeAndCall_cached(String functionName, Object... args) {
Class c = loadFunctions_cached(functionName);
callF(makeAndCall_initChild.get(), c);
return preciseCall(c, functionName, args);
}
static JTextArea jtextarea() {
return jTextArea();
}
static JTextArea jtextarea(String text) {
return jTextArea(text);
}
static void setEnabled(final JComponent c, final boolean enable) {
if (c != null) { swing(new Runnable() { public void run() { try { c.setEnabled(enable);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.setEnabled(enable);"; }}); }
}
static void swingNowOrLater(Runnable r) {
if (isAWTThread())
r.run();
else
swingLater(r);
}
static boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++)
if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static JLabel jcenteredLabel(String text) {
JLabel l = jLabel(text);
l.setHorizontalAlignment(JLabel.CENTER);
return l;
}
static JLabel jcenteredLabel() {
return jcenteredLabel(" ");
}
static ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
static WeakReference creator_class;
static Class creator() {
return creator_class == null ? null : creator_class.get();
}
static A second(List l) {
return get(l, 1);
}
static A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static B second(Pair p) {
return p == null ? null : p.b;
}
static A jenableUndoRedo(A textcomp) {
final UndoManager undo = new UndoManager();
textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() { public void run() { try {
if (undo.canUndo()) undo.undo()
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canUndo()) undo.undo()"; }}));
textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() { public void run() { try {
if (undo.canRedo()) undo.redo()
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canRedo()) undo.redo()"; }}));
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
return textcomp;
}
static int indexOf(List l, A a, int startIndex) {
if (l == null) return -1;
for (int i = startIndex; i < l(l); i++)
if (eq(l.get(i), a))
return i;
return -1;
}
static int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
static int indexOf(List l, A a) {
if (l == null) return -1;
return l.indexOf(a);
}
static int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(A[] x, A a) {
if (x == null) return -1;
for (int i = 0; i < l(x); i++)
if (eq(x[i], a))
return i;
return -1;
}
static JWindow showWindow(Component c) {
JWindow w = new JWindow();
w.add(wrap(c));
return w;
}
static List sortedDesc(Collection c, final Object comparator) {
List l = cloneList(c);
sort(l, makeReversedComparator(comparator));
return l;
}
static List sortedDesc(Collection c) {
List l = cloneList(c);
sort(l);
Collections.reverse(l);
return l;
}
static String mechList_raw_fresh(String name) {
return (String) ((Map) jsonDecode(postPageSilently("http://butter.botcompany.de:8080/mech/raw/list-text/" + urlencode(name), muricaCredentials()))).get("Text");
}
static String jlabel_textAsHTML_center_ifNeeded(String text) {
if (swic(text, "") && ewic(text, "")) return text;
if (!containsNewLines(text)) return text;
return jlabel_textAsHTML_center(text);
}
static int scoredSearch_score_single(String s, String query) {
int i = indexOfIC_underscore(s, query);
if (i < 0) return 0;
if (i > 0) return 1;
return l(s) == l(query) ? 3 : 2;
}
static String hhtml(Object contents) {
return containerTag("html", contents);
}
static int moveToTopRightCorner_inset = 20;
static A moveToTopRightCorner(A a) {
return moveToTopRightCorner(moveToTopRightCorner_inset, moveToTopRightCorner_inset, a);
}
static A moveToTopRightCorner(int insetX, int insetY, A a) {
Window w = getWindow(a);
if (w != null)
w.setLocation(getScreenSize().width-w.getWidth()-insetX, insetY);
return a;
}
static A jPreferWidth(int w, A c) {
Dimension size = c.getPreferredSize();
c.setPreferredSize(new Dimension(/*max(w, size.width) ??? */w, size.height));
return c;
}
static JPanel infoMessage_makePanel(String text) {
final JTextArea ta = wrappedTextArea(text);
onClick(ta, new Runnable() { public void run() { try { disposeWindow(ta) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disposeWindow(ta)"; }});
int size = 14;
if (l(text) <= 50) size *= 2;
else if (l(text) < 100) size = iround(size*1.5);
ta.setFont(typeWriterFont(size));
JScrollPane sp = jscroll(ta);
return withMargin(sp);
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static Thread currentThread() {
return Thread.currentThread();
}
static String standardCredentials() {
String user = standardCredentialsUser();
String pass = standardCredentialsPass();
if (nempty(user) && nempty(pass))
return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
return "";
}
static void fillTableWithData(final JTable table, List rows, List colNames) {
fillTableWithData(table, rows, toStringArray(colNames));
}
// thread-safe
static void fillTableWithData(final JTable table, List rows, String... colNames) {
final DefaultTableModel model = fillTableWithData_makeModel(rows, colNames);
swingNowOrLater(new Runnable() { public void run() { try {
setTableModel(table, model);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setTableModel(table, model);"; }});
}
static DefaultTableModel fillTableWithData_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++) {
Object o = l.get(j);
if (o instanceof BufferedImage) o = imageIcon((BufferedImage) o);
r[j] = o;
}
data[i] = r;
w = Math.max(w, l.size());
}
Object[] columnNames = new Object[w];
for (int i = 0; i < w; i++)
columnNames[i] = i < l(colNames) ? colNames[i] : "?";
return new DefaultTableModel(data, columnNames) {
public Class getColumnClass(int column) {
return or(_getClass(getValueAt(0, column)), String.class);
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
};
}
static List toLinesFullTrim(String s) {
List l = new ArrayList();
for (String line : toLines(s)) if (nempty(line = trim(line))) l.add(line);
return l;
}
static List toLinesFullTrim(File f) {
List l = new ArrayList();
for (String line : linesFromFile(f)) if (nempty(line = trim(line))) l.add(line);
return l;
}
// runnable = Runnable or String (method name)
static Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
static Thread newThread(Object runnable, String name) {
if (name == null) name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x) x = d;
return x;
}
static int showForm_defaultGap = 4;
static int showForm_gapBetweenColumns = 10;
static JPanel showFormTitled(final String title, final Object... _parts) {
return swing(new F0() { JPanel get() { try {
final Var frame = new Var();
JPanel panel = showForm_makePanel(frame, _parts);
frame.set(showForm_makeFrame(title, panel));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final new Var frame;\r\n JPanel panel = showForm_makePanel(frame, _p..."; }});
}
static JPanel showForm_makePanel(final Var frame, Object... _parts) {
List out = showForm_arrange1(showForm_makeComponents(frame, _parts));
return vstackWithSpacing(out, showForm_defaultGap);
}
static Object[] flattenArray2(Object... a) {
List l = new ArrayList();
for (Object x : a)
if (x instanceof Object[])
l.addAll(asList((Object[]) x));
else if (x instanceof Collection)
l.addAll((Collection) x);
else
l.add(x);
return asObjectArray(l);
}
static Class getMainClass() {
return main.class;
}
static Class getMainClass(Object o) { try {
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) { throw rethrow(__e); } }
static String getSnippetTitleOpt(String s) {
return isSnippetID(s) ? getSnippetTitle(s) : s;
}
static String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++)
a[i] = it.next();
return a;
}
static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
static File getGlobalCache() {
File file = new File(javaxCachesDir(), "Binary Snippets");
file.mkdirs();
return file;
}
static int gzInputStream_defaultBufferSize = 65536;
static GZIPInputStream gzInputStream(File f) { try {
return gzInputStream(new FileInputStream(f));
} catch (Exception __e) { throw rethrow(__e); } }
static GZIPInputStream gzInputStream(File f, int bufferSize) { try {
return new GZIPInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) { throw rethrow(__e); } }
static GZIPInputStream gzInputStream(InputStream in) { try {
return new GZIPInputStream(in, gzInputStream_defaultBufferSize);
} catch (Exception __e) { throw rethrow(__e); } }
static void renewConsoleFrame() {
setConsoleFrame(renewFrame(consoleFrame()));
}
static Runnable toRunnable(final Object o) {
if (o instanceof Runnable) return (Runnable) o;
return new Runnable() { public void run() { try { callF(o) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; }};
}
static JScrollPane jscroll(final Component c) {
return swing(new F0() { JScrollPane get() { try { return new JScrollPane(c) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "new JScrollPane(c)"; }});
}
static void dataToTable_dynSet(List l, int i, Object 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 : keysWithoutHidden(m)) {
String field = (String) ( _field);
Object value = m.get(field);
int col = cols.indexOf(field);
if (col < 0) {
cols.add(field);
col = cols.size()-1;
}
dataToTable_dynSet(row, col, dataToTable_wrapValue(value));
}
return row;
}
return litlist(structureOrText(x));
}
static Object dataToTable_wrapValue(Object o) {
if (o instanceof BufferedImage) return o;
if (o instanceof Boolean) return o;
return structureOrText(o);
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static void unlock(Lock lock, String msg) {
print("Unlocking: " + msg);
lock.unlock();
}
static void unlock(Lock lock) {
lock.unlock();
}
static void printException(Throwable e) {
printStackTrace(e);
}
static TableWithTooltips tableWithTooltips() {
return (TableWithTooltips) swing(new F0