Warning : session_start(): open(/var/lib/php/sessions/sess_usuo3j7iisrts7tr1r1ebdnn8q, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import org.pushingpixels.substance.api.skin.*;
import java.awt.datatransfer.StringSelection;
import org.pushingpixels.substance.api.*;
class main {
static Map aiPrograms = litorderedmap(
"Circle Editor", "#1009961",
"Encyclopedia", "#1010561",
"AI Concepts", "#1006463",
"Truth Table", "#1007236",
"English To Concepts Translator", "#1007419",
"Concepts To English Translator", "#1007163",
"AI Clipboard", "#1007441",
"AI Suite", "#1007449");
public static void main(final String[] args) throws Exception { { swing(new Runnable() { public void run() { try {
framesBot();
magellan();
Map progs = mapWithoutKey(aiPrograms, "AI Suite");
showPackedCenterFrame(withMargin(vgrid(map("btn", progs))));
hideConsole();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "framesBot();\n magellan();\n Map progs = mapWithoutKey(aiProgram..."; }}); }}
static JComponent btn(String text, final String programID) {
return withTopAndBottomMargin(
setBoldFontSize(15,
jbutton(text, new Runnable() { public void run() { try { startOrActivate(programID) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "startOrActivate(programID)"; }})));
}
static RuntimeException rethrow(Throwable e) {
throw asRuntimeException(e);
}
static LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static int withMargin_defaultWidth = 6;
static JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
static JPanel withMargin(final int w, final Component c) {
return swing(new F0() { JPanel get() { try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(w, w, w, w));
p.add(c);
return p;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.createEm..."; }});
}
// returns informative message
static String startOrActivate(String progID) {
String msg = activateFramesOf(progID);
if (nempty(msg)) return msg;
nohupJavax(progID);
return fsI(progID) + " nohup-started.";
}
static Map _registerThread_threads = Collections.synchronizedMap(new WeakHashMap());
static Thread _registerThread(Thread t) {
_registerThread_threads.put(t, true);
return t;
}
static void _registerThread() { _registerThread(Thread.currentThread()); }
static volatile boolean framesBot_has;
static Android3 framesBot() {
if (framesBot_has) return null;
framesBot_has = true;
Android3 android = new Android3();
android.greeting = programID() + " Frames.";
android.console = false;
android.responder = new Responder() {
String answer(String s, List history) {
if (match("activate frames", s)) {
swingLater(new Runnable() { public void run() { try { // prevent blocking when called from same program's AWT thread
activateMyFrames();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// prevent blocking when called from same program's AWT thread\r\n activa..."; }});
return "OK, activating frames.";
}
return null;
}
};
return makeBot(android);
}
static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
// button without action
static JButton jbutton(String text) {
return newButton(text, null);
}
static JButton jbutton(BufferedImage img, Object action) {
return setButtonImage(img, jbutton("", action));
}
static JButton jbutton(Action action) {
return new JButton(action);
}
static Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static JPanel vgrid(List parts) {
return vgrid(asArray(parts));
}
static JPanel vgrid(Object... parts) {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(parts.length, 1));
smartAdd(panel, parts);
return panel;
}
static RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static int withTopAndBottomMargin_defaultWidth = 6;
static JPanel withTopAndBottomMargin(Component c) {
JPanel p = new JPanel(new BorderLayout());
int w = withTopAndBottomMargin_defaultWidth;
p.setBorder(BorderFactory.createEmptyBorder(w, 0, w, 0));
p.add(c);
return p;
}
static A setBoldFontSize(int size, A a) {
return makeBold(setFontSize(size, a));
}
static JFrame showPackedCenterFrame(Component c) {
return centerFrame(showPackedFrame(c));
}
static Map mapWithoutKey(Map map, A key) {
Map m = cloneMap(map);
m.remove(key);
return m;
}
static void hideConsole() {
final JFrame frame = consoleFrame();
if (frame != null) {
autoVMExit();
swingLater(new Runnable() { public void run() { try {
frame.setVisible(false);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setVisible(false);"; }});
}
}
static List map(Iterable l, Object f) {
return map(f, l);
}
static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null) for (Object o : l)
x.add(callF(f, o));
return x;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }
static List map(Object f, Map map) {
return map(map, f);
}
static List map(Map map, Object f) {
List x = new ArrayList();
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static void magellan() {
substanceLAF("Magellan");
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static Object[] asArray(List l) {
return toObjectArray(l);
}
static A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static WeakHashMap> callF_cache = new WeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static Object callF(Object f, Object... args) { try {
if (f instanceof String)
return callMC((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) throw fail("No get method in " + getClassName(c));
if (n == 1) return methods.get(0).invoke(f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return m.invoke(f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
m.setAccessible(true);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
// returns null if program not running, answer otherwise
static String activateFramesOf(String progID) {
return sendToLocalBotOpt(fsI(progID) + " Frames.", "activate frames");
}
static String substanceLAF_defaultSkin = "Creme";
static void substanceLAF() {
substanceLAF(null);
}
static void substanceLAF(String skinName) {
try {
enableSubstance_impl(or2(skinName, substanceLAF_defaultSkin));
} catch (Throwable __e) { printStackTrace2(__e); }
}
static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : 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 A centerFrame(A c) {
Window w = getWindow(c);
if (w != null)
w.setLocationRelativeTo(null); // magic trick
return c;
}
static A centerFrame(int w, int h, A c) {
return centerFrame(setFrameSize(w, h, c));
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static List emptyList(int capacity) {
return new ArrayList(capacity);
}
// Try to match capacity
static List emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
f.setAccessible(true);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(Object o, String field) {
try {
Field f = get_findField(o.getClass(), field);
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static 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 void nohupJavax(final String javaxargs) {
{ Thread _t_0 = new Thread() {
public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs); } catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
}
static void nohupJavax(final String javaxargs, final String vmArgs) {
{ Thread _t_1 = new Thread() {
public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs); } catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_1); }
}
static int makeBot(String greeting) {
return makeAndroid3(greeting).port;
}
static Android3 makeBot(Android3 a) {
makeAndroid3(a);
return a;
}
static Android3 makeBot(String greeting, Object responder) {
Android3 a = new Android3(greeting);
a.responder = makeResponder(responder);
makeBot(a);
return a;
}
static Android3 makeBot() {
return makeAndroid3(getProgramTitle() + ".");
}
static String fsI(String id) {
return formatSnippetID(id);
}
static String fsI(long id) {
return formatSnippetID(id);
}
static String programID() {
return getProgramID();
}
static void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(r);
} catch (Exception __e) { throw rethrow(__e); } }
static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() { public void run() { try {
result.set(callF(f));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; }});
return result.get();
}
}
static JFrame showPackedFrame(String title, Component contents) {
return packFrame(showFrame(title, contents));
}
static JFrame showPackedFrame(Component contents) {
return packFrame(showFrame(contents));
}
static Map cloneMap(Map map) {
if (map == null) return litmap();
// assume mutex is equal to collection
synchronized(map) {
return map instanceof TreeMap ? new TreeMap(map)
: map instanceof LinkedHashMap ? new LinkedHashMap(map)
: new HashMap(map);
}
}
static List activateMyFrames() {
final List l = myFrames();
{ swing(new Runnable() { public void run() { try {
for (JFrame f : l)
activateFrame(f);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "for (JFrame f : l)\r\n activateFrame(f);"; }}); }
return l;
}
static JButton setButtonImage(BufferedImage img, JButton btn) {
btn.setIcon(imageIcon(img));
return btn;
}
static boolean nempty(Collection c) {
return !isEmpty(c);
}
static boolean nempty(CharSequence s) {
return !isEmpty(s);
}
static boolean nempty(Object[] o) {
return !isEmpty(o);
}
static boolean nempty(Map m) {
return !isEmpty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean match(String pat, String s) {
return match3(pat, s);
}
static boolean match(String pat, String s, Matches matches) {
return match3(pat, s, matches);
}
static JPanel smartAdd(JPanel panel, List parts) {
for (Object o : parts)
addToContainer(panel, wrapForSmartAdd(o));
return panel;
}
static JPanel smartAdd(JPanel panel, Object... parts) {
return smartAdd(panel, asList(parts));
}
static A setFontSize(int size, A a) {
if (a != null) a.setFont(a.getFont().deriveFont((float) size));
return a;
}
static A setFontSize(A a, int size) {
return setFontSize(size, a);
}
static A makeBold(final A c) {
if (c != null) { swing(new Runnable() { public void run() { try { c.setFont(c.getFont().deriveFont(Font.BOLD));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.setFont(c.getFont().deriveFont(Font.BOLD));"; }}); }
return c;
}
static void autoVMExit() {
call(getJavaX(), "autoVMExit");
}
// 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);
if (action != null)
btn.addActionListener(actionListener(action));
return btn;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JButton btn = new JButton(text);\r\n if (action != null)\r\n btn.addActionLi..."; }});
}
static Map litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length-1; i += 2)
if (x[i+1] != null)
map.put(x[i], x[i+1]);
}
static boolean match3(String pat, String s) {
return match3(pat, s, null);
}
static boolean match3(String pat, String s, Matches matches) {
if (pat == null || s == null) return false;
return match3(pat, parse3_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;
if (matches != null) matches.m = m; return true;
}
// An "Android" is a program that accepts text questions (on console or TCP) and outputs one response text per question
static boolean makeAndroid3_disable; // disable all android making
static class Android3 {
String greeting;
boolean publicOverride; // optionally set this in client
int startPort = 5000; // optionally set this in client
Responder responder;
boolean console = true;
boolean quiet; // no messages on console
boolean daemon = false;
boolean incomingSilent = false;
int incomingPrintLimit = 200;
boolean useMultiPort = true;
boolean recordHistory;
boolean verbose;
int answerPrintLimit = 500;
boolean newLineAboveAnswer, newLineBelowAnswer;
// set by system
int port;
long vport;
DialogHandler handler;
ServerSocket server;
Android3(String greeting) {
this.greeting = greeting;}
Android3() {}
synchronized void dispose() {
if (server != null) {
try {
server.close();
} catch (IOException e) {
print("[internal] " + e);
}
server = null;
}
if (vport != 0) try {
print("Disposing " + this);
removeFromMultiPort(vport);
vport = 0;
} catch (Throwable __e) { printStackTrace2(__e); }
}
public String toString() { return "Bot: " + greeting + " [vport " + vport + "]"; }
}
static abstract class Responder {
abstract String answer(String s, List history);
}
static Android3 makeAndroid3(final String greeting) {
return makeAndroid3(new Android3(greeting));
}
static Android3 makeAndroid3(final String greeting, Responder responder) {
Android3 android = new Android3(greeting);
android.responder = responder;
return makeAndroid3(android);
}
static Android3 makeAndroid3(final Android3 a) {
if (makeAndroid3_disable) return a;
if (a.responder == null)
a.responder = new Responder() {
String answer(String s, List history) {
return callStaticAnswerMethod(s, history);
}
};
if (!a.quiet)
print("[bot] " + a.greeting);
if (a.console && makeAndroid3_consoleInUse() && !readLine_noReadLine) a.console = false;
record(a);
if (a.useMultiPort)
a.vport = addToMultiPort(a.greeting,
makeAndroid3_verboseResponder(a));
if (a.console)
makeAndroid3_handleConsole(a);
if (a.useMultiPort) return a;
a.handler = makeAndroid3_makeDialogHandler(a);
if (a.quiet) startDialogServer_quiet.set(true);
try {
a.port = a.daemon
? startDialogServerOnPortAboveDaemon(a.startPort, a.handler)
: startDialogServerOnPortAbove(a.startPort, a.handler);
} finally {
startDialogServer_quiet.set(null);
}
a.server = startDialogServer_serverSocket;
return a;
}
static void makeAndroid3_handleConsole(final Android3 a) {
// Console handling stuff
if (!a.quiet)
print("You may also type on this console.");
{ Thread _t_0 = new Thread() {
public void run() { try {
List history = new ArrayList();
while (licensed()) {
String line;
try {
line = readLine();
} catch (Throwable e) {
print(getInnerMessage(e));
break;
}
if (line == null) break;
/*if (eq(line, "bye")) {
print("> bye stranger");
history = new ArrayList();
} else*/ {
history.add(line);
history.add(makeAndroid3_getAnswer(line, history, a)); // prints answer on console too
}
}
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
}
static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
return new DialogHandler() {
public void run(final DialogIO io) {
if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
io.sendLine("Sorry, not allowed");
return;
}
String dialogID = randomID(8);
io.sendLine(a.greeting + " / Your ID: " + dialogID);
List history = new ArrayList();
while (io.isStillConnected()) {
if (io.waitForLine()) {
final String line = io.readLineNoBlock();
String s = dialogID + " at " + now() + ": " + quote(line);
if (!a.incomingSilent)
print(shorten(s, a.incomingPrintLimit));
if (eq(line, "bye")) {
io.sendLine("bye stranger");
return;
}
Matches m = new Matches();
if (a.recordHistory)
history.add(line);
String answer;
if (match3("this is a continuation of talk *", s, m)
|| match3("hello bot! this is a continuation of talk *", s, m)) {
dialogID = unquote(m.m[0]);
answer = "ok";
} else try {
makeAndroid3_io.set(io);
answer = makeAndroid3_getAnswer(line, history, a);
} finally {
makeAndroid3_io.set(null);
}
if (a.recordHistory)
history.add(answer);
io.sendLine(answer);
//appendToLog(logFile, s);
}
}
}};
}
static String makeAndroid3_getAnswer(String line, List history, Android3 a) {
String answer, originalAnswer;
try {
originalAnswer = a.responder.answer(line, history);
answer = makeAndroid3_fallback(line, history, originalAnswer);
} catch (Throwable e) {
e = getInnerException(e);
printStackTrace(e);
originalAnswer = answer = e.toString();
}
if (!a.incomingSilent) {
if (originalAnswer == null) originalAnswer = "?";
if (a.newLineAboveAnswer) print();
print(">" + dropFirst(indentx(2, shorten(rtrim(originalAnswer), a.answerPrintLimit))));
if (a.newLineBelowAnswer) print();
}
return answer;
}
static String makeAndroid3_fallback(String s, List history, String answer) {
// Now we only do the safe thing instead of VM inspection - give out our process ID
if (answer == null && match3("what is your pid", s))
return getPID();
if (answer == null && match3("what is your program id", s)) // should be fairly safe, right?
return getProgramID();
if (match3("get injection id", s))
return getInjectionID();
if (answer == null) answer = "?";
if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
answer = quote(answer);
return answer;
}
static boolean makeAndroid3_consoleInUse() {
for (Object o : record_list)
if (o instanceof Android3 && ((Android3) o).console)
return true;
return false;
}
static Responder makeAndroid3_verboseResponder(final Android3 a) {
return new Responder() {
String answer(String s, List history) {
if (a.verbose)
print("> " + shorten(s, a.incomingPrintLimit));
String answer = a.responder.answer(s, history);
if (a.verbose)
print("< " + shorten(answer, a.incomingPrintLimit));
return answer;
}
};
}
static ThreadLocal makeAndroid3_io = new ThreadLocal();
static Android3 makeAndroid3() {
return makeAndroid3(getProgramTitle() + ".");
}
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 void activateFrame(final Component c) {
{ swing(new Runnable() { public void run() { try {
JFrame f = getFrame(c);
if (f == null) return;
if (!f.isVisible()) f.setVisible(true);
if (f.getState() == Frame.ICONIFIED)
f.setState(Frame.NORMAL);
// My glorious Windows hack
// See: https://stackoverflow.com/questions/309023/how-to-bring-a-window-to-the-front
if (isWindows()) {
boolean fullscreen = f.getExtendedState() == Frame.MAXIMIZED_BOTH;
f.setExtendedState(JFrame.ICONIFIED);
f.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL);
}
f.toFront();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFrame f = getFrame(c);\r\n if (f == null) return;\r\n if (!f.isVisible()) f.s..."; }}); }
}
static final HashMap> callMC_cache = new HashMap();
static String callMC_key;
static Method callMC_value;
// varargs assignment fixer for a single string array argument
static Object callMC(String method, String[] arg) {
return callMC(method, new Object[] {arg});
}
static Object callMC(String method, Object... args) { try {
Method me;
synchronized(callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null) return callMC_value.invoke(null, args);
List m;
synchronized(callMC_cache) {
m = callMC_cache.get(method);
}
if (m == null) {
if (callMC_cache.isEmpty()) {
callMC_makeCache();
m = callMC_cache.get(method);
}
if (m == null) throw fail("Method named " + method + " not found in main");
}
int n = m.size();
if (n == 1) {
me = m.get(0);
synchronized(callMC_cache) {
callMC_key = method;
callMC_value = me;
}
return me.invoke(null, args);
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return me.invoke(null, args);
}
throw fail("No method called " + method + " with matching arguments found in main");
} catch (Exception __e) { throw rethrow(__e); } }
static void callMC_makeCache() {
synchronized(callMC_cache) {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods())
if ((m.getModifiers() & Modifier.STATIC) != 0) {
m.setAccessible(true);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
static void addToContainer(Container a, Component b) {
if (a != null && b != null) a.add(b);
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
// TODO: test if android complains about this
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isAWTThread_awt();
}
static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static String getProgramTitle() {
return getProgramName();
}
static int packFrame_minw = 150, packFrame_minh = 50;
static A packFrame(final A c) {
{ swing(new Runnable() { public void run() { try {
JFrame frame = getFrame(c);
if (frame != 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)));
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFrame frame = getFrame(c);\r\n if (frame != null) {\r\n frame.pack();\r\n ..."; }}); }
return c;
}
static JFrame packFrame(ButtonGroup g) {
return packFrame(getFrame(g));
}
static String or2(String a, String b) {
return nempty(a) ? a : b;
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static 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;
}
// Substance
// Trident (required by Substance)
static void enableSubstance_impl(final String skinName) { swing(new Runnable() { public void run() { try {
if (!substanceLookAndFeelEnabled())
enableSubstance_impl_2(skinName);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!substanceLookAndFeelEnabled())\r\n enableSubstance_impl_2(skinName);"; }}); }
static void enableSubstance_impl_2(String skinName) { try {
boolean wasEnabled = substanceLookAndFeelEnabled();
ClassLoader cl = main.class.getClassLoader();
UIManager.getDefaults().put("ClassLoader", cl);
Thread.currentThread().setContextClassLoader(cl);
String skinClassName = "org.pushingpixels.substance.api.skin." + addSuffix(skinName, "Skin");
SubstanceSkin skin = (SubstanceSkin) nuObject(cl.loadClass(skinClassName));
SubstanceLookAndFeel.setSkin(skin);
JFrame.setDefaultLookAndFeelDecorated(true);
updateLookAndFeelOnAllWindows_noRenew();
if (!wasEnabled) renewConsoleFrame();
if (substanceLookAndFeelEnabled())
print("Substance L&F enabled.");
else
print("Could not enable Substance L&F?");
} catch (Exception __e) { throw rethrow(__e); } }
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
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 String programID;
static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
// TODO: ask JavaX instead
static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static ActionListener actionListener(final Object runnable) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { callF(runnable); } catch (Throwable __e) { messageBox(__e); }}};
}
static Component wrapForSmartAdd(Object o) {
if (o == null) return new JPanel();
if (o instanceof String) return jlabel((String) o);
return wrap(o);
}
static ImageIcon imageIcon(String imageID) { try {
return new ImageIcon(loadBinarySnippet(imageID).toURI().toURL());
} catch (Exception __e) { throw rethrow(__e); } }
static ImageIcon imageIcon(BufferedImage img) {
return new ImageIcon(img);
}
static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static Thread startThread(String name, Object runnable) {
return startThread(newThread(toRunnable(runnable), name));
}
static Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
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) { swing(new Runnable() { public void run() { try {
if (frameTooSmall(frame)) frameStandardSize(frame);
frame.setVisible(true);
} catch (Exception __e) { throw rethrow(__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 Class __javax;
static Class getJavaX() {
return __javax;
}
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 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 Class hotwireOnce(String programID) {
return hotwireCached(programID, false);
}
static List myFrames() {
return (List) swing(new Object() { Object get() { try {
Map map = (Map) getOpt(mc(), "makeFrame_myFrames");
return map == null ? new ArrayList() : asList(keys(map));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Map map = (Map) getOpt(mc(), \"makeFrame_myFrames\");\r\n ret ma..."; }});
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); } static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: l((Collection) o); // incomplete
}
static A setFrameSize(A c, int w, int h) {
JFrame f = getFrame(c);
if (f != null)
f.setSize(w, h);
return c;
}
static A setFrameSize(int w, int h, A c) {
return setFrameSize(c, w, h);
}
static String makeResponder_callAnswerMethod(Object bot, String s, List history) {
String answer = (String) callOpt(bot, "answer", s, history);
if (answer == null)
answer = (String) callOpt(bot, "answer", s);
return answer;
}
static Responder makeResponder(final Object bot) {
if (bot instanceof Responder) return (Responder) bot;
if (bot instanceof String) {
String f = (String) ( bot);
return new Responder() {
String answer(String s, List history) {
String answer = (String) callOptMC((String) bot, s, history);
if (answer == null)
answer = (String) callOptMC((String) bot, s);
return answer;
}
};
}
return new Responder() {
String answer(String s, List history) {
return makeResponder_callAnswerMethod(bot, s, history);
}
};
}
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// access of static fields is not yet optimized
static Object getOpt(Class c, String field) {
try {
if (c == null) return null;
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static 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 Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
/*static void printStackTrace2(S indent, Throwable e) {
if (endsWithLetter(indent)) indent += " ";
printIndent(indent, getStackTrace2(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;
}
static WeakHashMap makeFrame_myFrames = new WeakHashMap();
static JFrame makeFrame() {
return makeFrame((Component) null);
}
static JFrame makeFrame(Object content) {
return makeFrame(programTitle(), content);
}
static JFrame makeFrame(String title) {
return makeFrame(title, null);
}
static JFrame makeFrame(String title, Object content) {
return makeFrame(title, content, true);
}
static JFrame makeFrame(final String title, final Object content, final boolean showIt) {
return swing(new F0() { JFrame get() { try {
if (getFrame(content) != null)
return getFrame(setFrameTitle((Component) content, title));
final JFrame frame = new JFrame(title);
makeFrame_myFrames.put(frame, Boolean.TRUE);
JComponent wrapped = wrap(content);
if (wrapped != null)
frame.getContentPane().add(wrapped);
frame.setBounds(defaultNewFrameBounds());
if (showIt)
frame.setVisible(true);
//callOpt(content, "requestFocus");
//exitOnFrameClose(frame);
standardTitlePopupMenu(frame);
return frame;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (getFrame(content) != null)\r\n ret getFrame(setFrameTitle((Component) con..."; }});
}
static Object callOptMC(String method, Object... args) {
return callOpt(mc(), method, args);
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder((int) (l(s)*1.5+2));
quote_impl(s, out);
return out.toString();
}
static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else
out.append(c);
}
out.append('"');
}
static int shorten_default = 100;
static String shorten(String s) { return shorten(s, shorten_default); }
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)) + "...";
}
static String shorten(int max, String s) { return shorten(s, max); }
static List record_list = synchroList();
static void record(Object o) {
record_list.add(o);
}
static TreeMap hotwireCached_cache = new TreeMap();
static Lock hotwireCached_lock = lock();
static Class hotwireCached(String programID) {
return hotwireCached(programID, true);
}
static Class hotwireCached(String programID, boolean runMain) {
Lock _lock_949 = hotwireCached_lock; lock(_lock_949); try {
programID = formatSnippetID(programID);
Class c = hotwireCached_cache.get(programID);
if (c == null) {
c = hotwire(programID);
if (runMain)
callMain(c);
hotwireCached_cache.put(programID, c);
}
return c;
} finally { _lock_949.unlock(); } }
public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}
static void setFrameContents(final Component c, final Object contents) {
{ swing(new Runnable() { public void run() { try {
JFrame frame = getFrame(c);
frame.getContentPane().removeAll();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrap(contents));
revalidate(frame);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFrame frame = getFrame(c);\r\n frame.getContentPane().removeAll();\r\n frame...."; }}); }
}
static String getStackTrace2(Throwable throwable) {
return hideCredentials(getStackTrace(throwable) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
hideCredentials(str(getInnerException(throwable)))) + "\n");
}
static boolean substanceLookAndFeelEnabled() {
return startsWith(getLookAndFeel(), "org.pushingpixels.");
}
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 String defaultThreadName_name;
static String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static void removeFromMultiPort(long vport) {
if (vport == 0) return;
for (Object port : getMultiPorts())
call(port, "removePort", vport);
}
static File loadBinarySnippet(String snippetID) { try {
long id = parseSnippetID(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile(snippetID);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static Object addToMultiPort_responder;
static long addToMultiPort(final String botName) {
return addToMultiPort(botName, new Object() {
public String answer(String s, List history) {
String answer = (String) ( callOpt(getMainClass(), "answer", s, history));
if (answer != null) return answer;
answer = (String) callOpt(getMainClass(), "answer", s);
if (answer != null) return answer;
if (match3("get injection id", s))
return getInjectionID();
return null;
}
});
}
static long addToMultiPort(final String botName, final Object responder) {
//print(botName);
addToMultiPort_responder = responder;
startMultiPort();
List ports = getMultiPorts();
if (ports == null) return 0;
if (ports.isEmpty())
throw fail("No multiports!");
if (ports.size() > 1)
print("Multiple multi-ports. Using last one.");
Object port = last(ports);
Object responder2 = new Object() {
public String answer(String s, List history) {
if (match3("get injection id", s))
return getInjectionID();
if (match3("your name", s))
return botName;
return (String) call(responder, "answer", s, history);
}
};
record(responder2);
return (Long) call(port, "addResponder", botName, responder2);
}
// runnable = Runnable or String (method name)
static Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
static Thread newThread(Object runnable, String name) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static String addSuffix(String s, String suffix) {
return s.endsWith(suffix) ? s : s + suffix;
}
static String myJavaSource_code;
static String myJavaSource() {
return myJavaSource_code;
}
static List parse3(String s) {
return dropPunctuation(javaTokPlusPeriod(s));
}
static String getInnerMessage(Throwable e) {
if (e == null) return null;
return getInnerException(e).getMessage();
}
static int getScreenWidth() {
return getScreenSize().width;
}
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 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 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 volatile boolean licensed_yes = true;
static boolean licensed() {
ping();
return licensed_yes;
}
static void licensed_off() {
licensed_yes = false;
}
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 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 (Throwable __e) { print(exceptionToStringShort(__e)); }
}
return null;
}
static Throwable getInnerException(Throwable e) {
while (e.getCause() != null)
e = e.getCause();
return e;
}
static int getScreenHeight() {
return getScreenSize().height;
}
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_MESSAG..."; }}); }
}
static void messageBox(Throwable e) {
showConsole();
printStackTrace(e);
messageBox(str(innerException(e)));
}
// c = JComponent or something implementing swing()
static JComponent wrap(Object swingable) {
if (swingable == null) return null;
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 || c instanceof JTree)
return jscroll(c);
return c;
}
// match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens)
static String[] match2(List pat, List tok) {
// standard case (no ...)
int i = pat.indexOf("...");
if (i < 0) return match2_match(pat, tok);
pat = new ArrayList(pat); // We're modifying it, so copy first
pat.set(i, "*");
while (pat.size() < tok.size()) {
pat.add(i, "*");
pat.add(i+1, ""); // doesn't matter
}
return match2_match(pat, tok);
}
static String[] match2_match(List pat, List tok) {
List result = new ArrayList();
if (pat.size() != tok.size()) {
return null;
}
for (int i = 1; i < pat.size(); i += 2) {
String p = pat.get(i), t = tok.get(i);
if (eq(p, "*"))
result.add(t);
else if (!equalsIgnoreCase(unquote(p), unquote(t))) // bold change - match quoted and unquoted now
return null;
}
return result.toArray(new String[result.size()]);
}
static void renewConsoleFrame() {
setConsoleFrame(renewFrame(consoleFrame()));
}
static boolean frameTooSmall(JFrame frame) {
return frame.getWidth() < 100 || frame.getHeight() < 50;
}
static Boolean isHeadless_cache;
static boolean isHeadless() {
if (isHeadless_cache != null) return isHeadless_cache;
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 boolean publicCommOn() {
return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
}
static Class mc() {
return main.class;
}
static String indentx(String s) {
return indentx(indent_default, s);
}
static String indentx(int n, String s) {
return dropSuffix(repeat(' ', n), indent(n, s));
}
static String indentx(String indent, String s) {
return dropSuffix(indent, indent(indent, s));
}
static 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 String format(String pat, Object... args) {
return format3(pat, args);
}
static String getInjectionID() {
return (String) call(getJavaX(), "getInjectionID", getMainClass());
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || a.equals(b);
}
static Object nuObject(String className, Object... args) { try {
return nuObject(Class.forName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }
// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
ret nuObject(_getClass(realm, className), args);
}*/
static A nuObject(Class c, Object... args) { try {
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return (A) m.newInstance(args);
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found"
+ (args.length == 0 && (c.getModifiers() & Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static void updateLookAndFeelOnAllWindows_noRenew() {
for (Window window : Window.getWindows())
SwingUtilities.updateComponentTreeUI(window);
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static Object callOpt(Object o) {
if (o == null) return null;
return callF(o);
}
static Object callOpt(Object o, String method, Object... args) {
try {
if (o == null) return null;
if (o instanceof Class) {
Method m = callOpt_findStaticMethod((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = callOpt_findMethod(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
//fail(e.getMessage() + " | Method: " + method + ", receiver: " + className(o) + ", args: (" + join(", ", map(f className, args) + ")");
throw new RuntimeException(e);
}
}
static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (!m.getName().equals(method)) {
if (debug) System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static 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((ButtonGro..."; }});
}
static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
static JLabel jlabel() {
return jlabel(" ");
}
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 final WeakHashMap> getOpt_cache = new WeakHashMap();
static final HashMap getOpt_special = new HashMap(); // just a marker
static {
getOpt_cache.put(Class.class, getOpt_special);
getOpt_cache.put(String.class, getOpt_special);
}
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
/*if (o instanceof S)
ret getOpt(getBot((S) o), field);*/
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
f.setAccessible(true);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
getOpt_cache.put(c, map);
return map;
}
static AtomicInteger dialogServer_clients = new AtomicInteger();
static boolean dialogServer_printConnects;
static ThreadLocal startDialogServer_quiet = new ThreadLocal();
static Set dialogServer_knownClients = synchroTreeSet();
static int startDialogServerOnPortAbove(int port, DialogHandler handler) {
while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler))
++port;
return port;
}
static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) {
while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler, true))
++port;
return port;
}
static void startDialogServer(int port, DialogHandler handler) {
if (!startDialogServerIfPortAvailable(port, handler))
throw fail("Can't start dialog server on port " + port);
}
static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) {
return startDialogServerIfPortAvailable(port, handler, false);
}
static ServerSocket startDialogServer_serverSocket;
static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
// probably the port number is used - let's assume there already is a chat server.
return false;
}
final ServerSocket _serverSocket = serverSocket;
startDialogServer_serverSocket = serverSocket;
Thread thread = new Thread("Socket accept port " + port) { public void run() {
try {
while (true) {
try {
final Socket s = _serverSocket.accept();
String client = s.getInetAddress().toString();
if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) {
print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet());
dialogServer_knownClients.add(client);
}
String threadName = "Handling client " + s.getInetAddress();
Thread t2 = new Thread(threadName) {
public void run() {
try {
final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
final BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream(), "UTF-8"));
DialogIO io = new DialogIO() {
// This should be the same as #1001076 (talkTo)
boolean isLocalConnection() {
return s.getInetAddress().isLoopbackAddress();
}
boolean isStillConnected() {
return !(eos || s.isClosed());
}
void sendLine(String line) { try {
w.write(line + "\n");
w.flush();
} catch (Exception __e) { throw rethrow(__e); } }
String readLineImpl() { try {
return in.readLine();
} catch (Exception __e) { throw rethrow(__e); } }
void close() {
try {
s.close();
} catch (IOException e) {
// whatever
}
}
Socket getSocket() {
return s;
}
};
try {
handler.run(io);
} finally {
s.close();
}
} catch (IOException e) {
print("[internal] " + e);
} finally {
//print("client disconnect - " + dialogServer_clients.decrementAndGet() + " remaining");
}
}
}; // Thread t2
t2.setDaemon(true); // ?
t2.start();
} catch (SocketTimeoutException e) {
}
}
} catch (IOException e) {
print("[internal] " + e);
}
}};
if (daemon) thread.setDaemon(true);
thread.start();
if (!isTrue(getAndClearThreadLocal(startDialogServer_quiet)))
print("Dialog server on port " + port + " started.");
return true;
}
static void frameStandardSize(JFrame frame) {
frame.setBounds(300, 100, 500, 400);
}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static String processID_cached;
// try to get our current process ID
static String getPID() {
if (processID_cached == null) {
String name = ManagementFactory.getRuntimeMXBean().getName();
processID_cached = name.replaceAll("@.*", "");
}
return processID_cached;
}
static String unquote(String s) {
if (s == null) return null;
if (s.startsWith("[")) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i+1, s.length()-i-1);
}
}
if ((s.startsWith("\"") || s.startsWith("\'")) && s.length() > 1) {
int l = s.endsWith(substring(s, 0, 1)) ? s.length()-1 : s.length();
StringBuilder sb = new StringBuilder(l-1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
// Hex Unicode: u????
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + s.charAt(i + 2) + s.charAt(i + 3)
+ s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar; // added by Stefan
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
return s; // not quoted - return original
}
public static String rtrim(String s) {
int i = s.length();
while (i > 0 && " \t\r\n".indexOf(s.charAt(i-1)) >= 0)
--i;
return i < s.length() ? s.substring(0, i) : s;
}
static String callStaticAnswerMethod(List bots, String s) {
for (Object c : bots) try {
String answer = callStaticAnswerMethod(c, s);
if (!empty(answer)) return answer;
} catch (Throwable e) {
print("Error calling " + getProgramID(c));
e.printStackTrace();
}
return null;
}
static String callStaticAnswerMethod(Object c, String s) {
String answer = (String) callOpt(c, "answer", s, litlist(s));
if (answer == null)
answer = (String) callOpt(c, "answer", s);
return emptyToNull(answer);
}
static String callStaticAnswerMethod(String s) {
return callStaticAnswerMethod(mc(), s);
}
static String callStaticAnswerMethod(String s, List history) {
return callStaticAnswerMethod(mc(), s, history);
}
static String callStaticAnswerMethod(Object c, String s, List history) {
String answer = (String) callOpt(c, "answer", s, history);
if (answer == null)
answer = (String) callOpt(c, "answer", s);
return emptyToNull(answer);
}
static volatile boolean readLine_noReadLine;
static String readLine() {
if (readLine_noReadLine) return null;
return (String) call(getJavaX(), "readLine");
}
static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
static int parseInt(char c) {
return Integer.parseInt(str(c));
}
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 Object print_byThread_lock = new Object();
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) {
F1 f = print_byThread.get();
if (f != null)
if (isFalse(f.get(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 randomID_defaultLength = 12;
static String randomID(int length) {
return makeRandomID(length);
}
static String randomID() {
return randomID(randomID_defaultLength);
}
static String getProgramName_cache;
static synchronized String getProgramName() {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitleOpt(programID());
return getProgramName_cache;
}
static int isAndroid_flag;
static boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
static String[] dropFirst(String[] a) {
return drop(1, a);
}
static Object[] dropFirst(Object[] a) {
return drop(1, a);
}
static List dropFirst(List l) {
return dropFirst(1, l);
}
static List dropFirst(Iterable i) {
return dropFirst(toList(i));
}
static List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
static List dropFirst(List l, int n) {
return dropFirst(n, l);
}
static String dropFirst(int n, String s) { return substring(s, n); }
static String dropFirst(String s) { return substring(s, 1); }
static boolean equalsIgnoreCase(String a, String b) {
return a == null ? b == null : a.equalsIgnoreCase(b);
}
static boolean equalsIgnoreCase(char a, char b) {
if (a == b) return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2) return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static String 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 String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix)) return s;
return replacement + substring(s, l(prefix));
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static DialogIO talkToSubBot(final long vport, final DialogIO io) {
return talkToSubBot(String.valueOf(vport), io);
}
static DialogIO talkToSubBot(final String subBot, final DialogIO io) {
if (subBot == null) return io;
return new talkToSubBot_IO(subBot, io);
}
static class talkToSubBot_IO extends DialogIO {
String subBot;
DialogIO io;
talkToSubBot_IO(String subBot, DialogIO io) {
this.io = io;
this.subBot = subBot;}
// delegate all but sendLine
boolean isStillConnected() { return io.isStillConnected(); }
String readLineImpl() { return io.readLineImpl(); }
boolean isLocalConnection() { return io.isLocalConnection(); }
Socket getSocket() { return io.getSocket(); }
void close() { io.close(); }
void sendLine(String line) {
io.sendLine(format3("please forward to bot *: *", subBot, line));
}
}
static Set synchroTreeSet() {
return Collections.synchronizedSet(new TreeSet ());
}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
static void showConsole() {
showFrame(consoleFrame());
}
static Object unstructure(String text) {
return unstructure(text, false);
}
static Object unstructure(String text, final boolean allDynamic) {
return unstructure(text, allDynamic, null);
}
static int structure_internStringsLongerThan = 50;
static int unstructure_tokrefs; // stats
abstract static class unstructure_Receiver {
abstract void set(Object o);
}
// classFinder: func(name) -> class (optional)
static Object unstructure(String text, boolean allDynamic,
Object classFinder) {
if (text == null) return null;
return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
}
static Object unstructure_reader(BufferedReader reader) {
return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
}
static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object classFinder) {
final boolean debug = unstructure_debug;
final class X {
int i = -1;
HashMap refs = new HashMap();
HashMap tokrefs = new HashMap();
HashSet concepts = new HashSet();
HashMap classesMap = new HashMap();
List stack = new ArrayList();
String curT;
// look at current token
String t() {
return curT;
}
// get current token, move to next
String tpp() {
String t = curT;
consume();
return t;
}
void parse(final unstructure_Receiver out) {
String t = t();
int refID = 0;
if (structure_isMarker(t, 0, l(t))) {
refID = parseInt(t.substring(1));
consume();
}
final int _refID = refID;
// if (debug) print("parse: " + quote(t));
final int tokIndex = i;
parse_inner(refID, tokIndex, new unstructure_Receiver() {
void set(Object o) {
if (_refID != 0)
refs.put(_refID, o);
if (o != null)
tokrefs.put(tokIndex, o);
out.set(o);
}
});
}
void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) {
String t = t();
// if (debug) print("parse_inner: " + quote(t));
Class c = classesMap.get(t);
if (c == null) {
if (t.startsWith("\"")) {
String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
out.set(s); return;
}
if (t.startsWith("'")) {
out.set(unquoteCharacter(tpp())); return;
}
if (t.equals("bigint")) {
out.set(parseBigInt()); return;
}
if (t.equals("d")) {
out.set(parseDouble()); return;
}
if (t.equals("fl")) {
out.set(parseFloat()); return;
}
if (t.equals("false") || t.equals("f")) {
consume(); out.set(false); return;
}
if (t.equals("true") || t.equals("t")) {
consume(); out.set(true); return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
//if (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t));
if (isLongConstant(t)) {
out.set(parseLong(t)); return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
if (debug)
print("l=" + l + ", isInt: " + isInt);
out.set(isInt ? (Object) new Integer((int) l) : (Object) new Long(l)); return;
}
if (t.equals("File")) {
consume();
File f = new File(unquote(tpp()));
out.set(f); return;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
print("Warning: unsatisfied back reference " + ref);
out.set(o); return;
}
if (t.startsWith("t") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = tokrefs.get(ref);
if (o == null)
print("Warning: unsatisfied token reference " + ref);
out.set(o); return;
}
if (t.equals("hashset")) {
parseHashSet(out); return;
}
if (t.equals("treeset")) {
parseTreeSet(out); return;
}
if (eqOneOf(t, "hashmap", "hm")) {
consume();
parseMap(new HashMap(), out);
return;
}
if (t.equals("lhm")) {
consume();
parseMap(new LinkedHashMap(), out);
return;
}
if (t.equals("{")) {
parseMap(out); return;
}
if (t.equals("[")) {
parseList(out); return;
}
if (t.equals("bitset")) {
parseBitSet(out); return;
}
if (t.equals("array") || t.equals("intarray")) {
parseArray(out); return;
}
if (t.equals("ba")) {
consume();
String hex = unquote(tpp());
out.set(hexToBytes(hex)); return;
}
if (t.equals("boolarray")) {
consume();
int n = parseInt(tpp());
String hex = unquote(tpp());
out.set(boolArrayFromBytes(hexToBytes(hex), n)); return;
}
if (t.equals("class")) {
out.set(parseClass()); return;
}
if (t.equals("l")) {
parseLisp(out); return;
}
if (t.equals("null")) {
consume(); out.set(null); return;
}
if (eq(t, "c")) {
consume("c");
t = t();
assertTrue(isJavaIdentifier(t));
concepts.add(t);
}
}
if (eq(t, "j")) {
consume("j");
out.set(parseJava()); return;
}
if (c == null && !isJavaIdentifier(t))
throw new RuntimeException("Unknown token " + (i+1) + ": " + t);
// any other class name
if (c == null) {
// First, find class
if (allDynamic) c = null;
else c = classFinder != null ? (Class) callF(classFinder, t) : findClass(t);
if (c != null)
classesMap.put(t, c);
}
// Check if it has an outer reference
consume();
boolean hasBracket = eq(t(), "(");
if (hasBracket) consume();
boolean hasOuter = hasBracket && eq(t(), "this$1");
DynamicObject dO = null;
Object o = null;
if (c != null) {
o = hasOuter ? nuStubInnerObject(c) : nuEmptyObject(c);
if (o instanceof DynamicObject) dO = (DynamicObject) o;
} else {
if (concepts.contains(t) && (c = findClass("Concept")) != null)
o = dO = (DynamicObject) nuEmptyObject(c);
else
dO = new DynamicObject();
dO.className = t;
if (debug) print("Made dynamic object " + t + " " + shortClassName(dO));
}
// Save in references list early because contents of object
// might link back to main object
if (refID != 0)
refs.put(refID, o != null ? o : dO);
tokrefs.put(tokIndex, o != null ? o : dO);
// NOW parse the fields!
final LinkedHashMap fields = new LinkedHashMap(); // preserve order
final Object _o = o;
final DynamicObject _dO = dO;
if (hasBracket) {
stack.add(new Runnable() { public void run() { try {
if (eq(t(), ")")) {
consume(")");
objRead(_o, _dO, fields);
out.set(_o != null ? _o : _dO);
} else {
final String key = unquote(tpp());
consume("=");
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object value) {
fields.put(key, value);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \")\")) {\r\n consume(\")\");\r\n objRead(_o, _dO, fie..."; }});
} else {
objRead(o, dO, fields);
out.set(o != null ? o : dO);
}
}
void objRead(Object o, DynamicObject dO, Map fields) {
if (o != null)
if (dO != null) {
if (debug)
printStructure("setOptAllDyn", fields);
setOptAllDyn(dO, fields);
} else {
setOptAll(o, fields);
}
else for (String field : keys(fields))
dO.fieldValues.put(field.intern(), fields.get(field));
if (o != null)
pcallOpt_noArgs(o, "_doneLoading");
}
void parseSet(final Set set, final unstructure_Receiver out) {
parseList(new unstructure_Receiver() {
void set(Object o) {
set.addAll((List) o);
out.set(set);
}
});
}
void parseLisp(final unstructure_Receiver out) {
consume("l");
consume("(");
final ArrayList list = new ArrayList();
stack.add(new Runnable() { public void run() { try {
if (eq(t(), ")")) {
consume(")");
out.set(newObject("main$Lisp", (String) list.get(0), subList(list, 1)));
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
list.add(o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \")\")) {\r\n consume(\")\");\r\n out.set(newObject(\"main$..."; }});
}
void parseBitSet(final unstructure_Receiver out) {
consume("bitset");
consume("{");
final BitSet bs = new BitSet();
stack.add(new Runnable() { public void run() { try {
if (eq(t(), "}")) {
consume("}");
out.set(bs);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
bs.set((Integer) o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n } ..."; }});
}
void parseList(final unstructure_Receiver out) {
consume("[");
final ArrayList list = new ArrayList();
stack.add(new Runnable() { public void run() { try {
if (eq(t(), "]")) {
consume("]");
out.set(list);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
//if (debug) print("List element type: " + getClassName(o));
list.add(o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"]\")) {\r\n consume(\"]\");\r\n out.set(list);\r\n ..."; }});
}
void parseArray(final unstructure_Receiver out) {
final String type = tpp();
consume("{");
final List list = new ArrayList();
stack.add(new Runnable() { public void run() { try {
if (eq(t(), "}")) {
consume("}");
out.set(type.equals("intarray") ? toIntArray(list) : list.toArray());
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
list.add(o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(type.equals(\"int..."; }});
}
Object parseClass() {
consume("class");
consume("(");
String name = unquote(tpp());
consume(")");
name = dropPrefix("main$", name);
Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass(name);
if (c != null) return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
dO.fieldValues.put("name", name);
return dO;
}
Object parseBigInt() {
consume("bigint");
consume("(");
String val = tpp();
if (eq(val, "-"))
val = "-" + tpp();
consume(")");
return new BigInteger(val);
}
Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tpp());
consume(")");
return Double.parseDouble(val);
}
Object parseFloat() {
consume("fl");
String val;
if (eq(t(), "(")) {
consume("(");
val = unquote(tpp());
consume(")");
} else {
val = unquote(tpp());
}
return Float.parseFloat(val);
}
void parseHashSet(unstructure_Receiver out) {
consume("hashset");
parseSet(new HashSet(), out);
}
void parseTreeSet(unstructure_Receiver out) {
consume("treeset");
parseSet(new TreeSet(), out);
}
void parseMap(unstructure_Receiver out) {
parseMap(new TreeMap(), out);
}
Object parseJava() {
String j = unquote(tpp());
Matches m = new Matches();
if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
else {
warn("Unknown Java object: " + j);
return null;
}
}
void parseMap(final Map map, final unstructure_Receiver out) {
consume("{");
stack.add(new Runnable() {
boolean v;
Object key;
public void run() {
if (v) {
v = false;
stack.add(this);
consume("=");
parse(new unstructure_Receiver() {
void set(Object value) {
map.put(key, value);
if (debug)
print("parseMap: Got value " + getClassName(value) + ", next token: " + quote(t()));
if (eq(t(), ",")) consume();
}
});
} else {
if (eq(t(), "}")) {
consume("}");
out.set(map);
} else {
v = true;
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
key = o;
}
});
}
} // if v else
} // run()
});
}
/*void parseSub(unstructure_Receiver out) {
int n = l(stack);
parse(out);
while (l(stack) > n)
stack
}*/
void consume() { curT = tok.next(); ++i; }
void consume(String s) {
if (!eq(t(), s)) {
/*S prevToken = i-1 >= 0 ? tok.get(i-1) : "";
S nextTokens = join(tok.subList(i, Math.min(i+2, tok.size())));
fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");*/
throw fail(quote(s) + " expected, got " + quote(t()));
}
consume();
}
void parse_x(unstructure_Receiver out) {
consume(); // get first token
parse(out);
while (nempty(stack))
popLast(stack).run();
}
}
final Var v = new Var();
X x = new X();
x.parse_x(new unstructure_Receiver() {
void set(Object o) { v.set(o); }
});
unstructure_tokrefs = x.tokrefs.size();
return v.get();
}
static boolean unstructure_debug;
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }
static String hideCredentials(String url) {
return url.replaceAll("([&?])_pass=[^&\\s\"]*", "$1_pass=");
}
static String getSnippetTitleOpt(String s) {
return isSnippetID(s) ? getSnippetTitle(s) : s;
}
static Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400);
static Rectangle defaultNewFrameBounds() {
return swing(new F0() { Rectangle get() { try {
defaultNewFrameBounds_r.translate(60, 20);
if (!screenRectangle().contains(defaultNewFrameBounds_r))
defaultNewFrameBounds_r.setLocation(30+random(30), 20+random(20));
return new Rectangle(defaultNewFrameBounds_r);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "defaultNewFrameBounds_r.translate(60, 20);\r\n if (!screenRectangle().contains(..."; }});
}
static String exceptionToStringShort(Throwable e) {
lastException(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 boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
throw fail(getClassName(o));
}
static boolean startsWithIgnoreCase(String a, String b) {
return a != null && a.regionMatches(true, 0, b, 0, b.length());
}
static String format3(String pat, Object... args) {
if (args.length == 0) return pat;
List tok = javaTokPlusPeriod(pat);
int argidx = 0;
for (int i = 1; i < tok.size(); i += 2)
if (tok.get(i).equals("*"))
tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null"));
return join(tok);
}
static String format3_formatArg(Object arg) {
if (arg == null) return "null";
if (arg instanceof String) {
String s = (String) arg;
return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s);
}
if (arg instanceof Integer || arg instanceof Long) return String.valueOf(arg);
return quote(structure(arg));
}
static A callMain(A c, String... args) {
callOpt(c, "main", new Object[] {args});
return c;
}
static void callMain() {
callMain(mc());
}
static A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
static JFrame renewFrame(final JFrame frame) {
if (frame == null) return null;
return (JFrame) swing(new Object() { Object get() { try {
Container content = frame.getContentPane();
JFrame frame2 = makeFrame(frame.getTitle());
frame2.setBounds(frame.getBounds());
try { frame2.setIconImages(frame.getIconImages()); } catch (Throwable __e) { printStackTrace2(__e); }
frame2.setDefaultCloseOperation(frame.getDefaultCloseOperation());
for (WindowListener wl : frame.getWindowListeners())
frame2.addWindowListener(wl);
frame.setContentPane(new JPanel());
frame2.setContentPane(content);
frame2.setVisible(true);
frame.dispose();
return frame2;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Container content = frame.getContentPane();\r\n JFrame frame2 = makeFrame(frame..."; }});
}
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 boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(String s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static String firstPartOfHelloString(String s) {
int i = s.lastIndexOf('/');
return i < 0 ? s : rtrim(s.substring(0, i));
}
static boolean isInteger(String s) {
if (s == null) return false;
int n = l(s);
if (n == 0) return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n) return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9') return false;
++i;
}
return true;
}
static String getStackTrace(Throwable throwable) {
lastException(throwable);
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static A last(List l) {
return empty(l) ? null : l.get(l.size()-1);
}
static char last(String s) {
return empty(s) ? '#' : s.charAt(l(s)-1);
}
static int last(int[] a) {
return l(a) != 0 ? a[l(a)-1] : 0;
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static boolean forbiddenPort(int port) {
return port == 5037; // adb
}
static void revalidate(final Component c) {
if (c == null || !c.isShowing()) return;
{ swing(new Runnable() { public void run() { try {
// magic combo to actually relayout and repaint
c.revalidate();
c.repaint();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// magic combo to actually relayout and repaint\r\n c.revalidate();\r\n c.repa..."; }}); }
}
// 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 String sendToLocalBotQuietly(String bot, String text, Object... args) {
text = format3(text, args);
DialogIO channel = newFindBot2(bot);
if (channel == null)
throw fail(quote(bot) + " not found");
try {
channel.readLine();
channel.sendLine(text);
String s = channel.readLine();
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
channel.close();
}
}
static String sendToLocalBotQuietly(int port, String text, Object... args) {
text = format3(text, args);
DialogIO channel = talkTo(port);
try {
channel.readLine();
channel.sendLine(text);
String s = channel.readLine();
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
if (channel != null)
channel.close();
}
}
static String[] drop(int n, String[] a) {
n = Math.min(n, a.length);
String[] b = new String[a.length-n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
static Object[] drop(int n, Object[] a) {
n = Math.min(n, a.length);
Object[] b = new Object[a.length-n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
static File loadDataSnippetToFile(String snippetID) { try {
snippetID = fsI(snippetID);
File f = DiskSnippetCache_file(parseSnippetID(snippetID));
try {
URL url = new URL(dataSnippetLink(snippetID));
print("Loading library: " + hideCredentials(url));
try {
loadBinaryPageToFile(openConnection(url), f);
if (fileSize(f) == 0) throw fail();
} catch (Throwable _e) {
url = new URL("http://tinybrain.de/blobs/" // TODO: should be data.tinybrain.de
+ psI(snippetID));
print("Trying other server: " + hideCredentials(url));
loadBinaryPageToFile(openConnection(url), f);
print("Got bytes: " + fileSize(f));
}
// TODO: check if we hit the "LOADING" message
if (fileSize(f) == 0) throw fail();
System.err.println("Bytes loaded: " + fileSize(f));
} catch (Throwable e) {
printStackTrace(e);
throw fail("Binary snippet " + snippetID + " not found or not public");
}
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static List quickBotScan() {
return ProgramScan.quickBotScan();
}
static List quickBotScan(int[] preferredPorts) {
return ProgramScan.quickBotScan(preferredPorts);
}
static List quickBotScan(String searchPattern) {
List l = new ArrayList();
for (ProgramScan.Program p : ProgramScan.quickBotScan())
if (indexOfIgnoreCase(p.helloString, searchPattern) == 0)
l.add(p);
return l;
}
static void standardTitlePopupMenu(final JFrame frame) {
// standard right-click behavior on titles
if (isSubstanceLAF())
titlePopupMenu(frame,
new Object() { void get(JPopupMenu menu) { try {
boolean alwaysOnTop = frame.isAlwaysOnTop();
menu.add(jmenuItem("Restart Program", "restart"));
menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram"));
menu.add(jmenuItem("Show Console", "showConsole"));
menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() { public void run() { try {
toggleAlwaysOnTop(frame) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "toggleAlwaysOnTop(frame)"; }}));
menu.add(jMenuItem("Shoot Window", new Runnable() { public void run() { try { shootWindowGUI_external(frame, 500) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "shootWindowGUI_external(frame, 500)"; }}));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n menu.add(jmenuItem(\"Restart P..."; }});
}
static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static String makeRandomID(int length) {
Random random = new Random();
char[] id = new char[length];
for (int i = 0; i < id.length; i++)
id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
static boolean headless() {
return isHeadless();
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static Runnable _topLevelErrorHandling(final Runnable runnable) {
return new Runnable() { public void run() { try { try { runnable.run(); } catch (Throwable __e) { printStackTrace2(__e); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall { runnable.run(); }"; }};
}
static File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
// Data files are immutable, use centralized cache
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = DiskSnippetCache_file(snippetID);
return file.exists() ? file : null;
}
public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(DiskSnippetCache_file(snippetID), data);
}
static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
+ parseSnippetID(snippetID) + "&contentType=application/binary");
System.err.println("Loading library: " + url);
try {
data = loadBinaryPage(url.openConnection());
} catch (RuntimeException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL("http://data.tinybrain.de/blobs/"
+ parseSnippetID(snippetID));
System.err.println("Loading library: " + url);
data = loadBinaryPage(url.openConnection());
}
System.err.println("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
static void lock(Lock lock) { try {
lock.lockInterruptibly();
} catch (Exception __e) { throw rethrow(__e); } }
static void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static ReentrantLock lock() {
return fairLock();
}
static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static DialogIO talkTo(int port) {
return talkTo("localhost", port);
}
static int talkTo_defaultTimeout = 10000; // This is the CONNECT timeout
static int talkTo_timeoutForReads = 0; // Timeout waiting for answers (0 = no timeout)
static ThreadLocal> talkTo_byThread = new ThreadLocal();
static DialogIO talkTo(String ip, int port) { try {
String full = ip + ":" + port;
Map map = talkTo_byThread.get();
if (map != null && map.containsKey(full)) return map.get(full);
if (isLocalhost(ip) && port == vmPort()) return talkToThisVM();
return new talkTo_IO(ip, port);
} catch (Exception __e) { throw rethrow(__e); } }
static class talkTo_IO extends DialogIO {
String ip;
int port;
Socket s;
Writer w;
BufferedReader in;
talkTo_IO(String ip, int port) {
this.port = port;
this.ip = ip; try {
s = new Socket();
try {
if (talkTo_timeoutForReads != 0)
s.setSoTimeout(talkTo_timeoutForReads);
s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout);
} catch (Throwable e) {
throw fail("Tried talking to " + ip + ":" + port, e);
}
w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
} catch (Exception __e) { throw rethrow(__e); } }
boolean isLocalConnection() {
return s.getInetAddress().isLoopbackAddress();
}
boolean isStillConnected() {
return !(eos || s.isClosed());
}
void sendLine(String line) { try {
w.write(line + "\n");
w.flush();
} catch (Exception __e) { throw rethrow(__e); } }
String readLineImpl() { try {
return in.readLine();
} catch (Exception __e) { throw rethrow(__e); } }
void close() {
try {
if (!noClose) s.close();
} catch (IOException e) {
// whatever
}
}
Socket getSocket() {
return s;
}
}
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 volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = (Map) synchroMap(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) {
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;
}
static void setConsoleFrame(JFrame frame) {
setOpt(get(getJavaX(), "console"), "frame", frame);
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
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 ArrayList litlist(A... a) {
return new ArrayList (Arrays.asList(a));
}
static List getClasses(Object[] array) {
List l = new ArrayList();
for (Object o : array) l.add(_getClass(o));
return l;
}
static String programTitle() {
return getProgramName();
}
// works on lists and strings and null
static int indexOfIgnoreCase(Object a, Object b) {
if (a == null) return -1;
if (a instanceof String) {
Matcher m = Pattern.compile((String) b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher((String) a);
if (m.find()) return m.start(); else return -1;
}
if (a instanceof List) {
for (int i = 0; i < ((List) a).size(); i++) {
Object o = ((List) a).get(i);
if (o != null && ((String) o).equalsIgnoreCase((String) b))
return i;
}
return -1;
}
throw fail("Unknown type: " + a);
}
static 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 String getLookAndFeel() {
return getClassName(UIManager.getLookAndFeel());
}
static ArrayList toList(A[] a) { return asList(a); }
static ArrayList toList(int[] a) { return asList(a); }
static ArrayList toList(Set s) { return asList(s); }
static ArrayList toList(Iterable s) { return asList(s); }
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static List getMultiPorts() {
return (List) callOpt(getJavaX(), "getMultiPorts");
}
static String emptyToNull(String s) {
return eq(s, "") ? null : s;
}
static long fileSize(String path) { return getFileSize(path); }
static long fileSize(File f) { return getFileSize(f); }
static int indent_default = 2;
static String indent(int indent) {
return repeat(' ', indent);
}
static String indent(int indent, String s) {
return indent(repeat(' ', indent), s);
}
static String indent(String indent, String s) {
return indent + s.replace("\n", "\n" + indent);
}
static String indent(String s) {
return indent(indent_default, s);
}
static List indent(String indent, List lines) {
List l = new ArrayList();
for (String s : lines)
l.add(indent + s);
return l;
}
static String substring(String s, int x) {
return substring(s, x, l(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
if (x > s.length()) return "";
if (y < x) y = x;
if (y > s.length()) y = s.length();
return s.substring(x, y);
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static String repeat(char c, int n) {
n = Math.max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++)
chars[i] = c;
return new String(chars);
}
static List repeat(A a, int n) {
List l = new ArrayList(n);
for (int i = 0; i < n; i++)
l.add(a);
return l;
}
static List repeat(int n, A a) {
return repeat(a, n);
}
static Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
static Class> hotwire(String src) {
assertFalse(_inCore());
Class j = getJavaX();
if (isAndroid()) {
synchronized(j) { // hopefully this goes well...
List libraries = new ArrayList();
File srcDir = (File) call(j, "transpileMain", src, libraries);
if (srcDir == null)
throw fail("transpileMain returned null (src=" + quote(src) + ")");
Object androidContext = get(j, "androidContext");
return (Class) call(j, "loadx2android", srcDir, src);
}
} else {
// ret hotwire_overInternalBot(src);
Class c = (Class) ( call(j, "hotwire", src));
hotwire_copyOver(c);
return c;
}
}
public static String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(File fileName, String defaultContents) {
ping();
try {
if (fileName == null || !fileName.exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(String fileName, String defaultContents) {
return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
}
public static String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer)))
builder.append(buffer, 0, n);
} finally {
reader.close();
}
return builder.toString();
}
static List dropPunctuation_keep = litlist("*", "<", ">");
static List dropPunctuation(List tok) {
tok = new ArrayList(tok);
for (int i = 1; i < tok.size(); i += 2) {
String t = tok.get(i);
if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) {
tok.set(i-1, tok.get(i-1) + tok.get(i+1));
tok.remove(i);
tok.remove(i);
i -= 2;
}
}
return tok;
}
static String dropPunctuation(String s) {
return join(dropPunctuation(nlTok(s)));
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
// start multi-port if none exists in current VM.
static void startMultiPort() {
List mp = getMultiPorts();
if (mp != null && mp.isEmpty()) {
nohupJavax("#1001639");
throw fail("Upgrading JavaX, please restart this program afterwards.");
//callMain(hotwire("#1001672"));
}
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, char c) {
return nempty(a) && a.charAt(0) == c;
}
static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
m.m = new String[] {substring(a, l(b))};
return true;
}
static boolean startsWith(List a, List b) {
if (a == null || l(b) > l(a)) return false;
for (int i = 0; i < l(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static 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 Map newFindBot2_cache = synchroHashMap();
static boolean newFindBot2_verbose;
static DialogIO newFindBot2(String name) {
Integer port = newFindBot2_cache.get(name);
if (port != null) {
if (newFindBot2_verbose)
print("newFindBot2: testing " + name + " => " + port);
DialogIO io = talkTo(port);
String q = format("has bot *", name);
String s = io.ask(q);
if (match("yes", s)) {
io = talkToSubBot(name, io);
call(io, "pushback", "?"); // put some hello string in (yes, this should be improved.)
return io;
}
// bot not there anymore - remove cache entry
newFindBot2_cache.remove(name);
if (newFindBot2_verbose)
print("newFindBot2: dropping " + name + " => " + port);
}
DialogIO io = findBot(name);
if (io != null) {
newFindBot2_cache.put(name, io.getPort());
if (newFindBot2_verbose)
print("newFindBot2: remembering " + name + " => " + port);
}
return io;
}
static Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static Thread currentThread() {
return Thread.currentThread();
}
static byte[] hexToBytes(String s) {
int n = l(s) / 2;
byte[] bytes = new byte[n];
for (int i = 0; i < n; i++) {
String hex = substring(s, i*2, i*2+2);
try {
bytes[i] = (byte) parseHexByte(hex);
} catch (Throwable _e) {
throw fail("Bad hex byte: " + quote(hex) + " at " + i*2 + "/" + l(s));
}
}
return bytes;
}
static HashMap nuEmptyObject_cache = new HashMap();
static A nuEmptyObject(Class c) { try {
Constructor ctr;
synchronized(nuEmptyObject_cache) {
ctr = nuEmptyObject_cache.get(c);
if (ctr == null) {
nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
ctr.setAccessible(true);
}
}
return (A) ctr.newInstance();
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuEmptyObject_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors())
if (m.getParameterTypes().length == 0)
return m;
throw fail("No default constructor declared in " + c.getName());
}
static String getType(Object o) {
return getClassName(o);
}
static boolean setOptAllDyn_debug;
static void setOptAllDyn(DynamicObject o, Map fields) {
if (fields == null) return;
for (String field : keys(fields)) {
Object val = fields.get(field);
boolean has = hasField(o, field);
if (has)
setOpt(o, field, val);
else {
o.fieldValues.put(field.intern(), val);
if (setOptAllDyn_debug) print("setOptAllDyn added dyn " + field + " to " + o + " [value: " + val + ", fieldValues = " + systemHashCode(o.fieldValues) + ", " + struct(keys(o.fieldValues)) + "]");
}
}
}
static String unnull(String s) {
return s == null ? "" : s;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static boolean structure_isMarker(String s, int i, int j) {
if (i >= j) return false;
if (s.charAt(i) != 'm') return false;
++i;
while (i < j) {
char c = s.charAt(i);
if (c < '0' || c > '9') return false;
++i;
}
return true;
}
static Object newObject(Class c, Object... args) {
return nuObject(c, args);
}
static Object newObject(String className, Object... args) {
return nuObject(className, args);
}
// menuMaker = voidfunc(JPopupMenu)
static void titlePopupMenu(final Component c, final Object menuMaker) {
swingNowOrLater(new Runnable() { public void run() { try {
if (!isSubstanceLAF())
print("Can't add title right click!");
else {
JComponent titleBar = getTitlePaneComponent(getFrame(c));
componentPopupMenu(titleBar, menuMaker);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!isSubstanceLAF())\r\n print(\"Can't add title right click!\");\r\n else {..."; }});
}
static int vmPort() {
return myVMPort();
}
static void duplicateThisProgram() {
nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs"))));
}
static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static List subList(List l, int startIndex, int endIndex) {
startIndex = max(0, min(l(l), startIndex));
endIndex = max(0, min(l(l), endIndex));
if (startIndex > endIndex) return litlist();
return l.subList(startIndex, endIndex);
}
static File getGlobalCache() {
File file = new File(javaxCachesDir(), "Binary Snippets");
file.mkdirs();
return file;
}
static void lockOrFail(Lock lock, long timeout) { try {
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) ( lock);
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
} catch (Exception __e) { throw rethrow(__e); } }
static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static Class _getClass(Object o) {
return o == null ? null
: o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) { try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (Exception __e) { throw rethrow(__e); } }
static boolean jmatch(String pat, String s) {
return jmatch(pat, s, null);
}
static boolean jmatch(String pat, String s, Matches matches) {
if (s == null) return false;
return jmatch(pat, javaTok(s), matches);
}
static boolean jmatch(String pat, List toks) {
return jmatch(pat, toks, null);
}
static boolean jmatch(String pat, List toks, Matches matches) {
List tokpat = javaTok(pat);
String[] m = match2(tokpat, toks);
//print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
if (m == null)
return false;
else {
if (matches != null) matches.m = m;
return true;
}
}
static boolean isNonNegativeInteger(String s) {
return s != null && Pattern.matches("\\d+", s);
}
static URLConnection openConnection(URL url) { try {
ping();
callOpt(javax(), "recordOpenURLConnection", str(url));
return url.openConnection();
} catch (Exception __e) { throw rethrow(__e); } }
static long psI(String snippetID) {
return parseSnippetID(snippetID);
}
static Producer javaTokC_noMLS_iterator(final String s) {
return new Producer() {
final int l = s.length();
int i = 0;
public String next() {
if (i >= l) return null;
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
i = j;
if (i >= l) return null;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else
++j;
String t = quickSubstring(s, i, j);
i = j;
return t;
}
};
}
static boolean warn_on = true;
static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
}
static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static File newFile(String name) {
return name == null ? null : new File(name);
}
/** 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 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 shortClassName(Object o) {
if (o == null) return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
static ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static void setOptAll(Object o, Map fields) {
if (fields == null) return;
for (String field : keys(fields))
setOpt(o, field, fields.get(field));
}
static void setOptAll(Object o, Object... values) {
//values = expandParams(c.getClass(), values);
warnIfOddCount(values);
for (int i = 0; i+1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i+1];
setOpt(o, field, value);
}
}
static char unquoteCharacter(String s) {
assertTrue(s.startsWith("'") && s.length() > 1);
return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length()-1 : s.length()) + "\"").charAt(0);
}
static Producer javaTokC_noMLS_onReader(final BufferedReader r) {
final class X implements Producer {
StringBuilder buf = new StringBuilder(); // stores from "i"
char c, d, e = 'x'; // just not '\0'
X() {
// fill c, d and e
nc();
nc();
nc();
}
// get next character(s) into c, d and e
void nc() { try {
c = d;
d = e;
if (e == '\0') return;
int i = r.read();
e = i < 0 ? '\0' : (char) i;
} catch (Exception __e) { throw rethrow(__e); } }
void ncSave() {
if (c != '\0') {
buf.append(c);
nc();
}
}
public String next() {
// scan for whitespace
while (c != '\0') {
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
nc();
else if (c == '/' && d == '*') {
do nc(); while (c != '\0' && !(c == '*' && d == '/'));
nc(); nc();
} else if (c == '/' && d == '/') {
do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
} else
break;
}
if (c == '\0') return null;
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
ncSave();
while (c != '\0') {
if (c == opener || c == '\n') { // end at \n to not propagate unclosed string literal errors
ncSave();
break;
} else if (c == '\\') {
ncSave();
ncSave();
} else
ncSave();
}
} else if (Character.isJavaIdentifierStart(c))
do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\''); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ncSave(); while (Character.isDigit(c));
if (c == 'L') ncSave(); // Long constants like 1L
} else
ncSave();
String t = buf.toString();
buf.setLength(0);
return t;
}
}
return new X();
}
static List nlTok(String s) {
return javaTokPlusPeriod(s);
}
static Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
static void setOpt(Object o, String field, Object value) { try {
if (o == null) return;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
// It's probably a subclass of Map. Use raw method
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null)
smartSet(f, o, value); // possible improvement: skip setAccessible
} catch (Exception __e) { throw rethrow(__e); } }
static void setOpt(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static A popLast(List l) {
return liftLast(l);
}
static String dataSnippetLink(String snippetID) {
long id = parseSnippetID(snippetID);
if (id >= 1200000 && id < 1300000) {
String pw = muricaPassword();
if (empty(pw)) throw fail("Please set 'murica password by running #1008829");
return "http://ai1.lol/1008823/raw/" + id + "?_pass=" + pw; // XXX, although it typically gets hidden when printing
} else
return "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
+ id + "&contentType=application/binary";
}
static A nuStubInnerObject(Class c) { try {
Class outerType = getOuterClass(c);
Constructor m = c.getDeclaredConstructor(outerType);
m.setAccessible(true);
return (A) m.newInstance(new Object[] {null});
} catch (Exception __e) { throw rethrow(__e); } }
static volatile Throwable lastException_lastException;
static Throwable lastException() {
return lastException_lastException;
}
static void lastException(Throwable e) {
lastException_lastException = e;
}
static boolean[] boolArrayFromBytes(byte[] a, int n) {
boolean[] b = new boolean[n];
int m = min(n, l(a)*8);
for (int i = 0; i < m; i++)
b[i] = (a[i/8] & 1 << (i & 7)) != 0;
return b;
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static boolean isSubstanceLAF() {
return substanceLookAndFeelEnabled();
}
static JMenuItem jmenuItem(String text, final Object r) {
JMenuItem mi = new JMenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
static HashMap findClass_cache = new HashMap();
// currently finds only inner classes of class "main"
// returns null on not found
// this is the simple version that is not case-tolerant
static Class findClass(String name) {
synchronized(findClass_cache) {
if (findClass_cache.containsKey(name))
return findClass_cache.get(name);
if (!isJavaIdentifier(name)) return null;
Class c;
try {
c = Class.forName("main$" + name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_cache.put(name, c);
return c;
}
}
static float parseFloat(String s) {
return Float.parseFloat(s);
}
static boolean _inCore() {
return false;
}
static DialogIO talkToThisVM() {
return new talkToThisVM_IO();
}
static class talkToThisVM_IO extends DialogIO {
List answers = ll(thisVMGreeting());
boolean isLocalConnection() { return true; }
boolean isStillConnected() { return true; }
int getPort() { return vmPort(); }
void sendLine(String line) {
answers.add(or2(sendToThisVM_newThread(line), "?"));
}
String readLineImpl() { try {
return popFirst(answers);
} catch (Exception __e) { throw rethrow(__e); } }
void close() {}
Socket getSocket() { return null; }
}
static void assertTrue(Object o) {
assertEquals(true, o);
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static boolean isLongConstant(String s) {
if (!s.endsWith("L")) return false;
s = s.substring(0, l(s)-1);
return isInteger(s);
}
static String baseClassName(String className) {
return substring(className, className.lastIndexOf('.')+1);
}
static String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
static String internIfLongerThan(String s, int l) {
return s == null ? null : l(s) >= l ? s.intern() : s;
}
static void pcallOpt_noArgs(Object o, String method) {
try { callOpt_noArgs(o, method); } catch (Throwable __e) { printStackTrace2(__e); }
}
static void restart() {
Object j = getJavaX();
call(j, "cleanRestart", get(j, "fullArgs"));
}
static long parseLong(String s) {
if (s == null) return 0;
return Long.parseLong(dropSuffix("L", s));
}
static long parseLong(Object s) {
return Long.parseLong((String) s);
}
static List ll(A... a) {
return litlist(a);
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static String getSnippetTitle(String id) { try {
if (id == null) return null;
if (!isSnippetID(id)) return "?";
long parsedID = parseSnippetID(id);
String url;
if (isImageServerSnippet(parsedID))
url = "http://ai1.lol/images/raw/title/" + parsedID;
else
url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials();
return trim(loadPageSilently(url));
} catch (Exception __e) { throw rethrow(__e); } }
static String getSnippetTitle(long id) {
return getSnippetTitle(fsI(id));
}
static void loadBinaryPageToFile(String url, File file) { try {
print("Loading " + url);
loadBinaryPageToFile(openConnection(new URL(url)), file);
} catch (Exception __e) { throw rethrow(__e); } }
static void loadBinaryPageToFile(URLConnection con, File file) { try {
setHeaders(con);
loadBinaryPageToFile_noHeaders(con, file);
} catch (Exception __e) { throw rethrow(__e); } }
static void loadBinaryPageToFile_noHeaders(URLConnection con, File file) { try {
File ftemp = new File(f2s(file) + "_temp");
FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
InputStream inputStream = con.getInputStream();
try {
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.");
}
buf.close();
buf = null;
file.delete();
ftemp.renameTo(file);
inputStream.close();
} finally {
if (buf != null) buf.close();
}
} catch (Exception __e) { throw rethrow(__e); } }
static void hotwire_copyOver(Class c) {
synchronized(StringBuffer.class) {
for (String field : litlist("print_log", "print_silent", "androidContext")) {
Object o = getOpt(mc(), field);
if (o != null)
setOpt(c, field, o);
}
Object mainBot = getMainBot();
if (mainBot != null)
setOpt(c, "mainBot", mainBot);
setOpt(c, "creator_class", new WeakReference(mc()));
}
}
static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked);
mi.addActionListener(actionListener(r));
return mi;
}
static int[] toIntArray(List l) {
int[] a = new int[l(l)];
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
return a;
}
static void printStructure(String prefix, Object o) {
if (endsWithLetter(prefix)) prefix += ": ";
print(prefix + structureForUser(o));
}
static void printStructure(Object o) {
print(structureForUser(o));
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static JMenuItem jMenuItem(String text, Object r) {
return jmenuItem(text, r);
}
static Rectangle screenRectangle() {
return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static void assertFalse(Object o) {
assertEquals(false, o);
}
static boolean assertFalse(boolean b) {
if (b) throw fail("oops");
return b;
}
static boolean assertFalse(String msg, boolean b) {
if (b) throw fail(msg);
return b;
}
static double parseDouble(String s) {
return Double.parseDouble(s);
}
static void toggleAlwaysOnTop(JFrame frame) {
frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
}
static void shootWindowGUI_external(JFrame frame) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame);
}
static void shootWindowGUI_external(final JFrame frame, int delay) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame, delay);
}
static byte[] loadBinaryPage(String url) { try {
print("Loading " + url);
return loadBinaryPage(loadPage_openConnection(new URL(url)));
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] loadBinaryPage(URLConnection con) { try {
setHeaders(con);
return loadBinaryPage_noHeaders(con);
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] loadBinaryPage_noHeaders(URLConnection con) { try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
InputStream inputStream = con.getInputStream();
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 (Exception __e) { throw rethrow(__e); } }
static boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
return structure(o, new structure_Data());
}
static String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack))
popLast(d.stack).run();
}
static void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static class structure_Data {
PrintWriter out;
int stringSizeLimit;
int shareStringsLongerThan = 20;
boolean noStringSharing;
IdentityHashMap seen = new IdentityHashMap();
//new BitSet refd;
HashMap strings = new HashMap();
HashSet concepts = new HashSet();
HashMap> fieldsByClass = new HashMap();
int n; // token count
List stack = new ArrayList();
// append single token
structure_Data append(String token) { out.print(token); ++n; return this; }
structure_Data append(int i) { out.print(i); ++n; return this; }
// append multiple tokens
structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; }
// extend last token
structure_Data app(String token) { out.print(token); return this; }
structure_Data app(int i) { out.print(i); return this; }
}
static void structure_1(final Object o, final structure_Data d) {
if (o == null) { d.append("null"); return; }
Class c = o.getClass();
boolean concept = false;
List lFields = d.fieldsByClass.get(c);
if (lFields == null) {
// these are never back-referenced (for readability)
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; }
if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; }
if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; }
if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; }
if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; }
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f"); return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o)); return;
}
if (o instanceof File) {
d.append("File ").append(quote(((File) o).getPath())); return;
}
// referencable objects follow
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null) ref = d.strings.get((String) o);
if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
if (!(o instanceof String))
d.seen.put(o, d.n); // record token number
else {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out); d.n++; return;
}
if (o instanceof HashSet) {
d.append("hashset ");
structure_1(new ArrayList((Set) o), d);
return;
}
if (o instanceof TreeSet) {
d.append("treeset ");
structure_1(new ArrayList((Set) o), d);
return;
}
String name = c.getName();
if (o instanceof Collection
&& !startsWith(name, "main$")
/* && neq(name, "main$Concept$RefL") */) {
d.append("[");
final int l = d.n;
final Iterator it = ((Collection) o).iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.stack...."; }});
return;
}
if (o instanceof Map && !startsWith(name, "main$")) {
if (o instanceof LinkedHashMap) d.append("lhm");
else if (o instanceof HashMap) d.append("hm");
d.append("{");
final int l = d.n;
final Iterator it = ((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
boolean v;
Map.Entry e;
public void run() {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(e.getKey(), d);
}
}
}
});
return;
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o))); return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return;
}
String atype = "array", sep = ", ";
if (o instanceof int[]) {
//ret "intarray " + quote(intArrayToHex((int[]) o));
atype = "intarray";
sep = " ";
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0) d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
if (d.n != l) d.append(", ");
d.append(i);
}
d.append("}"); return;
}
// Need more cases? This should cover all library classes...
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o))); return; // Hm. this is not unstructure-able
}
/*if (name.equals("main$Lisp")) {
fail("lisp not supported right now");
}*/
String dynName = shortDynamicClassName(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
// serialize an object with fields.
// first, collect all fields and values in fv.
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
if ((field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0)
continue;
String fieldName = field.getName();
fields.add(field);
// put special cases here...
}
cc = cc.getSuperclass();
}
lFields = asList(fields);
// Render this$1 first because unstructure needs it for constructor call.
for (int i = 0; i < l(lFields); i++) {
Field f = lFields.get(i);
if (f.getName().equals("this$1")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
d.fieldsByClass.put(c, lFields);
} // << if (lFields == null)
else { // ref handling for lFields != null
Integer ref = d.seen.get(o);
if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
d.seen.put(o, d.n); // record token number
}
LinkedHashMap fv = new LinkedHashMap();
for (Field f : lFields) {
Object value;
try {
value = f.get(o);
} catch (Exception e) {
value = "?";
}
if (value != null)
fv.put(f.getName(), value);
}
String name = c.getName();
String shortName = dropPrefix("main$", name);
// Now we have fields & values. Process fieldValues if it's a DynamicObject.
// omit field "className" if equal to class's name
if (concept && eq(fv.get("className"), shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
fv.putAll((Map) fv.get("fieldValues"));
fv.remove("fieldValues");
shortName = shortDynamicClassName(o);
fv.remove("className");
}
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
d.append(shortName);
final int l = d.n;
final Iterator it = fv.entrySet().iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext()) {
if (d.n != l)
d.append(")");
} else {
Map.Entry e = (Map.Entry) it.next();
d.append(d.n == l ? "(" : ", ");
d.append((String) e.getKey()).append("=");
d.stack.add(this);
structure_1(e.getValue(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else {\r..."; }});
}
static File userDir() {
return new File(userHome());
}
static File userDir(String path) {
return new File(userHome(), path);
}
static boolean isLocalhost(String ip) {
return isLoopbackIP(ip) || eqic(ip, "localhost");
}
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 String quoteCharacter(char c) {
if (c == '\'') return "'\\''";
if (c == '\\') return "'\\\\'";
if (c == '\r') return "'\\r'";
if (c == '\n') return "'\\n'";
if (c == '\t') return "'\\t'";
return "'" + c + "'";
}
static String shortDynamicClassName(Object o) {
if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
return ((DynamicObject) o).className;
return shortClassName(o);
}
static String standardCredentials() {
String user = standardCredentialsUser();
String pass = standardCredentialsPass();
if (nempty(user) && nempty(pass))
return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
return "";
}
static JComponent getTitlePaneComponent(Window window) {
if (!substanceLookAndFeelEnabled()) return null;
JRootPane rootPane = null;
if (window instanceof JFrame)
rootPane = ((JFrame) window).getRootPane();
if (window instanceof JDialog)
rootPane = ((JDialog) window).getRootPane();
if (rootPane != null) {
Object /*SubstanceRootPaneUI*/ ui = rootPane.getUI();
return (JComponent) call(ui, "getTitlePane");
}
return null;
}
static String quickSubstring(String s, int i, int j) {
if (i == j) return "";
return s.substring(i, j);
}
static A liftLast(List l) {
if (l.isEmpty()) return null;
int i = l(l)-1;
A a = l.get(i);
l.remove(i);
return a;
}
// 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
// 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 && javaTok_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(quickSubstring(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static List javaTok(List tok) {
return javaTok(join(tok), tok);
}
static boolean javaTok_isCopyable(String t, String s, int i, int j) {
return t.length() == j-i
&& s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static Object mainBot;
static Object getMainBot() {
return mainBot;
}
static int myVMPort() {
List records = (List) ( get(getJavaX(), "record_list"));
Object android = records.get(records.size()-1);
return (Integer) get(android, "port");
}
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());
component.addMouseListener(new componentPopupMenu_Adapter(maker));
}
maker.menuMakers.add(menuMaker);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "componentPopupMenu_Maker maker = componentPopupMenu_map.get(component);\r\n if ..."; }});
}
static class componentPopupMenu_Adapter extends MouseAdapter {
componentPopupMenu_Maker maker;
componentPopupMenu_Adapter(componentPopupMenu_Maker maker) {
this.maker = maker;}
public void mousePressed(MouseEvent e) { displayMenu(e); }
public void mouseReleased(MouseEvent e) { displayMenu(e); }
void displayMenu(MouseEvent e) {
if (e.isPopupTrigger()) displayMenu2(e);
}
void displayMenu2(MouseEvent e) {
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());
}
}
static void setHeaders(URLConnection con) throws IOException {
String computerID = getComputerID_quick();
if (computerID != null) try {
con.setRequestProperty("X-ComputerID", computerID);
con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
} catch (Throwable e) {
//printShortException(e);
}
}
static HashMap getDeclaredFields_cache = new HashMap();
static Field[] getDeclaredFields_cached(Class c) {
Field[] fields;
synchronized(getDeclaredFields_cache) {
fields = getDeclaredFields_cache.get(c);
if (fields == null) {
getDeclaredFields_cache.put(c, fields = c.getDeclaredFields());
for (Field f : fields)
f.setAccessible(true);
}
}
return fields;
}
static String boolArrayToHex(boolean[] a) {
return bytesToHex(boolArrayToBytes(a));
}
static boolean hasField(Object o, String field) {
return findField2(o, field) != null;
}
static String thisVMGreeting() {
List record_list = (List) ( get(getJavaX(), "record_list"));
Object android = first(record_list); // Should be of class Android3
return getString(android, "greeting");
}
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len*2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs+i]);
stringBuilder.append(s.substring(s.length()-2, s.length()));
}
return stringBuilder.toString();
}
static A oneOf(List l) {
return l.isEmpty() ? null : l.get(new Random().nextInt(l.size()));
}
static char oneOf(String s) {
return empty(s) ? '?' : s.charAt(random(l(s)));
}
static String oneOf(String... l) {
return oneOf(asList(l));
}
static boolean isLoopbackIP(String ip) {
return eq(ip, "127.0.0.1");
}
static Class javax() {
return getJavaX();
}
static String classNameToVM(String name) {
return name.replace(".", "$");
}
static int systemHashCode(Object o) {
return identityHashCode(o);
}
static void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
static String muricaPassword() {
return trim(loadTextFile(muricaPasswordFile()));
}
static A collectionGet(Collection c, int idx) {
if (c == null || idx < 0 || idx >= l(c)) return null;
if (c instanceof List) return get((List ) c, idx);
Iterator it = c.iterator();
for (int i = 0; i < idx; i++) if (it.hasNext()) it.next(); else return null;
return it.hasNext() ? it.next() : null;
}
static FileOutputStream newFileOutputStream(File path) throws IOException {
return newFileOutputStream(path.getPath());
}
static FileOutputStream newFileOutputStream(String path) throws IOException {
return newFileOutputStream(path, false);
}
static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
FileOutputStream f = new // Line break for ancient translator
FileOutputStream(path, append);
callJavaX("registerIO", f, path, true);
return f;
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
static String struct(Object o) {
return structure(o);
}
static String struct(Object o, structure_Data data) {
return structure(o, data);
}
static void setOpt_raw(Object o, String field, Object value) {
if (o == null) return;
if (o instanceof Class) setOpt_raw((Class) o, field, value);
else try {
Field f = setOpt_raw_findField(o.getClass(), field);
if (f != null)
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void setOpt_raw(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = setOpt_raw_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_raw_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Field setOpt_raw_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Class getOuterClass(Class c) { try {
String s = c.getName();
int i = s.lastIndexOf('$');
return Class.forName(substring(s, 0, i));
} catch (Exception __e) { throw rethrow(__e); } }
static String shortenClassName(String name) {
if (name == null) return null;
int i = lastIndexOf(name, "$");
if (i < 0) i = lastIndexOf(name, ".");
return i < 0 ? name : substring(name, i+1);
}
static List _registerWeakMap_preList;
static A _registerWeakMap(A map) {
if (javax() == null) {
// We're in class init
if (_registerWeakMap_preList == null) _registerWeakMap_preList = synchroList();
_registerWeakMap_preList.add(map);
return map;
}
try {
call(javax(), "_registerWeakMap", map);
} catch (Throwable e) {
printException(e);
print("Upgrade JavaX!!");
}
return map;
}
static void _onLoad_registerWeakMap() {
assertNotNull(javax());
if (_registerWeakMap_preList == null) return;
for (Object o : _registerWeakMap_preList)
_registerWeakMap(o);
_registerWeakMap_preList = null;
}
static void swingNowOrLater(Runnable r) {
if (isAWTThread())
r.run();
else
swingLater(r);
}
static String sendToThisVM_newThread(String s, Object... args) {
final String _s = format(s, args);
try {
return (String) evalInNewThread(new Object() { Object get() { try { return
callStaticAnswerMethod(getJavaX(), _s)
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callStaticAnswerMethod(getJavaX(), _s)"; }});
} catch (Throwable e) {
e = getInnerException(e);
printStackTrace(e);
return str(e);
}
}
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 = 1; //60; // seconds
static ThreadLocal loadPage_silent = new ThreadLocal();
static volatile int loadPage_forcedTimeout; // ms
public static String loadPageSilently(String url) { try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (Exception __e) { throw rethrow(__e); } }
public static String loadPageSilently(URL url) { try {
IOException e = null;
for (int tries = 0; tries < loadPage_retries; tries++)
try {
URLConnection con = loadPage_openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPageThroughProxy_enabled) {
print("Trying proxy because of: " + e);
try {
return loadPageThroughProxy(str(url));
} catch (Throwable e2) {
print(" " + exceptionToStringShort(e2));
}
} else if (loadPage_debug)
print(e);
sleepSeconds(1);
}
throw e;
} catch (Exception __e) { throw rethrow(__e); } }
static String loadPage_preprocess(String url) {
if (url.startsWith("tb/")) // don't think we use this anymore
url = tb_mainServer() + "/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
public static String loadPage(String url) { try {
url = loadPage_preprocess(url);
if (!isTrue(loadPage_silent.get()))
print("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (Exception __e) { throw rethrow(__e); } }
public static String loadPage(URL url) {
print("Loading: " + hideCredentials(url.toExternalForm()));
return loadPageSilently(url);
}
static String loadPage(URLConnection con, URL url) throws IOException {
return loadPage(con, url, true);
}
static String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
if (addHeaders) try {
if (!loadPage_anonymous)
setHeaders(con);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
con.setRequestProperty("X-No-Cookies", "1");
} catch (Throwable e) {} // fails if within doPost
String contentType = con.getContentType();
if (contentType == null) {
printStruct("Headers: ", con.getHeaderFields());
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();
try {
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();
} finally { in.close(); }
}
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");
}
static URLConnection loadPage_openConnection(URL url) {
URLConnection con = openConnection(url);
if (loadPage_forcedTimeout != 0)
setURLConnectionTimeouts(con, loadPage_forcedTimeout);
return con;
}
static File javaxCachesDir_dir; // can be set to work on different base dir
static File javaxCachesDir() {
return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
static A popFirst(List l) {
if (empty(l)) return null;
A a = first(l);
l.remove(0);
return a;
}
static boolean endsWithLetter(String s) {
return nempty(s) && isLetter(last(s));
}
static String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static List javaTokC(String s) {
if (s == null) return null;
int l = s.length();
ArrayList tok = new ArrayList();
int i = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(quickSubstring(s, i, j));
i = j;
}
return tok;
}
static A assertEquals(Object x, A y) {
return assertEquals(null, x, y);
}
static A assertEquals(String msg, Object x, A y) {
if (!(x == null ? y == null : x.equals(y)))
throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
return y;
}
// 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 Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static Class getClass(Object realm, String name) { try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) { throw rethrow(__e); } }
static WeakHashMap> callOpt_noArgs_cache = new WeakHashMap();
static Object callOpt_noArgs(Object o, String method) { try {
if (o == null) return null;
if (o instanceof Class)
return callOpt(o, method); // not optimized
Class c = o.getClass();
HashMap map;
synchronized(callOpt_noArgs_cache) {
map = callOpt_noArgs_cache.get(c);
if (map == null)
map = callOpt_noArgs_makeCache(c);
}
Method m = map.get(method);
return m != null ? m.invoke(o) : null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap callOpt_noArgs_makeCache(Class c) {
HashMap map = new HashMap();
Class _c = c;
do {
for (Method m : c.getDeclaredMethods())
if (m.getParameterTypes().length == 0) {
m.setAccessible(true);
String name = m.getName();
if (!map.containsKey(name))
map.put(name, m);
}
_c = _c.getSuperclass();
} while (_c != null);
callOpt_noArgs_cache.put(c, map);
return map;
}
static void quoteToPrintWriter(String s, PrintWriter out) {
if (s == null) { out.print("null"); return; }
out.print('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"') {
out.print('\\'); out.print(c);
} else if (c == '\r')
out.print("\\r");
else if (c == '\n')
out.print("\\n");
else
out.print(c);
}
out.print('"');
}
static A println(A a) {
return print(a);
}
static String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
public static File mkdirsFor(File file) {
return mkdirsForFile(file);
}
static void smartSet(Field f, Object o, Object value) throws Exception {
f.setAccessible(true);
// take care of common case (long to int)
if (f.getType() == int.class && value instanceof Long)
value = ((Long) value).intValue();
try {
f.set(o, value);
} catch (Exception e) {
throw e;
}
}
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 int parseHexByte(String s) {
return Integer.parseInt(s, 16);
}
static int stdcompare(Number a, Number b) {
return cmp(a, b);
}
static int stdcompare(String a, String b) {
return cmp(a, b);
}
static int stdcompare(long a, long b) {
return a < b ? -1 : a > b ? 1 : 0;
}
static int stdcompare(Object a, Object b) {
return cmp(a, b);
}
static File muricaPasswordFile() {
return new File(javaxSecretDir(), "murica/muricaPasswordFile");
}
// supports the usual quotings (', ", variable length double brackets)
static boolean isQuoted(String s) {
if (startsWith(s, "'") || startsWith(s, "\"")) return true;
return isMultilineQuoted(s);
}
static A printStruct(String prefix, A a) {
printStructure(prefix, a);
return a;
}
static A printStruct(A a) {
printStructure(a);
return a;
}
static String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
static String getString(List l, int idx) {
return (String) get(l, idx);
}
static String getString(Object o, Object key) {
if (o instanceof Map) return getString((Map) o, key);
if (key instanceof String)
return (String) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static int identityHashCode(Object o) {
return System.identityHashCode(o);
}
static boolean odd(int i) {
return (i & 1) != 0;
}
static boolean odd(long i) {
return (i & 1) != 0;
}
static int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static int cmp(String a, String b) {
return a == null ? b == null ? 0 : -1 : a.compareTo(b);
}
static int cmp(Object a, Object b) {
if (a == null) return b == null ? 0 : -1;
if (b == null) return 1;
return ((Comparable) a).compareTo(b);
}
static Object evalInNewThread(final Object f) {
final Flag flag = new Flag();
final Var var = new Var();
final Var exception = new Var();
{ Thread _t_0 = new Thread() {
public void run() { try {
try {
var.set(callF(f));
} catch (Throwable e) {
exception.set(e);
}
flag.raise();
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
flag.waitUntilUp();
if (exception.has()) throw rethrow(exception.get());
return var.get();
}
static A or(A a, A b) {
return a != null ? a : b;
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static String[] 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 void printException(Throwable e) {
printStackTrace(e);
}
static String beautifyStructure(String s) {
return structure_addTokenMarkers(s);
}
public static File mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) // is null if file is in current dir
dir.mkdirs();
return file;
}
static Object callJavaX(String method, Object... args) {
return callOpt(getJavaX(), method, args);
}
static File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
static int lastIndexOf(String a, String b) {
return a == null || b == null ? -1 : a.lastIndexOf(b);
}
static Field findField2(Object o, String field) {
if (o instanceof Class) return findField2_findStaticField((Class) o, field);
return findField2_findField(o.getClass(), field);
}
static Field findField2_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Field findField2_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static String struct_noStringSharing(Object o) {
structure_Data d = new structure_Data();
d.noStringSharing = true;
return structure(o, d);
}
static String getComputerID_quick() {
return computerID();
}
static URLConnection setURLConnectionTimeouts(URLConnection con, int timeout) {
con.setConnectTimeout(timeout);
con.setReadTimeout(timeout);
if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
print("Warning: Timeouts not set by JDK.");
return con;
}
static byte[] boolArrayToBytes(boolean[] a) {
byte[] b = new byte[(l(a)+7)/8];
for (int i = 0; i < l(a); i++)
if (a[i])
b[i/8] |= 1 << (i & 7);
return b;
}
static String standardCredentialsUser() {
return trim(loadTextFile(new File(userHome(), ".tinybrain/username")));
}
static final boolean loadPageThroughProxy_enabled = false;
static String loadPageThroughProxy(String url) {
return null;
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static void sleepSeconds(double s) {
if (s > 0) sleep(round(s*1000));
}
static boolean isLetter(char c) {
return Character.isLetter(c);
}
static String standardCredentialsPass() {
return trim(loadTextFile(new File(userHome(), ".tinybrain/userpass")));
}
static File javaxSecretDir_dir; // can be set to work on different base dir
static File javaxSecretDir() {
return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
}
static volatile boolean sleep_noSleep;
static void sleep(long ms) {
ping();
if (ms < 0) return;
// allow spin locks
if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) { throw new RuntimeException(e); }
}
static void sleep() { try {
if (sleep_noSleep) throw fail("nosleep");
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) { throw rethrow(__e); } }
static String _computerID;
public static String computerID() { try {
if (_computerID == null) {
File file = new File(userHome(), ".tinybrain/computer-id");
_computerID = loadTextFile(file.getPath(), null);
if (_computerID == null) {
_computerID = makeRandomID(12);
saveTextFile(file.getPath(), _computerID);
}
}
return _computerID;
} catch (Exception __e) { throw rethrow(__e); } }
static String structure_addTokenMarkers(String s) {
List tok = javaTok(s);
// find references
TreeSet refs = new TreeSet();
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
if (t.startsWith("t") && isInteger(t.substring(1)))
refs.add(parseInt(t.substring(1)));
}
if (empty(refs)) return s;
// add markers
for (int i : refs) {
int idx = i*2+1;
String t = "";
if (endsWithLetterOrDigit(tok.get(idx-1))) t = " ";
tok.set(idx, t + "m" + i + " " + tok.get(idx));
}
return join(tok);
}
static boolean isMultilineQuoted(String s) {
if (!startsWith(s, "[")) return false;
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
return i < s.length() && s.charAt(i) == '[';
}
static File getProgramDir() {
return programDir();
}
static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { printStackTrace2(__e); }
return null;
}
static long round(double d) {
return Math.round(d);
}
/** 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 boolean endsWithLetterOrDigit(String s) {
return nempty(s) && isLetterOrDigit(lastCharacter(s));
}
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 File programDir_mine; // set this to relocate program's data
static File programDir() {
return programDir(getProgramID());
}
static File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetID(snippetID));
if (me) {
String c = caseID();
if (nempty(c)) dir = newFile(dir, c);
}
return dir;
}
static List beginCriticalAction_inFlight = synchroList();
static class CriticalAction {
String description;
CriticalAction() {}
CriticalAction(String description) {
this.description = description;}
void done() {
beginCriticalAction_inFlight.remove(this);
}
}
static CriticalAction beginCriticalAction(String description) {
ping();
CriticalAction c = new CriticalAction(description);
beginCriticalAction_inFlight.add(c);
return c;
}
static void cleanMeUp_beginCriticalAction() {
int n = 0;
while (nempty(beginCriticalAction_inFlight)) {
int m = l(beginCriticalAction_inFlight);
if (m != n) {
n = m;
try {
print("Waiting for " + n(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
} catch (Throwable __e) { printStackTrace2(__e); }
}
sleepInCleanUp(10);
}
}
static boolean isLetterOrDigit(char c) {
return Character.isLetterOrDigit(c);
}
static File javaxDataDir_dir; // can be set to work on different base dir
static File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static volatile String caseID_caseID;
static String caseID() { return caseID_caseID; }
static void caseID(String id) {
caseID_caseID = id;
}
public static void copyFile(File src, File dest) { try {
mkdirsForFile(dest);
FileInputStream inputStream = new FileInputStream(src.getPath());
FileOutputStream outputStream = newFileOutputStream(dest.getPath());
try {
copyStream(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
} catch (Exception __e) { throw rethrow(__e); } }
static boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b)) return false;
return parseSnippetID(a) == parseSnippetID(b);
}
static char lastCharacter(String s) {
return empty(s) ? 0 : s.charAt(l(s)-1);
}
static String n(long l, String name) {
return l + " " + trim(l == 1 ? singular(name) : getPlural(name));
}
static String n(Collection l, String name) {
return n(l(l), name);
}
static String n(Map m, String name) {
return n(l(m), name);
}
static String n(Object[] a, String name) {
return n(l(a), name);
}
static void sleepInCleanUp(long ms) { try {
if (ms < 0) return;
Thread.sleep(ms);
} catch (Exception __e) { throw rethrow(__e); } }
static List collect(Collection c, String field) {
return collectField(c, field);
}
static List collect(String field, Collection c) {
return collectField(c, field);
}
static void copyStream(InputStream in, OutputStream out) { try {
byte[] buf = new byte[65536];
while (true) {
int n = in.read(buf);
if (n <= 0) return;
out.write(buf, 0, n);
}
} catch (Exception __e) { throw rethrow(__e); } }
static List getPlural_specials = ll("sheep", "fish");
static String getPlural(String s) {
if (containsIgnoreCase(getPlural_specials, s)) return s;
if (ewic(s, "y")) return dropSuffixIgnoreCase("y", s) + "ies";
if (ewic(s, "ss")) return s + "es";
if (ewic(s, "s")) return s;
return s + "s";
}
static ArrayList list(A[] a) {
return asList(a);
}
static ArrayList list(int[] a) {
return asList(a);
}
static ArrayList list(Set s) {
return asList(s);
}
static Map singular_specials = litmap(
"children", "child", "images", "image", "chess", "chess");
static Set singular_specials2 = litset("time", "machine");
static String singular(String s) {
if (s == null) return null;
{ String _a_173 = singular_specials.get(s); if (!empty(_a_173)) return _a_173; }
{ String _a_174 = hippoSingulars().get(lower(s)); if (!empty(_a_174)) return _a_174; }
if (singular_specials2.contains(dropSuffix("s", s)))
return dropSuffix("s", s);
if (s.endsWith("ness")) return s;
if (s.endsWith("ges")) return dropSuffix("s", s);
if (endsWith(s, "bases")) return dropLast(s);
s = dropSuffix("es", s);
s = dropSuffix("s", s);
return s;
}
static List collectField(Collection c, String field) {
List l = new ArrayList();
for (Object a : c)
l.add(getOpt(a, field));
return l;
}
static String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[a.length-n];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static List dropLast(List l) {
return subList(l, 0, l(l)-1);
}
static List dropLast(int n, List l) {
return subList(l, 0, l(l)-n);
}
static List dropLast(Iterable l) {
return dropLast(asList(l));
}
static String dropLast(String s) {
return substring(s, 0, l(s)-1);
}
static String dropLast(String s, int n) {
return substring(s, 0, l(s)-n);
}
static HashSet litset(A... items) {
return lithashset(items);
}
static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
static String dropSuffixIgnoreCase(String suffix, String s) {
return ewic(s, suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static boolean containsIgnoreCase(List l, String s) {
for (String x : l)
if (eqic(x, s))
return true;
return false;
}
static boolean containsIgnoreCase(String[] l, String s) {
for (String x : l)
if (eqic(x, s))
return true;
return false;
}
static boolean containsIgnoreCase(String s, char c) {
return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}
static boolean containsIgnoreCase(String a, String b) {
return indexOfIgnoreCase(a, b) >= 0;
}
static String lower(String s) {
return s == null ? null : s.toLowerCase();
}
static char lower(char c) {
return Character.toLowerCase(c);
}
static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static Map hippoSingulars() {
return pairsToMap((List>) scanStructureLog("#1011041", "singulars"));
}
static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
static boolean endsWithIgnoreCase(String a, String b) {
return a != null && l(a) >= l(b) && a.regionMatches(true, l(a)-l(b), b, 0, l(b));
}
static List scanStructureLog(String progID, String fileName) {
return scanStructureLog(getProgramFile(progID, fileName));
}
static List scanStructureLog(String fileName) {
return scanStructureLog(getProgramFile(fileName));
}
static List scanStructureLog(File file) {
List l = new ArrayList();
for (String s : scanLog(file)) try {
l.add(unstructure(s));
} catch (Throwable __e) { printStackTrace2(__e); }
return l;
}
static HashMap pairsToMap(Collection extends Pair > l) {
HashMap map = new HashMap();
if (l != null) for (Pair p : l)
map.put(p.a, p.b);
return map;
}
static char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s)-1);
}
static List scanLog(String progID, String fileName) {
return scanLog(getProgramFile(progID, fileName));
}
static List scanLog(String fileName) {
return scanLog(getProgramFile(fileName));
}
static List scanLog(File file) {
List l = new ArrayList();
for (String s : toLines(file))
if (isProperlyQuoted(s))
l.add(unquote(s));
return l;
}
static boolean isProperlyQuoted(String s) {
return s.length() >= 2
&& s.startsWith("\"")
&& s.endsWith("\"")
&& (!s.endsWith("\\\"") || s.endsWith("\\\\\""));
}
static List toLines(File f) {
return toLines(loadTextFile(f));
}
public static List toLines(String s) {
List lines = new ArrayList();
if (s == null) return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start) lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
private static int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static class BetterLabel extends JLabel {
BetterLabel() {
componentPopupMenu(this, new Object() { void get(JPopupMenu menu) { try {
addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(getText());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(getText());"; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(get..."; }});
}
BetterLabel(String text) {
this();
setText(text);
}
public void setText(String text) {
super.setText(text);
setToolTipText(text);
}
}
static abstract class F0 {
abstract A get();
}
static abstract class F1 {
abstract B get(A a);
}
static interface Producer {
public A next();
}
static ThreadLocal DynamicObject_loading = new ThreadLocal();
static class DynamicObject {
String className; // just the name, without the "main$"
LinkedHashMap fieldValues = new LinkedHashMap();
DynamicObject() {}
// className = just the name, without the "main$"
DynamicObject(String className) {
this.className = className;}
}
/** this class is fully thread-safe */
static class Flag {
private boolean up;
/** returns true if flag was down before */
public synchronized boolean raise() {
if (!up) {
up = true;
notifyAll();
return true;
} else
return false;
}
public synchronized void waitUntilUp() {
while (!up) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void waitUntilUp(long timeout) {
if (!up) {
try {
wait(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized boolean isUp() {
return up;
}
public String toString() {
return isUp() ? "up" : "down";
}
// currently does a semi-active wait with latency = 50 ms
public void waitForThisOr(Flag otherFlag) { try {
while (!isUp() && !otherFlag.isUp())
Thread.sleep(50);
} catch (Exception __e) { throw rethrow(__e); } }
}
static class Pair {
A a;
B b;
Pair() {}
Pair(A a, B b) {
this.b = b;
this.a = a;}
public int hashCode() {
return hashCodeFor(a) + 2*hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Pair)) return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
public String toString() {
return "<" + a + ", " + b + ">";
}
}
static class Var implements IVar {
A v; // you can access this directly if you use one thread
Var() {}
Var(A v) {
this.v = v;}
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() { return v; }
public synchronized boolean has() { return v != null; }
public synchronized void clear() { v = null; }
public String toString() { return str(get()); }
}
static class ProgramScan {
static int threads = isWindows() ? 500 : 10;
static int timeout = 5000; // hmm...
static String ip = "127.0.0.1";
// This range is not used anymore anyway
static int quickScanFrom = 10000, quickScanTo = 10999;
static int maxNumberOfVMs_android = 4; // Android will always only have one if we don't screw up
static int maxNumberOfVMs_nonAndroid = 50; // 100;
static int maxNumberOfVMs;
static boolean verbose;
static class Program {
int port;
String helloString;
Program(int port, String helloString) {
this.helloString = helloString;
this.port = port;}
}
static List scan() { try {
return scan(1, 65535);
} catch (Exception __e) { throw rethrow(__e); } }
static List scan(int fromPort, int toPort) {
return scan(fromPort, toPort, new int[0]);
}
static List scan(int fromPort, int toPort, int[] preferredPorts) { try {
Set preferredPortsSet = new HashSet(asList(preferredPorts));
int scanSize = toPort-fromPort+1;
String name = toPort < 10000 ? "bot" : "program";
int threads = isWindows() ? min(500, scanSize) : min(scanSize, 10);
final ExecutorService es = Executors.newFixedThreadPool(threads);
if (verbose) print(firstToUpper(name) + "-scanning " + ip + " with timeout " + timeout + " ms in " + threads + " threads.");
startTiming();
List < Future < Program > > futures = new ArrayList();
List ports = new ArrayList();
for (int port : preferredPorts) {
futures.add(checkPort(es, ip, port, timeout));
ports.add(port);
}
for (int port = fromPort; port <= toPort; port++)
if (!preferredPortsSet.contains(port) && !forbiddenPort(port)) {
futures.add(checkPort(es, ip, port, timeout));
ports.add(port);
}
es.shutdown();
List programs = new ArrayList();
long time = now();
int i = 0;
for (final Future f : futures) {
if (verbose) print("Waiting for port " + get(ports, i++) + " at time " + (now()-time));
Program p = f.get();
if (p != null)
programs.add(p);
}
//stopTiming("Port Scan " + scanSize + ", " + n(threads, "threads") + ": ", 250);
if (verbose) print("Found " + programs.size() + " " + name + "(s) on " + ip);
return programs;
} catch (Exception __e) { throw rethrow(__e); } }
static Future checkPort(final ExecutorService es, final String ip, final int port, final int timeout) {
return es.submit(new Callable() {
@Override public Program call() {
try {
Socket socket = new Socket();
try {
socket.setSoTimeout(timeout);
socket.connect(new InetSocketAddress(ip, port), timeout);
//if (verbose) print("Connected to " + ip + ":" + port);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), "UTF-8"));
String hello = or(in.readLine(), "?");
return new Program(port, hello);
} finally {
socket.close();
}
} catch (Exception ex) {
return null;
}
}
});
}
static List quickScan() {
return scan(quickScanFrom, quickScanTo);
}
static List quickBotScan() {
return quickBotScan(new int[0]);
}
static List quickBotScan(int[] preferredPorts) {
if (maxNumberOfVMs == 0)
maxNumberOfVMs = isAndroid() ? maxNumberOfVMs_android : maxNumberOfVMs_nonAndroid;
return scan(4999, 5000+maxNumberOfVMs-1, preferredPorts);
}
}
static abstract class DialogIO {
String line;
boolean eos, loud, noClose;
abstract String readLineImpl();
abstract boolean isStillConnected();
abstract void sendLine(String line);
abstract boolean isLocalConnection();
abstract Socket getSocket();
abstract void close();
int getPort() { Socket s = getSocket(); return s == null ? 0 : s.getPort(); }
boolean helloRead;
int shortenOutputTo = 500;
String readLineNoBlock() {
String l = line;
line = null;
return l;
}
boolean waitForLine() { try {
if (line != null) return true;
//print("Readline");
line = readLineImpl();
//print("Readline done: " + line);
if (line == null) eos = true;
return line != null;
} catch (Exception __e) { throw rethrow(__e); } }
String readLine() {
waitForLine();
helloRead = true;
return readLineNoBlock();
}
String ask(String s, Object... args) {
if (loud) return askLoudly(s, args);
if (!helloRead) readLine();
if (args.length != 0) s = format3(s, args);
sendLine(s);
return readLine();
}
String askLoudly(String s, Object... args) {
if (!helloRead) readLine();
if (args.length != 0) s = format3(s, args);
print("> " + shorten(s, shortenOutputTo));
sendLine(s);
String answer = readLine();
print("< " + shorten(answer, shortenOutputTo));
return answer;
}
void pushback(String l) {
if (line != null)
throw fail();
line = l;
helloRead = false;
}
}
static abstract class DialogHandler {
abstract void run(DialogIO io);
}
static class Matches {
String[] m;
Matches() {}
Matches(String... m) {
this.m = m;}
String get(int i) { return i < m.length ? m[i] : null; }
String unq(int i) { return unquote(get(i)); }
String fsi(int i) { return formatSnippetID(unq(i)); }
String fsi() { return fsi(0); }
String tlc(int i) { return unq(i).toLowerCase(); }
boolean bool(int i) { return "true".equals(unq(i)); }
String rest() { return m[m.length-1]; } // for matchStart
int psi(int i) { return Integer.parseInt(unq(i)); }
}
static String copyTextToClipboard(String text) {
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
return text;
}
static A setToolTipText(final A c, final Object toolTip) {
if (c == null) return null;
{ swing(new Runnable() { public void run() { try {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ..."; }}); }
return c;
}
static int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
static void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static void addMenuItem(JMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(JMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static String fsi(String id) {
return formatSnippetID(id);
}
static boolean equals(Object a, Object b) {
return a == null ? b == null : a.equals(b);
}
static String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new Object() { Object get() { try { return c.getText() ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "c.getText()"; }});
}
static String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new Object() { Object get() { try { return l.getText() ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "l.getText()"; }});
}
// returns the contents of text field for editable combo box
static String getText(final JComboBox cb) {
if (cb.isEditable())
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
static long stopTiming_defaultMin = 10;
static long startTiming_startTime;
static void startTiming() {
startTiming_startTime = now();
}
static void stopTiming() {
stopTiming(null);
}
static void stopTiming(String text) {
stopTiming(text, stopTiming_defaultMin);
}
static void stopTiming(String text, long minToPrint) {
long time = now()-startTiming_startTime;
if (time >= minToPrint) {
text = or2(text, "Time: ");
print(text + time + " ms");
}
}
static boolean setText_opt = true; // optimize by calling getText first
static A setText(A c, Object text) {
setText((Object) c, text);
return c;
}
static A setText(final A c, Object text) {
// only for editable combo boxes at this point
final String s = strUnnull(text);
{ swing(new Runnable() { public void run() { try {
c.getEditor().setItem(s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.getEditor().setItem(s);"; }}); }
return c;
}
static void setText(JLabel c, Object text) {
setText((Object) c, text);
}
static JButton setText(JButton c, Object text) {
setText((Object) c, text);
return c;
}
static A setText(final A c, Object text) {
if (c == null) return null;
final String s = strUnnull(text);
swingAndWait(new Runnable() { public void run() { try {
if (!setText_opt || neq(callOpt(c, "getText"), s))
call(c, "setText", s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n call(c, \"setText\", s);"; }});
return c;
}
static String firstToUpper(String s) {
if (empty(s)) return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
static String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static String strUnnull(Object o) {
return o == null ? "" : str(o);
}
static interface IVar {
void set(A a);
A get();
boolean has();
void clear();
}
}