import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import javax.swing.Timer;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import org.pushingpixels.substance.api.*;
import org.pushingpixels.substance.api.skin.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
public class main {
static int secondsToDisplay = 10;
public static void main(final String[] args) throws Exception { substance();
String lastText = null;
while (licensed()) { try { /* pcall 1*/
String s = getTextFromClipboard();
if (neq(s, lastText)) {
lastText = s;
final long id = parseSnippetURLOpt(s);
if (id != 0) {
final String _id = fsI(id);
//infoBox("Snippet: " + _id, 2);
swingLater(new Runnable() { public void run() { try {
final JLabel lbl = jlabel("Testing snippet");
final JFrame f = showPackedFrameInTopRightCorner("Run " + _id + "?",
withMargin(vstackWithSpacing(lbl, jbutton("Run", new Runnable() { public void run() { try {
nohupJavax(_id);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "nohupJavax(_id);"; }}))));
{ /*nt*/ Thread _t_0 = new Thread("Fetch Stuff") {
public void run() { /* in run */ try { /* pcall 1*/ /* in thread */
print("Testing snippet " + id);
if (getSnippetType(id) != 34)
disposeWindow(f);
else {
print("Runnable");
setText(lbl, "Fetching title...");
packFrameInTopRightCorner(f);
setText(lbl, or2(getSnippetTitle(id), "Unnamed snippet"));
makeLabelBold(lbl);
packFrameInTopRightCorner(f);
disposeWindowIfMouseNotInIt(iround(secondsToDisplay*1000), f);
}
/* in thread */ /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } /* in run */ }
};
_t_0.start(); }
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "final JLabel lbl = jlabel(\"Testing snippet\");\n final JFrame f = showPackedFrameInTopRightCorner(\"Run \" + _id + \"?\",\n withMargin(vstackWithSpacing(lbl, jbutton(\"Run\", r {\n nohupJavax(_id);\n }))));\n thread \"Fetch Stuff\" {\n print(\"Testing snippet \" + id);\n if (getSnippetType(id) != 34)\n disposeWindow(f);\n else {\n print(\"Runnable\");\n setText(lbl, \"Fetching title...\");\n packFrameInTopRightCorner(f);\n setText(lbl, or2(getSnippetTitle(id), \"Unnamed snippet\"));\n makeLabelBold(lbl);\n packFrameInTopRightCorner(f);\n disposeWindowIfMouseNotInIt(iround(secondsToDisplay*1000), f);\n }\n }"; }});
}
}
/* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } sleepSeconds(1); }
}
static String getSnippetTitle(String id) { try {
if (!isSnippetID(id)) return "?";
return trim(loadPageSilently(new URL("http://tinybrain.de:8080/tb-int/getfield.php?id=" + parseSnippetID(id) + "&field=title" + standardCredentials())));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String getSnippetTitle(long id) {
return getSnippetTitle(fsI(id));
}
static A disposeWindowIfMouseNotInIt(int delay, final A w) {
if (w != null)
swingLater(delay, new Runnable() { public void run() { try {
if (!mouseInWindow(w))
w.dispose();
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "if (!mouseInWindow(w))\r\n w.dispose();"; }});
return w;
}
static int withMargin_defaultWidth = 6;
static JPanel withMargin(Component c) {
JPanel p = new JPanel(new BorderLayout());
int w = withMargin_defaultWidth;
p.setBorder(BorderFactory.createEmptyBorder(w, w, w, w));
p.add(c);
return p;
}
static int iround(double d) {
return (int) Math.round(d);
}
static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
// button without action
static JButton jbutton(String text) {
return newButton(text, null);
}
static JLabel jlabel(String text) {
final JLabel l = new JLabel(text) {
@Override
public void setText(String text) {
super.setText(text);
setToolTipText(text);
}
};
componentPopupMenu(l, new Object() { void get(JPopupMenu menu) { try {
addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(l.getText());
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "copyTextToClipboard(l.getText());"; }});
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(l.getText());\r\n });"; }});
return l;
}
static JLabel jlabel() {
return jlabel(" ");
}
static long parseSnippetURLOpt(String s) {
if (empty(s)) return 0;
for (String pat : ll("tinybrain.de/(\\d+)", "show-snippet.php\\?id=(\\d+)",
"(\\d+)\\.tinybrain\\.de")) {
String id = regexpFirstGroupIC(pat, s);
if (id != null) return psI(id);
}
return 0;
}
// can probably be merged with next variant
static void disposeWindow(final Window window) {
if (window != null) swingNowOrLater(new Runnable() { public void run() { try {
window.dispose();
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "window.dispose();"; }});
}
static void disposeWindow(final Component c) {
disposeWindow(getWindow(c));
}
static JFrame showPackedFrameInTopRightCorner(Component c) {
return moveToTopRightCorner(showPackedFrame(c));
}
static JFrame showPackedFrameInTopRightCorner(String title, Component c) {
return setFrameTitle(title, showPackedFrameInTopRightCorner(c));
}
static String or2(String a, String b) {
return nempty(a) ? a : b;
}
static JLabel makeLabelBold(final JLabel l) {
if (l != null) { swingAndWait(new Runnable() { public void run() { try {
l.setFont(l.getFont().deriveFont(Font.BOLD));
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "l.setFont(l.getFont().deriveFont(Font.BOLD));"; }}); }
return l;
}
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 int print_maxLineLength = 0; // 0 = unset
static boolean print_silent; // total mute if set
static volatile ThreadLocal print_byThread; // special handling by thread
static void print() {
print("");
}
// slightly overblown signature to return original object...
static A print(A o) {
ping();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
if (print_byThread != null) {
Object f = print_byThread.get();
if (f != null)
if (isFalse(callF(f, s))) return;
}
print_raw(s);
}
static void print_raw(String s) {
s = fixNewLines(s);
// TODO if (print_maxLineLength != 0)
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);
}
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 int getSnippetType(String id) {
if (!isSnippetID(id)) return 0;
return getSnippetType(psI(id));
}
static int getSnippetType(long id) { try {
return parseInt(trim(loadPageSilently(new URL("http://tinybrain.de:8080/tb-int/getfield.php?id=" + id + "&field=type" + standardCredentials()))));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String getTextFromClipboard() { try {
Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor))
return (String) transferable.getTransferData(DataFlavor.stringFlavor);
return null;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static int vstackWithSpacing_default = 10;
static JPanel vstackWithSpacing(List parts, int spacing) {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(spacing/2, 0, spacing/2, 0); // well...
smartAddWithLayout(panel, gbc, toObjectArray(parts));
//gbc = (GridBagConstraints) gbc.clone();
//gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
gbc.insets = new Insets(0, 0, 0, 0);
panel.add(Box.createRigidArea(new Dimension(0, 0)), gbc);
return panel;
}
static JPanel vstackWithSpacing(Component... parts) {
return vstackWithSpacing(asList(parts), vstackWithSpacing_default);
}
static void nohupJavax(String javaxargs) {
nohupJavax(javaxargs, javaxDefaultVMArgs());
}
// not using pre-spun VM if vmArgs present
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();
vmArgs = trim(vmArgs);
if (empty(vmArgs) && usePreSpunVMs()) {
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.");
return;
}
if (answer != null)
print("> " + answer);
print("Using standard nohup.");
}
classicNohupJavax(javaxargs, vmArgs);
}
static JFrame packFrameInTopRightCorner(Component c) {
JFrame f = getFrame(c);
if (f != null) {
packFrame(f);
moveToTopRightCorner(f);
}
return f;
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static String fsI(String id) {
return formatSnippetID(id);
}
static String fsI(long id) {
return formatSnippetID(id);
}
static void setText(JTextComponent c, Object text) {
setText((Object) c, text);
}
static void setText(JLabel c, Object text) {
setText((Object) c, text);
}
static void setText(JButton c, Object text) {
setText((Object) c, text);
}
static void setText(final Object c, Object text) {
if (c == null) return;
final String s = str(text);
swingAndWait(new Runnable() { public void run() { try { call(c, "setText", s) ;
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "call(c, \"setText\", s)"; }});
}
static List ll(A... a) {
return litlist(a);
}
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));
}
// 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_cached(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 A setToolTipText(A c, Object toolTip) {
if (c == null) return null;
c.setToolTipText(str(toolTip));
return c;
}
static Object callF(Object f, Object... args) {
return callFunction(f, args);
}
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(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
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 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 empty(float[] a) { return a == null || a.length == 0; }
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 swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(r));
timer.setRepeats(false);
timer.start();
}
static void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
static String javaxDefaultVMArgs() {
return trim(loadProgramTextFile("#1005850", "default-vm-args", ""));
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + 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); } } public String toString() { return "result.set(callF(f));"; }});
return result.get();
}
}
static String regexpFirstGroupIC(String pat, String s) {
Matcher m = regexpIC(pat, s);
if (m.find()) return m.group(1); else return null;
}
static int packFrame_minw = 150, packFrame_minh = 50;
static JFrame packFrame(final Component c) {
return (JFrame) swing(new Object() { Object get() { try {
JFrame frame = getFrame(c);
if (frame == null) return null;
frame.pack();
int maxW = getScreenWidth()-50, maxH = getScreenHeight()-50;
frame.setSize(
min(maxW, max(frame.getWidth(), packFrame_minw)),
min(maxH, max(frame.getHeight(), packFrame_minh)));
return frame;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "JFrame frame = getFrame(c);\r\n if (frame == null) null;\r\n frame.pack();\r\n int maxW = getScreenWidth()-50, maxH = getScreenHeight()-50;\r\n frame.setSize(\r\n min(maxW, max(frame.getWidth(), packFrame_minw)),\r\n min(maxH, max(frame.getHeight(), packFrame_minh)));\r\n ret frame;"; }});
}
static JFrame packFrame(ButtonGroup g) {
return packFrame(getFrame(g));
}
static long psI(String snippetID) {
return parseSnippetID(snippetID);
}
static boolean isFalse(Object o) {
return eq(false, o);
}
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 String str(Object o) {
return String.valueOf(o);
}
static String str(char[] c) {
return new String(c);
}
static String standardCredentials() {
String user = standardCredentialsUser();
String pass = standardCredentialsPass();
if (nempty(user) && nempty(pass))
return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
return "";
}
static void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
static Window getWindow(Object o) {
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof Window) return (Window) c;
c = c.getParent();
}
return null;
}
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = synchroMap(new WeakHashMap());
// returns true if it did anything
static boolean ping() { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
Object action;
synchronized(mc()) {
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 (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static JFrame getFrame(Object 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;
}
static A setFrameTitle(A c, String title) {
JFrame f = getFrame(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;
}
// 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;
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 && 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);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else 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 && 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
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
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;
static int loadPage_retries = 60; // seconds
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 < loadPage_retries; tries++)
try {
URLConnection con = openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPageThroughProxy_enabled) {
print("Trying proxy because of: " + e);
try {
return loadPageThroughProxy(str(url));
} catch (Throwable e2) {
print(" " + exceptionToStringShort(e2));
}
}
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 {
url = loadPage_preprocess(url);
print("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPage(URL url) {
print("Loading: " + hideCredentials(url.toExternalForm()));
return loadPageSilently(url);
}
public static String loadPage(URLConnection con, URL url) throws IOException {
try {
if (!loadPage_anonymous)
setHeaders(con);
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);
String match = m.matches() ? m.group(1) : null;
if (loadPage_debug)
print("loadPage: contentType=" + contentType + ", match: " + match);
/* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
return or(match, "ISO-8859-1");
}
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 class componentPopupMenu_Maker {
List menuMakers = new ArrayList();
}
static Map componentPopupMenu_map = new WeakHashMap();
static ThreadLocal componentPopupMenu_mouseEvent = new ThreadLocal();
// menuMaker = voidfunc(JPopupMenu)
static void componentPopupMenu(final JComponent component, final Object menuMaker) {
swingNowOrLater(new Runnable() { public void run() { try {
componentPopupMenu_Maker maker = componentPopupMenu_map.get(component);
if (maker == null) {
componentPopupMenu_map.put(component, maker = new componentPopupMenu_Maker());
final componentPopupMenu_Maker _maker = maker;
component.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 emptyCount = menu.getComponentCount();
componentPopupMenu_mouseEvent.set(e);
for (Object menuMaker : _maker.menuMakers)
pcallF(menuMaker, menu);
// show menu if any items in it
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
maker.menuMakers.add(menuMaker);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "componentPopupMenu_Maker maker = componentPopupMenu_map.get(component);\n if (maker == null) {\n componentPopupMenu_map.put(component, maker = new componentPopupMenu_Maker);\n final componentPopupMenu_Maker _maker = maker;\n component.addMouseListener(new MouseAdapter {\n public void mousePressed(MouseEvent e) { displayMenu(e); }\n public void mouseReleased(MouseEvent e) { displayMenu(e); }\n \n void displayMenu(MouseEvent e) {\n if (e.isPopupTrigger()) {\n new JPopupMenu menu;\n int emptyCount = menu.getComponentCount();\n \n componentPopupMenu_mouseEvent.set(e);\n for (Object menuMaker : _maker.menuMakers)\n pcallF(menuMaker, menu);\n \n // show menu if any items in it\n if (menu.getComponentCount() != emptyCount)\n menu.show(e.getComponent(), e.getX(), e.getY());\n }\n }\n });\n }\n maker.menuMakers.add(menuMaker);"; }});
}
static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static boolean mouseInWindow(Component c) {
Window w = getWindow(c);
return w != null && w.isShowing() && boundsOnScreen(w).contains(mousePosition());
}
static JFrame showPackedFrame(String title, Component contents) {
return packFrame(showFrame(title, contents));
}
static JFrame showPackedFrame(Component contents) {
return packFrame(showFrame(contents));
}
static JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
for (Object o : parts) {
Component c;
if (o == null)
c = new JPanel();
else if (o instanceof String)
c = jlabel((String) o);
else
c = wrap(o);
panel.add(c, layout);
}
return panel;
}
static JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
return smartAddWithLayout(panel, layout, asList(parts));
}
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 int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
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 String sendToLocalBotOpt(String bot, String text, Object... args) {
if (bot == null) return null;
text = format(text, args);
DialogIO channel = findBot(bot);
if (channel == null) {
print(quote(bot) + " not found, skipping send: " + quote(text));
return null;
}
try {
channel.readLine();
print(shorten(bot + "> " + text, 200));
channel.sendLine(text);
String s = channel.readLine();
print(shorten(bot + "< " + s, 200));
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
channel.close();
}
}
static String copyTextToClipboard(String text) {
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
return text;
}
// action can be Runnable or a function name
static JButton newButton(String text, final Object action) {
JButton btn = new JButton(text);
if (action != null)
btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) {
callFunction(action);
}});
return btn;
}
static int moveToTopRightCorner_inset = 20;
static A moveToTopRightCorner(A a) {
Window w = getWindow(a);
if (w != null)
w.setLocation(getScreenSize().width-w.getWidth()-moveToTopRightCorner_inset, moveToTopRightCorner_inset);
return a;
}
static boolean usePreSpunVMs() {
return eq("1", trim(loadProgramTextFile("#1005457", "enable-prespun-vms")));
}
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
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 String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder();
quote_impl(s, out);
return out.toString();
}
static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else
out.append(c);
}
out.append('"');
}
static String shorten(String s, int max) {
if (s == null) return "";
if (max < 0) return s;
return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}
public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}
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 boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isTrue(callOpt(getClass("javax.swing.SwingUtilities"), "isEventDispatchThread"));
}
/** 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 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 Thread currentThread() {
return Thread.currentThread();
}
static JMenuItem jmenuItem(String text, final Object r) {
JMenuItem mi = new JMenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
static String standardCredentialsUser() {
return trim(loadTextFile(new File(userHome(), ".tinybrain/username")));
}
static Point mousePosition() {
return MouseInfo.getPointerInfo().getLocation();
}
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));
}
static RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
// disabled for now to shorten some programs
/*static RuntimeException fail(S msg, O... args) {
throw new RuntimeException(format(msg, args));
}*/
static String getType(Object o) {
return getClassName(o);
}
static String quickSubstring(String s, int i, int j) {
if (i == j) return "";
return s.substring(i, j);
}
static Matcher regexpIC(String pat, String s) {
return Pattern.compile(pat, Pattern.CASE_INSENSITIVE).matcher(s);
}
static List parse3(String s) {
return dropPunctuation(javaTokPlusPeriod(s));
}
static int getScreenWidth() {
return getScreenSize().width;
}
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 List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
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 ActionListener actionListener(final Object runnable) {
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { pcallF(runnable); }};
}
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 ArrayList litlist(A... a) {
return new ArrayList(Arrays.asList(a));
}
static String hideCredentials(String url) {
return url.replaceAll("&_pass=[^&]*", "&_pass=");
}
static String parse3_cached_s;
static List parse3_cached_l;
static synchronized List parse3_cached(String s) {
if (neq(s, parse3_cached_s))
parse3_cached_l = parse3(parse3_cached_s = s);
return parse3_cached_l;
}
static JFrame showFrame() {
return makeFrame();
}
static JFrame showFrame(Object content) {
return makeFrame(content);
}
static JFrame showFrame(String title) {
return makeFrame(title);
}
static JFrame showFrame(String title, Object content) {
return makeFrame(title, content);
}
static JFrame showFrame(final JFrame frame) {
if (frame != null) { swingAndWait(new Runnable() { public void run() { try {
if (frameTooSmall(frame)) frameStandardSize(frame);
frame.setVisible(true);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "if (frameTooSmall(frame)) frameStandardSize(frame);\r\n frame.setVisible(true);"; }}); }
return frame;
}
// make or update frame
static JFrame showFrame(String title, Object content, JFrame frame) {
if (frame == null)
return showFrame(title, content);
else {
frame.setTitle(title);
setFrameContents(frame, content);
return frame;
}
}
static void setHeaders(URLConnection con) throws IOException {
String computerID = getComputerID();
if (computerID != null) try {
con.setRequestProperty("X-ComputerID", computerID);
con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
} catch (Throwable e) {
//printShortException(e);
}
}
static 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 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 Map findBot_cache = synchroHashMap();
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(sendToLocalBotQuietly(p.port, "list bots"));
for (Number vport : subBots.keySet()) {
String name = subBots.get(vport);
if (startsWithIgnoreCase(name, searchPattern))
return talkToSubBot(vport.longValue(), talkTo("localhost", p.port));
}
} catch (Exception e) { e.printStackTrace(); }
}
return null;
}
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 int getScreenHeight() {
return getScreenSize().height;
}
static Object swing(Object f) {
return swingAndWait(f);
}
/** possibly improvable */
public static String winQuote(String text) {
if (text == null) return null;
return "\"" + text
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r") + "\"";
}
static final boolean loadPageThroughProxy_enabled = false;
static String loadPageThroughProxy(String url) {
return null;
}
// c = JComponent or something implementing swing()
static JComponent wrap(Object swingable) {
JComponent c = (JComponent) ( swingable instanceof JComponent ? swingable : callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList
|| c instanceof JTextArea || c instanceof JEditorPane
|| c instanceof JTextPane)
return new JScrollPane(c);
return c;
}
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 boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
// 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 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 __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "callF(o)"; }};
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static Object mc() {
return getMainClass();
}
// 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 boolean isNonNegativeInteger(String s) {
return s != null && Pattern.matches("\\d+", s);
}
static URLConnection openConnection(URL url) { try {
ping();
return url.openConnection();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String format(String pat, Object... args) {
return format3(pat, args);
}
// 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;
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static void sleepSeconds(double s) {
if (s > 0) sleep(round(s*1000));
}
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;
}
/** 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 = newFileOutputStream(tempFileName);
fileOutputStream.write(contents);
fileOutputStream.close();
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
}
static void saveBinaryFile(File fileName, byte[] contents) {
try {
saveBinaryFile(fileName.getPath(), contents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static String loadProgramTextFile(String name) {
return loadTextFile(getProgramFile(name));
}
static String loadProgramTextFile(String progID, String name) {
return loadTextFile(getProgramFile(progID, name));
}
static String loadProgramTextFile(String progID, String name, String defaultText) {
return loadTextFile(getProgramFile(progID, name), defaultText);
}
static Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
public static File nohup(String cmd) { try {
File outFile = File.createTempFile("nohup_" + nohup_sanitize(cmd), ".out");
nohup(cmd, outFile, false);
return outFile;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
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) { try {
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();
}
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
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 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 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 byte[] loadBinaryPage(String url) { try {
print("Loading " + url);
return loadBinaryPage(new URL(url).openConnection());
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static byte[] loadBinaryPage(URLConnection con) { try {
setHeaders(con);
return loadBinaryPage_noHeaders(con);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static byte[] loadBinaryPage_noHeaders(URLConnection con) { try {
setHeaders(con);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
InputStream inputStream = con.getInputStream();
long len = 0;
try { len = con.getContentLengthLong(); } catch (Throwable e) { printStackTrace(e); }
int n = 0;
while (true) {
int ch = inputStream.read();
if (ch < 0)
break;
buf.write(ch);
if (++n % 100000 == 0)
println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
}
inputStream.close();
return buf.toByteArray();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
structure_Data d = new structure_Data();
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack))
popLast(d.stack).run();
}
static void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static int structure_shareStringsLongerThan = 20;
static class structure_Data {
PrintWriter out;
int stringSizeLimit;
IdentityHashMap