p) {
return p == null ? null : p.a;
}
public static List buttonsInGroup(ButtonGroup g) {
if (g == null)
return ll();
return asList(g.getElements());
}
public static boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
public static boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
public static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
public static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
public static boolean containsNewLines(String s) {
return containsNewLine(s);
}
public static String jlabel_textAsHTML_center(String text) {
return "" + replace(htmlencode(text), "\n", "
") + "
";
}
public static Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() {
public void run() {
try {
_inheritThreadInfo(info);
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_inheritThreadInfo(info); callF(r);";
}
};
}
public static Map loadFont_cached_cache = new HashMap();
public static synchronized Font loadFont_cached(String snippetID) {
try {
snippetID = formatSnippetID(snippetID);
Font f = loadFont_cached_cache.get(snippetID);
if (f == null)
loadFont_cached_cache.put(snippetID, f = loadFont(snippetID, 12f));
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static synchronized Font loadFont_cached(String snippetID, float size) {
try {
return loadFont_cached(snippetID).deriveFont(size);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static int iround(double d) {
return (int) Math.round(d);
}
public static int iround(Number n) {
return iround(toDouble(n));
}
public static float getSwingFontScale() {
return or((Float) vm_generalMap_get("swingFontScale_value"), 1f);
}
public static boolean even(int i) {
return (i & 1) == 0;
}
public static boolean even(long i) {
return (i & 1) == 0;
}
public static int imageIcon_cacheSize = 10;
public static boolean imageIcon_verbose;
public static Map imageIcon_cache;
public static Lock imageIcon_lock = lock();
public static ThreadLocal imageIcon_fixGIF = new ThreadLocal();
public static ImageIcon imageIcon(String imageID) {
try {
if (imageID == null)
return null;
Lock __615 = imageIcon_lock;
lock(__615);
try {
if (imageIcon_cache == null)
imageIcon_cache = new MRUCache(imageIcon_cacheSize);
imageID = fsI(imageID);
ImageIcon ii = imageIcon_cache.get(imageID);
if (ii == null) {
if (imageIcon_verbose)
print("Loading image icon: " + imageID);
File f = loadBinarySnippet(imageID);
Boolean b = imageIcon_fixGIF.get();
if (!isFalse(b))
ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
else
ii = new ImageIcon(f.toURI().toURL());
} else
imageIcon_cache.remove(imageID);
imageIcon_cache.put(imageID, ii);
return ii;
} finally {
unlock(__615);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ImageIcon imageIcon(Image img) {
return new ImageIcon(img);
}
public static ImageIcon imageIcon(RGBImage img) {
return imageIcon(img.getBufferedImage());
}
public static String or2(String a, String b) {
return nempty(a) ? a : b;
}
public static String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
public static void swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
timer.setRepeats(false);
timer.start();
}
public static void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
public static void standardTitlePopupMenu(final JFrame frame) {
if (isSubstanceLAF())
titlePopupMenu(frame, new VF1() {
public void get(JPopupMenu menu) {
try {
boolean alwaysOnTop = frame.isAlwaysOnTop();
menu.add(jmenuItem("Restart Program", "restart"));
menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram"));
menu.add(jmenuItem("Show Console", "showConsole"));
menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() {
public void run() {
try {
toggleAlwaysOnTop(frame);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "toggleAlwaysOnTop(frame)";
}
}));
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(\"Restar...";
}
});
}
public static A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), c);
return c;
}
public static JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JScrollPane(c);";
}
});
}
public static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
public static JLabel jlabel() {
return jlabel(" ");
}
public static Rectangle screenRectangle() {
return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
}
public static Random random_random = new Random();
public static int random(int n) {
return n <= 0 ? 0 : random_random.nextInt(n);
}
public static double random(double max) {
return random() * max;
}
public static double random() {
return random_random.nextInt(100001) / 100000.0;
}
public static double random(double min, double max) {
return min + random() * (max - min);
}
public static int random(int min, int max) {
return min + random(max - min);
}
public static A random(List l) {
return oneOf(l);
}
public static A random(Collection c) {
if (c instanceof List)
return random((List) c);
int i = random(l(c));
return collectionGet(c, i);
}
public static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
public static void autoVMExit() {
call(getJavaX(), "autoVMExit");
}
public static Object interceptPrintInThisThread(Object f) {
Object old = print_byThread().get();
print_byThread().set(f);
return old;
}
public static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
public static Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
public static Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
public static String struct_noStringSharing(Object o) {
structure_Data d = new structure_Data();
d.noStringSharing = true;
return structure(o, d);
}
public static A pnl(A l) {
printNumberedLines(l);
return l;
}
public static void pnl(Map map) {
printNumberedLines(map);
}
public static void pnl(Object[] a) {
printNumberedLines(a);
}
public static void pnl(String s) {
printNumberedLines(lines(s));
}
public static String sfu(Object o) {
return structureForUser(o);
}
public static Object unstructure(String text) {
return unstructure(text, false);
}
public static Object unstructure(String text, final boolean allDynamic) {
return unstructure(text, allDynamic, null);
}
public static int structure_internStringsLongerThan = 50;
public static int unstructure_unquoteBufSize = 100;
public static int unstructure_tokrefs;
public abstract static class unstructure_Receiver {
public abstract void set(Object o);
}
public static Object unstructure(String text, boolean allDynamic, Object classFinder) {
if (text == null)
return null;
return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
}
public static Object unstructure_reader(BufferedReader reader) {
return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
}
public static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object _classFinder) {
final boolean debug = unstructure_debug;
final class X {
public int i = -1;
public final Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();
public HashMap refs = new HashMap();
public HashMap tokrefs = new HashMap();
public HashSet concepts = new HashSet();
public HashMap classesMap = new HashMap();
public List stack = new ArrayList();
public String curT;
public char[] unquoteBuf = new char[unstructure_unquoteBufSize];
public String unquote(String s) {
return unquoteUsingCharArray(s, unquoteBuf);
}
public String t() {
return curT;
}
public String tpp() {
String t = curT;
consume();
return t;
}
public 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;
final int tokIndex = i;
parse_inner(refID, tokIndex, new unstructure_Receiver() {
public void set(Object o) {
if (_refID != 0)
refs.put(_refID, o);
if (o != null)
tokrefs.put(tokIndex, o);
out.set(o);
}
});
}
public void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) {
String t = t();
Class c = classesMap.get(t);
if (c == null) {
if (t.startsWith("\"")) {
String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
out.set(s);
return;
}
if (t.startsWith("'")) {
out.set(unquoteCharacter(tpp()));
return;
}
if (t.equals("bigint")) {
out.set(parseBigInt());
return;
}
if (t.equals("d")) {
out.set(parseDouble());
return;
}
if (t.equals("fl")) {
out.set(parseFloat());
return;
}
if (t.equals("sh")) {
consume();
t = tpp();
if (t.equals("-")) {
t = tpp();
out.set((short) (-parseInt(t)));
return;
}
out.set((short) parseInt(t));
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("false") || t.equals("f")) {
consume();
out.set(false);
return;
}
if (t.equals("true") || t.equals("t")) {
consume();
out.set(true);
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("File")) {
consume();
File f = new File(unquote(tpp()));
out.set(f);
return;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
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("lhs")) {
parseLinkedHashSet(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("sync")) {
consume();
if (t().equals("tm")) {
consume();
{
parseMap(synchronizedTreeMap(), out);
return;
}
}
if (t().equals("[")) {
parseList(synchroList(), out);
return;
}
{
parseMap(synchronizedMap(), out);
return;
}
}
if (t.equals("{")) {
parseMap(out);
return;
}
if (t.equals("[")) {
this.parseList(new ArrayList(), out);
return;
}
if (t.equals("bitset")) {
parseBitSet(out);
return;
}
if (t.equals("array") || t.equals("intarray")) {
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);
consume();
String className, fullClassName;
if (eq(t(), ".")) {
consume();
className = fullClassName = t + "." + assertIdentifier(tpp());
} else {
className = t;
fullClassName = "main$" + t;
}
if (c == null) {
if (allDynamic)
c = null;
else
c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
if (c != null)
classesMap.put(className, c);
}
boolean hasBracket = eq(t(), "(");
if (hasBracket)
consume();
boolean hasOuter = hasBracket && eq(t(), "this$1");
DynamicObject dO = null;
Object o = null;
final String thingName = t;
if (c != null) {
o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c);
if (o instanceof DynamicObject)
dO = (DynamicObject) o;
} else {
if (concepts.contains(t) && (c = findClass("Concept")) != null)
o = dO = (DynamicObject) nuEmptyObject(c);
else
dO = new DynamicObject();
dO.className = className;
}
if (refID != 0)
refs.put(refID, o != null ? o : dO);
tokrefs.put(tokIndex, o != null ? o : dO);
final LinkedHashMap fields = new LinkedHashMap();
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());
if (!eq(tpp(), "="))
throw fail("= expected, got " + t() + " after " + quote(key) + " in object " + thingName);
stack.add(this);
parse(new unstructure_Receiver() {
public 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, ...";
}
});
} else {
objRead(o, dO, fields);
out.set(o != null ? o : dO);
}
}
public void objRead(Object o, DynamicObject dO, Map fields) {
if (o != null)
if (dO != null) {
setOptAllDyn(dO, fields);
} else {
setOptAll_pcall(o, fields);
}
else
for (String field : keys(fields)) dO.fieldValues.put(intern(field), fields.get(field));
if (o != null)
pcallOpt_noArgs(o, "_doneLoading");
}
public void parseSet(final Set set, final unstructure_Receiver out) {
this.parseList(new ArrayList(), new unstructure_Receiver() {
public void set(Object o) {
set.addAll((List) o);
out.set(set);
}
});
}
public void parseLisp(final unstructure_Receiver out) {
throw fail("class Lisp not included");
}
public 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() {
public 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 ...";
}
});
}
public void parseList(final List list, final unstructure_Receiver out) {
consume("[");
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "]")) {
consume("]");
out.set(list);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public 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(list);\r\n ...";
}
});
}
public 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() {
public 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(\"...";
}
});
}
public Object parseClass() {
consume("class");
consume("(");
String name = unquote(tpp());
consume(")");
Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass_fullName(name);
if (c != null)
return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
name = dropPrefix("main$", name);
dO.fieldValues.put("name", name);
return dO;
}
public Object parseBigInt() {
consume("bigint");
consume("(");
String val = tpp();
if (eq(val, "-"))
val = "-" + tpp();
consume(")");
return new BigInteger(val);
}
public Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tpp());
consume(")");
return Double.parseDouble(val);
}
public Object parseFloat() {
consume("fl");
String val;
if (eq(t(), "(")) {
consume("(");
val = unquote(tpp());
consume(")");
} else {
val = unquote(tpp());
}
return Float.parseFloat(val);
}
public void parseHashSet(unstructure_Receiver out) {
consume("hashset");
parseSet(new HashSet(), out);
}
public void parseLinkedHashSet(unstructure_Receiver out) {
consume("lhs");
parseSet(new LinkedHashSet(), out);
}
public void parseTreeSet(unstructure_Receiver out) {
consume("treeset");
parseSet(new TreeSet(), out);
}
public void parseMap(unstructure_Receiver out) {
parseMap(new TreeMap(), out);
}
public 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;
}
}
public void parseMap(final Map map, final unstructure_Receiver out) {
consume("{");
stack.add(new Runnable() {
public boolean v;
public Object key;
public void run() {
if (v) {
v = false;
stack.add(this);
if (!eq(tpp(), "="))
throw fail("= expected, got " + t() + " in map of size " + l(map));
parse(new unstructure_Receiver() {
public void set(Object value) {
map.put(key, value);
if (eq(t(), ","))
consume();
}
});
} else {
if (eq(t(), "}")) {
consume("}");
out.set(map);
} else {
v = true;
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
key = o;
}
});
}
}
}
});
}
public void consume() {
curT = tok.next();
++i;
}
public void consume(String s) {
if (!eq(t(), s)) {
throw fail(quote(s) + " expected, got " + quote(t()));
}
consume();
}
public void parse_x(unstructure_Receiver out) {
consume();
parse(out);
while (nempty(stack)) popLast(stack).run();
}
}
Boolean b = DynamicObject_loading.get();
DynamicObject_loading.set(true);
try {
final Var v = new Var();
X x = new X();
x.parse_x(new unstructure_Receiver() {
public void set(Object o) {
v.set(o);
}
});
unstructure_tokrefs = x.tokrefs.size();
return v.get();
} finally {
DynamicObject_loading.set(b);
}
}
public static boolean unstructure_debug;
public static String charToString(char c) {
return String.valueOf(c);
}
public static String charToString(int c) {
return String.valueOf((char) c);
}
public static Object[] asArray(List l) {
return toObjectArray(l);
}
public static A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
public static boolean isMenuSeparatorIndicator(Object o) {
return eqOneOf(o, "***", "---", "===", "");
}
public static boolean isRunnableX(Object o) {
if (o == null)
return false;
if (o instanceof String)
return hasMethod(mc(), (String) o);
return o instanceof Runnable || hasMethod(o, "get");
}
public static boolean jmenuItem_newThreads;
public static JMenuItem jmenuItem(final String text) {
return jMenuItem(text, null);
}
public static JMenuItem jmenuItem(final String text, final Object r) {
return swing(new F0() {
public JMenuItem get() {
try {
Pair p = jmenu_autoMnemonic(text);
JMenuItem mi = new JMenuItem(p.a);
if (p.b != 0)
mi.setMnemonic(p.b);
mi.addActionListener(jmenuItem_newThreads ? actionListenerInNewThread(r) : actionListener(r));
return mi;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Pair p = jmenu_autoMnemonic(text);\r\n JMenuItem mi = new JMenuItem(...";
}
});
}
public static A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) {
if (lv != null)
bindToComponent(component, new Runnable() {
public void run() {
try {
lv.onChangeAndNow(listener);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindLiveValueListenerToComponent_debug\r\n print(\"bindLiveValueL...";
}
}, new Runnable() {
public void run() {
try {
lv.removeOnChangeListener(listener);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "lv.removeOnChangeListener(listener)";
}
});
return component;
}
public static boolean isCurlyBracketed(String s) {
return isCurlyBraced(s);
}
public static void setEnabled(final JComponent c, final boolean enable) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
c.setEnabled(enable);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.setEnabled(enable);";
}
});
}
}
public static String unCurlyBracket(String s) {
return tok_unCurlyBracket(s);
}
public static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
public static boolean isInstanceOf(Object o, Class type) {
return type.isInstance(o);
}
public static String className(Object o) {
return getClassName(o);
}
public static int preferredWidth(Component c) {
return c == null ? 0 : getPreferredSize(c).width;
}
public static Object dm_getModule(Object moduleOrID) {
if (eq(moduleOrID, ""))
return null;
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
public static AutoCloseable dm_enter(Object mod) {
return (AutoCloseable) callOpt(dm_getModule(mod), "enter");
}
public static String dm_makeModule(String moduleLibID) {
return (String) callCreator("makeModule", moduleLibID);
}
public static ArrayList emptyList() {
return new ArrayList();
}
public static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
public static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
public static ArrayList emptyList(Class c) {
return new ArrayList();
}
public static List synchroList() {
return Collections.synchronizedList(new ArrayList());
}
public static List synchroList(List l) {
return Collections.synchronizedList(l);
}
public static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
public static Throwable innerException(Throwable e) {
return getInnerException(e);
}
public static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
public static ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList(l);
}
}
public static Throwable printStackTrace(Throwable e) {
print(getStackTrace(e));
return e;
}
public static void printStackTrace() {
printStackTrace(new Throwable());
}
public static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
public static void lockOrFail(Lock lock, long timeout) {
try {
ping();
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) (lock);
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ReentrantLock fairLock() {
return new ReentrantLock(true);
}
public static A findConceptWhere(Class c, Object... params) {
return findConceptWhere(mainConcepts, c, params);
}
public static A findConceptWhere(Concepts concepts, Class c, Object... params) {
params = expandParams(c, params);
if (concepts.fieldIndices != null)
for (int i = 0; i < l(params); i += 2) {
IFieldIndex index = concepts.getFieldIndex(c, (String) params[i]);
if (index != null) {
for (A x : index.getAll(params[i + 1])) if (checkConceptFields(x, params))
return x;
return null;
}
}
for (A x : concepts.list(c)) if (checkConceptFields(x, params))
return x;
return null;
}
public static Concept findConceptWhere(Concepts concepts, String c, Object... params) {
for (Concept x : concepts.list(c)) if (checkConceptFields(x, params))
return x;
return null;
}
public static A unlisted(Class c, Object... args) {
concepts_unlisted.set(true);
try {
return nuObject(c, args);
} finally {
concepts_unlisted.set(null);
}
}
public static int csetAll(Concept c, Object... values) {
return cset(c, values);
}
public static boolean isUpperCaseLetter(char c) {
return Character.isUpperCase(c);
}
public static String quoteUnlessIdentifierOrInteger(String s) {
return quoteIfNotIdentifierOrInteger(s);
}
public static void messageBox(final String msg) {
if (headless())
print(msg);
else {
swing(new Runnable() {
public void run() {
try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES...";
}
});
}
}
public static void messageBox(Throwable e) {
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
public static Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
public 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;
}
public static boolean isEditableComboBox(final JComboBox cb) {
return cb != null && swing(new F0() {
public Boolean get() {
try {
return cb.isEditable();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret cb.isEditable();";
}
});
}
public static String unnull(String s) {
return s == null ? "" : s;
}
public static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
public static List unnull(List l) {
return l == null ? emptyList() : l;
}
public static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
public static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
public static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
public static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
public static void addConceptIndex(IConceptIndex index) {
db_mainConcepts().addConceptIndex(index);
}
public static IConceptIndex simpleConceptIndex(final Runnable r) {
return new IConceptIndex() {
public void update(Concept c) {
pcallF(r);
}
public void remove(Concept c) {
pcallF(r);
}
};
}
public static String getSnippetTitle(String id) {
try {
if (id == null)
return null;
if (!isSnippetID(id))
return "?";
if (isLocalSnippetID(id))
return localSnippetTitle(id);
long parsedID = parseSnippetID(id);
String url;
if (isImageServerSnippet(parsedID))
url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery();
else if (isGeneralFileServerSnippet(parsedID))
url = "http://butter.botcompany.de:8080/files/name/" + parsedID;
else
url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies();
String title = trim(loadPageSilently(url));
if (title != null)
try {
saveTextFileIfChanged(snippetTitle_cacheFile(id), title);
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
return or(title, "?");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String getSnippetTitle(long id) {
return getSnippetTitle(fsI(id));
}
public static boolean hasBot(String searchPattern) {
DialogIO io = findBot(searchPattern);
if (io != null) {
io.close();
return true;
} else
return false;
}
public static String fsI(String id) {
return formatSnippetID(id);
}
public static String fsI(long id) {
return formatSnippetID(id);
}
public static String dropAfterSpace(String s) {
return s == null ? null : substring(s, 0, smartIndexOf(s, ' '));
}
public static boolean isOK(String s) {
s = trim(s);
return swic(s, "ok ") || eqic(s, "ok") || matchStart("ok", s);
}
public static String sendOpt(String bot, String text, Object... args) {
return sendToLocalBotOpt(bot, text, args);
}
public static boolean isMainProgram() {
return creator() == null;
}
public static void cleanKill() {
cleanKillVM();
}
public static String _userHome;
public static String userHome() {
if (_userHome == null) {
if (isAndroid())
_userHome = "/storage/sdcard0/";
else
_userHome = System.getProperty("user.home");
}
return _userHome;
}
public static File userHome(String path) {
return new File(userDir(), path);
}
public static String dbBotName(String progIDWithCase) {
return fsI_flex(progIDWithCase) + " Concepts";
}
public static String actualUserHome_value;
public static String actualUserHome() {
if (actualUserHome_value == null) {
if (isAndroid())
actualUserHome_value = "/storage/sdcard0/";
else
actualUserHome_value = System.getProperty("user.home");
}
return actualUserHome_value;
}
public static File actualUserHome(String sub) {
return newFile(new File(actualUserHome()), sub);
}
public static String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
public 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();
}
public static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
public static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
public static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
public static Android3 methodsBot2(String name, final Object receiver, final List exposedMethods) {
return methodsBot2(name, receiver, exposedMethods, null);
}
public static Android3 methodsBot2(String name, final Object receiver, final List exposedMethods, final Lock lock) {
Android3 android = new Android3();
android.greeting = name;
android.console = false;
android.responder = new Responder() {
public String answer(String s, List history) {
return exposeMethods2(receiver, s, exposedMethods, lock);
}
};
return makeBot(android);
}
public static List db_standardExposedMethods_list = ll("xlist", "xnew", "xset", "xdelete", "xget", "xclass", "xfullgrab", "xshutdown", "xchangeCount", "xcount");
public static List db_standardExposedMethods() {
return db_standardExposedMethods_list;
}
public static String singleFieldName(Class c) {
Set l = listFields(c);
if (l(l) != 1)
throw fail("No single field found in " + c + " (have " + n(l(l), "fields") + ")");
return first(l);
}
public static void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
public static A cget(Object c, String field) {
Object o = getOpt(c, field);
if (o instanceof Concept.Ref)
return (A) ((Concept.Ref) o).get();
return (A) o;
}
public static A cget(String field, Object c) {
return cget(c, field);
}
public static Object deref(Object o) {
if (o instanceof Derefable)
o = ((Derefable) o).get();
return o;
}
public static void restart() {
Object j = getJavaX();
call(j, "cleanRestart", get(j, "fullArgs"));
}
public static void duplicateThisProgram() {
nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs"))));
}
public static void showConsole() {
callOpt(get(javax(), "console"), "showConsole");
}
public static List keysList(Map map) {
return cloneListSynchronizingOn(keys(map), map);
}
public static void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null)
tl.set(l = new ArrayList());
l.add(a);
}
public static A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null)
return null;
A a = popLast(l);
if (empty(l))
tl.set(null);
return a;
}
public static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
public static WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
public static boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
public static boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
}
public static boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b))
return false;
m.m = new String[] { substring(a, 0, l(a) - l(b)) };
return true;
}
public static boolean containsNewLine(String s) {
return contains(s, '\n');
}
public static List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++) if (eq(l.get(i), a))
l.set(i, b);
return l;
}
public static String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
public static String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
public static String htmlencode(Object o) {
return htmlencode(str(o));
}
public static String htmlencode(String s) {
if (s == null)
return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&')
out.append("").append((int) c).append(';');
else
out.append(c);
}
return out.toString();
}
public static Runnable asRunnable(Object o) {
return toRunnable(o);
}
public static void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
public static Font loadFont(String snippetID) {
try {
return loadFont(snippetID, 12f);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Font loadFont(InputStream in) {
try {
return Font.createFont(Font.TRUETYPE_FONT, in);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Font loadFont(String snippetID, float fontSize) {
return loadFont(loadLibrary(snippetID), fontSize);
}
public static Font loadFont(File f, float fontSize) {
try {
return Font.createFont(Font.TRUETYPE_FONT, f).deriveFont(fontSize);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Font loadFont(InputStream in, float fontSize) {
try {
return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(fontSize);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o == null)
return 0.0;
throw fail(o);
}
public static A or(A a, A b) {
return a != null ? a : b;
}
public static A vm_generalMap_get(Object key) {
return (A) vm_generalMap().get(key);
}
public 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);
}
}
public static boolean loadBufferedImageFixingGIFs_debug;
public static ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal();
public static Image loadBufferedImageFixingGIFs(File file) {
try {
if (!file.exists())
return null;
if (!isGIF(file))
return ImageIO.read(file);
if (loadBufferedImageFixingGIFs_debug)
print("loadBufferedImageFixingGIFs" + ": checking gif");
ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
reader.setInput(ImageIO.createImageInputStream(file));
int numImages = reader.getNumImages(true);
IIOMetadata imageMetaData = reader.getImageMetadata(0);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
boolean foundBug = false;
for (int i = 0; i < numImages && !foundBug; i++) {
IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
if (Integer.parseInt(delay) == 0) {
foundBug = true;
}
break;
}
}
}
if (loadBufferedImageFixingGIFs_debug)
print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
Image image;
if (!foundBug) {
image = Toolkit.getDefaultToolkit().createImage(f2s(file));
} else {
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
{
ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
try {
ImageWriter writer = ImageIO.getImageWriter(reader);
writer.setOutput(ios);
writer.prepareWriteSequence(null);
for (int i = 0; i < numImages; i++) {
BufferedImage frameIn = reader.read(i);
IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
if (Integer.parseInt(delay) == 0) {
((IIOMetadataNode) node).setAttribute("delayTime", "10");
}
break;
}
}
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
IIOImage frameOut = new IIOImage(frameIn, null, metadata);
writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
}
writer.endWriteSequence();
} finally {
_close(ios);
}
}
byte[] data = baoStream.toByteArray();
setVar(loadBufferedImageFixingGIFs_output.get(), data);
if (loadBufferedImageFixingGIFs_debug)
print("Data size: " + l(data));
image = Toolkit.getDefaultToolkit().createImage(data);
}
return image;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public 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));
}
public static int toInt(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
public static boolean isSubstanceLAF() {
return substanceLookAndFeelEnabled();
}
public static boolean titlePopupMenu(final Component c, final Object menuMaker) {
JComponent titleBar = getTitlePaneComponent(getPossiblyInternalFrame(c));
if (titleBar == null) {
print("Can't add title right click!");
return false;
} else {
componentPopupMenu(titleBar, menuMaker);
return true;
}
}
public static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
final JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked);
addActionListener(mi, new Runnable() {
public void run() {
try {
callF(r, isChecked(mi));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r, isChecked(mi))";
}
});
return mi;
}
public static void toggleAlwaysOnTop(JFrame frame) {
frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
}
public static JMenuItem jMenuItem(final String text) {
return jmenuItem(text);
}
public static JMenuItem jMenuItem(String text, Object r) {
return jmenuItem(text, r);
}
public static void shootWindowGUI_external(JFrame frame) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame);
}
public static void shootWindowGUI_external(final JFrame frame, int delay) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame, delay);
}
public static A oneOf(List l) {
return l.isEmpty() ? null : l.get(new Random().nextInt(l.size()));
}
public static char oneOf(String s) {
return empty(s) ? '?' : s.charAt(random(l(s)));
}
public static String oneOf(String... l) {
return oneOf(asList(l));
}
public static A collectionGet(Collection c, int idx) {
if (c == null || idx < 0 || idx >= l(c))
return null;
if (c instanceof List)
return listGet((List) c, idx);
Iterator it = c.iterator();
for (int i = 0; i < idx; i++) if (it.hasNext())
it.next();
else
return null;
return it.hasNext() ? it.next() : null;
}
public static Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
public static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
public 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);
}
}
public static String classNameToVM(String name) {
return name.replace(".", "$");
}
public static List printNumberedLines(List l) {
printNumberedLines((Collection) l);
return l;
}
public static void printNumberedLines(Map map) {
printNumberedLines(mapToLines(map));
}
public static A printNumberedLines(A l) {
int i = 0;
if (l != null)
for (Object a : l) print((++i) + ". " + str(a));
return l;
}
public static void printNumberedLines(Object[] l) {
printNumberedLines(asList(l));
}
public static void printNumberedLines(Object o) {
printNumberedLines(lines(str(o)));
}
public static String lines(Collection lines) {
return fromLines(lines);
}
public static List lines(String s) {
return toLines(s);
}
public static String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
public static Producer javaTokC_noMLS_iterator(final String s) {
return javaTokC_noMLS_iterator(s, 0);
}
public static Producer javaTokC_noMLS_iterator(final String s, final int startIndex) {
return new Producer() {
public final int l = s.length();
public int i = startIndex;
public String next() {
if (i >= l)
return null;
int j = i;
char c, d;
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);
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') {
++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));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else
++j;
String t = quickSubstring(s, i, j);
i = j;
return t;
}
};
}
public static Producer javaTokC_noMLS_onReader(final BufferedReader r) {
final class X implements Producer {
public StringBuilder buf = new StringBuilder();
public char c, d, e = 'x';
public X() {
nc();
nc();
nc();
}
public void nc() {
try {
c = d;
d = e;
if (e == '\0')
return;
int i = r.read();
e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void ncSave() {
if (c != '\0') {
buf.append(c);
nc();
}
}
public String next() {
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;
if (c == '\'' || c == '"') {
char opener = c;
ncSave();
while (c != '\0') {
if (c == opener || c == '\n') {
ncSave();
break;
} else if (c == '\\') {
ncSave();
ncSave();
} else
ncSave();
}
} else if (Character.isJavaIdentifierStart(c))
do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\'');
else if (Character.isDigit(c)) {
do ncSave(); while (Character.isDigit(c));
if (c == 'L')
ncSave();
} else
ncSave();
String t = buf.toString();
buf.setLength(0);
return t;
}
}
return new X();
}
public static String unquoteUsingCharArray(String s, char[] buf) {
if (s == null)
return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i + 1, s.length() - i - 1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
if (l > buf.length)
return unquote(s);
int n = 0;
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
buf[n++] = (char) Integer.parseInt(code, 8);
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\'':
ch = '\'';
break;
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
char[] x = Character.toChars(code);
int lx = x.length;
for (int j = 0; j < lx; j++) buf[n++] = x[j];
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
buf[n++] = ch;
}
return new String(buf, 0, n);
}
}
return s;
}
public 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;
}
public static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
public static int parseInt(char c) {
return Integer.parseInt(str(c));
}
public static String internIfLongerThan(String s, int l) {
return s == null ? null : l(s) >= l ? intern(s) : s;
}
public static String unquote(String s) {
if (s == null)
return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i + 1, s.length() - i - 1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
StringBuilder sb = new StringBuilder(l - 1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\'':
ch = '\'';
break;
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;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s;
}
public 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);
}
public static double parseDouble(String s) {
return Double.parseDouble(s);
}
public static float parseFloat(String s) {
return Float.parseFloat(s);
}
public static boolean isLongConstant(String s) {
if (!s.endsWith("L"))
return false;
s = s.substring(0, l(s) - 1);
return isInteger(s);
}
public static boolean isInteger(String s) {
int n = l(s);
if (n == 0)
return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n)
return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9')
return false;
++i;
}
return true;
}
public static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
public static SortedMap synchronizedTreeMap() {
return synchroTreeMap();
}
public static List parseList(String s) {
return (List) safeUnstructure(s);
}
public static Map synchronizedMap() {
return synchroMap();
}
public static Map synchronizedMap(Map map) {
return synchroMap(map);
}
public static byte[] hexToBytes(String s) {
if (odd(l(s)))
throw fail("Hex string has odd length: " + quote(shorten(10, s)));
int n = l(s) / 2;
byte[] bytes = new byte[n];
for (int i = 0; i < n; i++) {
int a = parseHexChar(s.charAt(i * 2));
int b = parseHexChar(s.charAt(i * 2 + 1));
if (a < 0 || b < 0)
throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s));
bytes[i] = (byte) ((a << 4) | b);
}
return bytes;
}
public 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;
}
public 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;
}
public static String assertIdentifier(String s) {
return assertIsIdentifier(s);
}
public static A nuStubInnerObject(Class c) {
return nuStubInnerObject(c, null);
}
public static A nuStubInnerObject(Class c, Object classFinder) {
try {
Class outerType = getOuterClass(c, classFinder);
Constructor m = c.getDeclaredConstructor(outerType);
m.setAccessible(true);
return (A) m.newInstance(new Object[] { null });
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Map nuEmptyObject_cache = newDangerousWeakHashMap();
public 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);
}
}
try {
return (A) ctr.newInstance();
} catch (InstantiationException e) {
if (empty(e.getMessage()))
if ((c.getModifiers() & Modifier.ABSTRACT) != 0)
throw fail("Can't instantiate abstract class " + className(c), e);
else
throw fail("Can't instantiate " + className(c), e);
else
throw rethrow(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public 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());
}
public static HashMap findClass_cache = new HashMap();
public 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;
}
}
public static void setOptAllDyn(DynamicObject o, Map fields) {
if (fields == null)
return;
HashMap fieldMap = instanceFieldsMap(o);
for (Map.Entry e : fields.entrySet()) {
String field = e.getKey();
Object val = e.getValue();
boolean has = fieldMap.containsKey(field);
if (has)
setOpt(o, field, val);
else {
o.fieldValues.put(intern(field), val);
}
}
}
public static void setOptAll_pcall(Object o, Map fields) {
if (fields == null)
return;
for (String field : keys(fields)) try {
setOpt(o, field, fields.get(field));
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
public static void setOptAll_pcall(Object o, Object... values) {
warnIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
try {
setOpt(o, field, value);
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
}
public static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
public static Set keys(Object map) {
return keys((Map) map);
}
public static String intern(String s) {
return fastIntern(s);
}
public static void pcallOpt_noArgs(Object o, String method) {
try {
callOpt_noArgs(o, method);
} catch (Throwable __e) {
_handleException(__e);
}
}
public static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
public static List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
startIndex = Math.max(0, startIndex);
endIndex = Math.min(l(l), endIndex);
if (startIndex >= endIndex)
return ll();
return l.subList(startIndex, endIndex);
}
public 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;
}
public static boolean jmatch(String pat, String s) {
return jmatch(pat, s, null);
}
public static boolean jmatch(String pat, String s, Matches matches) {
if (s == null)
return false;
return jmatch(pat, javaTok(s), matches);
}
public static boolean jmatch(String pat, List toks) {
return jmatch(pat, toks, null);
}
public static boolean jmatch(String pat, List toks, Matches matches) {
List tokpat = javaTok(pat);
String[] m = match2(tokpat, toks);
if (m == null)
return false;
else {
if (matches != null)
matches.m = m;
return true;
}
}
public static boolean warn_on = true;
public static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
public static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
}
public static A popLast(List l) {
return liftLast(l);
}
public static boolean hasMethod(Object o, String method, Object... args) {
return findMethod(o, method, args) != null;
}
public static Pair jmenu_autoMnemonic(String s) {
int i = indexOf(s, '&');
if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i + 1)))
return pair(substring(s, 0, i) + substring(s, i + 1), (int) s.charAt(i + 1));
return pair(s, 0);
}
public static ActionListener actionListenerInNewThread(final Object runnable) {
return actionListenerInNewThread(runnable, null);
}
public static ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
startThread("Action Listener", new Runnable() {
public void run() {
try {
AutoCloseable __294 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__294);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __294 = holdInstance(instanceToHold); try {\r\n callF(runnab...";
}
});
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
public static boolean isCurlyBraced(String s) {
List tok = tok_combineCurlyBrackets_keep(javaTok(s));
return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}");
}
public static String tok_unCurlyBracket(String s) {
return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
}
public static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
public static Dimension getPreferredSize(final Component c) {
return c == null ? null : swing(new F0() {
public Dimension get() {
try {
return c.getPreferredSize();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getPreferredSize();";
}
});
}
public static boolean isStringOrIntOrLong(Object o) {
return o instanceof String || o instanceof Integer || o instanceof Long;
}
public static A dm_callOS(String functionName, Object... args) {
return (A) call(dm_os(), functionName, args);
}
public static Object dm_resolveModule(Object moduleOrStem) {
return dm_callOS("resolveModule", moduleOrStem);
}
public static int max(int a, int b) {
return Math.max(a, b);
}
public static int max(int a, int b, int c) {
return max(max(a, b), c);
}
public static long max(int a, long b) {
return Math.max((long) a, b);
}
public static long max(long a, long b) {
return Math.max(a, b);
}
public static double max(int a, double b) {
return Math.max((double) a, b);
}
public static float max(float a, float b) {
return Math.max(a, b);
}
public static double max(double a, double b) {
return Math.max(a, b);
}
public static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
public 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;
}
public 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;
}
public static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
public static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
public static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
public static Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
public static Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
public static Object collectionMutex(Object o) {
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
public static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
public static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
public static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
public static String quoteIfNotIdentifierOrInteger(String s) {
if (s == null)
return null;
return isJavaIdentifier(s) || isInteger(s) ? s : quote(s);
}
public static boolean headless() {
return isHeadless();
}
public static String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
public static String hideCredentials(String url) {
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
public static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
public static Throwable innerException2(Throwable e) {
if (e == null)
return null;
while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
return e;
}
public static Map classForName_cache = synchroHashMap();
public static Class classForName(String name) {
try {
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = Class.forName(name));
return c;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
public static Object nuObjectWithoutArguments(String className) {
try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A nuObjectWithoutArguments(Class c) {
try {
if (nuObjectWithoutArguments_cache == null)
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
m.setAccessible(true);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
public static List getClasses(Object[] array) {
List l = new ArrayList();
for (Object o : array) l.add(_getClass(o));
return l;
}
public 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);
}
public static Map emptyMap() {
return new HashMap();
}
public static boolean isLocalSnippetID(String snippetID) {
return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID));
}
public static boolean isLocalSnippetID(long snippetID) {
return snippetID >= 1000 && snippetID <= 9999;
}
public static String localSnippetTitle(String snippetID) {
if (!isLocalSnippetID(snippetID))
return null;
File f = localSnippetFile(snippetID);
if (!f.exists())
return null;
return or2(getFileInfoField(dropExtension(f), "Title"), "Unnamed");
}
public static boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
public static String imageServerURL() {
return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/");
}
public static String muricaCredentialsQuery() {
return htmlQuery(muricaCredentials());
}
public static boolean isGeneralFileServerSnippet(long id) {
return id >= 1400000 && id < 1500000;
}
public static String tb_mainServer_default = "http://tinybrain.de:8080";
public static Object tb_mainServer_override;
public static String tb_mainServer() {
if (tb_mainServer_override != null)
return (String) callF(tb_mainServer_override);
return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default));
}
public static File tb_mainServer_file() {
return getProgramFile("#1001638", "mainserver.txt");
}
public static boolean tb_mainServer_isDefault() {
return eq(tb_mainServer(), tb_mainServer_default);
}
public static String standardCredentials_noCookies() {
return standardCredentials() + "&noCookies=1";
}
public static boolean saveTextFileIfChanged(File f, String contents) {
return saveTextFileIfDifferent(f, contents);
}
public static File snippetTitle_cacheFile(String snippetID) {
return javaxCachesDir("Snippet Titles/" + psI(snippetID));
}
public static String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
public static Map findBot_cache = synchroHashMap();
public static int findBot_timeout = 5000;
public static DialogIO findBot(String searchPattern) {
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 + ".";
}
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();
String line = io.readLineNoBlock();
if (indexOfIgnoreCase(line, searchPattern) == 0) {
call(io, "pushback", line);
return talkToSubBot(subBot, io);
}
} catch (Exception e) {
e.printStackTrace();
}
List bots = quickBotScan();
for (ProgramScan.Program p : bots) {
if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) {
findBot_cache.put(searchPattern, p.port);
return talkToSubBot(subBot, talkTo("localhost", p.port));
}
}
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;
}
public static int smartIndexOf(String s, String sub, int i) {
if (s == null)
return 0;
i = s.indexOf(sub, min(i, l(s)));
return i >= 0 ? i : l(s);
}
public static int smartIndexOf(String s, int i, char c) {
return smartIndexOf(s, c, i);
}
public static int smartIndexOf(String s, char c, int i) {
if (s == null)
return 0;
i = s.indexOf(c, min(i, l(s)));
return i >= 0 ? i : l(s);
}
public static int smartIndexOf(String s, String sub) {
return smartIndexOf(s, sub, 0);
}
public static int smartIndexOf(String s, char c) {
return smartIndexOf(s, c, 0);
}
public static int smartIndexOf(List l, A sub) {
return smartIndexOf(l, sub, 0);
}
public static int smartIndexOf(List l, int start, A sub) {
return smartIndexOf(l, sub, start);
}
public static int smartIndexOf(List l, A sub, int start) {
int i = indexOf(l, sub, start);
return i < 0 ? l(l) : i;
}
public static boolean matchStart(String pat, String s) {
return matchStart(pat, s, null);
}
public static boolean matchStart(String pat, String s, Matches matches) {
if (s == null)
return false;
return matchStart(pat, parse3_cachedInput(s), matches);
}
public static boolean matchStart(String pat, List toks, Matches matches) {
if (toks == null)
return false;
List tokpat = parse3_cachedPattern(pat);
if (toks.size() < tokpat.size())
return false;
String[] m = match2(tokpat, toks.subList(0, tokpat.size()));
if (m == null)
return false;
if (matches != null) {
matches.m = new String[m.length + 1];
arraycopy(m, matches.m);
matches.m[m.length] = join(toks.subList(tokpat.size(), toks.size()));
}
return true;
}
public 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();
}
}
public static void cleanKillVM() {
try {
ping();
assertNotOnAWTThread();
cleanKillVM_noSleep();
Object o = new Object();
synchronized (o) {
o.wait();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void cleanKillVM_noSleep() {
call(getJavaX(), "cleanKill");
}
public static File userDir() {
return new File(userHome());
}
public static File userDir(String path) {
return new File(userHome(), path);
}
public static String fsI_flex(String s) {
return startsWithDigit(s) ? "#" + s : s;
}
public static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
public static File newFile(String name) {
return name == null ? null : new File(name);
}
public static boolean exposeMethods2_debug;
public static String exposeMethods2(Object receiver, String s, List methodNames) {
return exposeMethods2(receiver, s, methodNames, null);
}
public static String exposeMethods2(Object receiver, String s, List methodNames, Lock lock) {
Matches m = new Matches();
if (exposeMethods2_debug)
print("Received: " + s);
if (match("call *", s, m)) {
List l;
if (isIdentifier(m.unq(0)))
l = ll(m.unq(0));
else
l = (List) unstructure(m.unq(0));
String method = getString(l, 0);
if (!contains(methodNames, method))
throw fail("Method not allowed: " + method);
if (lock != null)
lock.lock();
try {
if (exposeMethods2_debug)
print("Calling: " + method);
Object o = call(receiver, method, asObjectArray(subList(l, 1)));
if (exposeMethods2_debug)
print("Got: " + getClassName(o));
return ok2(structure(o));
} finally {
if (lock != null)
lock.unlock();
}
}
if (match("list methods", s))
return ok2(structure(methodNames));
return null;
}
public static int makeBot(String greeting) {
return makeAndroid3(greeting).port;
}
public static Android3 makeBot(Android3 a) {
makeAndroid3(a);
return a;
}
public static Android3 makeBot(String greeting, Object responder) {
Android3 a = new Android3(greeting);
a.responder = makeResponder(responder);
makeBot(a);
return a;
}
public static Android3 makeBot() {
return makeAndroid3(defaultBotName());
}
public static Set listFields(Object c) {
TreeSet fields = new TreeSet();
for (Field f : _getClass(c).getDeclaredFields()) fields.add(f.getName());
return fields;
}
public static String n(long l, String name) {
return l + " " + trim(l == 1 ? singular(name) : getPlural(name));
}
public static String n(Collection l, String name) {
return n(l(l), name);
}
public static String n(Map m, String name) {
return n(l(m), name);
}
public static String n(Object[] a, String name) {
return n(l(a), name);
}
public static boolean odd(int i) {
return (i & 1) != 0;
}
public static boolean odd(long i) {
return (i & 1) != 0;
}
public static boolean odd(BigInteger i) {
return odd(toInt(i));
}
public static void nohupJavax(final String javaxargs) {
startThread(new Runnable() {
public void run() {
try {
call(hotwireOnce("#1008562"), "nohupJavax", javaxargs);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs);";
}
});
}
public static void nohupJavax(final String javaxargs, final String vmArgs) {
startThread(new Runnable() {
public void run() {
try {
call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs, vmArgs);";
}
});
}
public 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);
}
public static String smartJoin(List args) {
return smartJoin(toStringArray(args));
}
public static ArrayList cloneListSynchronizingOn(Collection l, Object mutex) {
if (l == null)
return new ArrayList();
synchronized (mutex) {
return new ArrayList(l);
}
}
public static Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null)
return e;
while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause();
return e;
}
public static String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix))
return s;
return replacement + substring(s, l(prefix));
}
public static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
public static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
public static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
public static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
public static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
public static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
public static File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
public static Map vm_generalMap_map;
public static Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
public static File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
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);
}
public static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL(dataSnippetLink(snippetID));
print("Loading library: " + hideCredentials(url));
try {
data = loadBinaryPage(url.openConnection());
} catch (RuntimeException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL("http://data.tinybrain.de/blobs/" + parseSnippetID(snippetID));
print("Loading library: " + hideCredentials(url));
data = loadBinaryPage(url.openConnection());
}
print("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
public static long fileSize(String path) {
return getFileSize(path);
}
public static long fileSize(File f) {
return getFileSize(f);
}
public static File loadDataSnippetToFile(String snippetID) {
try {
snippetID = fsI(snippetID);
File f = DiskSnippetCache_file(parseSnippetID(snippetID));
List urlsTried = new ArrayList();
List errors = new ArrayList();
try {
URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
print("Loading library: " + hideCredentials(url));
try {
loadBinaryPageToFile(openConnection(url), f);
if (fileSize(f) == 0)
throw fail();
} catch (Throwable e) {
errors.add(e);
url = addAndReturn(urlsTried, new URL("http://data.tinybrain.de/blobs/" + psI(snippetID)));
print("Trying other server: " + hideCredentials(url));
loadBinaryPageToFile(openConnection(url), f);
print("Got bytes: " + fileSize(f));
}
if (fileSize(f) == 0)
throw fail();
System.err.println("Bytes loaded: " + fileSize(f));
} catch (Throwable e) {
printStackTrace(e);
errors.add(e);
throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
}
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static byte[] isGIF_magic = bytesFromHex("47494638");
public static boolean isGIF(byte[] data) {
return byteArrayStartsWith(data, isGIF_magic);
}
public static boolean isGIF(File f) {
return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
}
public static String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
public static String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
public static void setVar(IVar v, A value) {
if (v != null)
v.set(value);
}
public static boolean substanceLookAndFeelEnabled() {
return startsWith(getLookAndFeel(), "org.pushingpixels.");
}
public static JComponent getTitlePaneComponent(RootPaneContainer window) {
if (window instanceof JInternalFrame)
return getInternalFrameTitlePaneComponent((JInternalFrame) window);
if (!substanceLookAndFeelEnabled() || window == null)
return null;
JRootPane rootPane = window.getRootPane();
if (rootPane != null) {
Object ui = rootPane.getUI();
return (JComponent) call(ui, "getTitlePane");
}
return null;
}
public static RootPaneContainer getPossiblyInternalFrame(Component c) {
JInternalFrame f = getInternalFrame(c);
if (f != null)
return f;
return optCast(RootPaneContainer.class, getWindow(c));
}
public static void addActionListener(JTextField tf, final Runnable action) {
onEnter(tf, action);
}
public static void addActionListener(final JComboBox cb, final Runnable action) {
if (cb != null) {
swing(new Runnable() {
public void run() {
try {
cb.addActionListener(actionListener(action));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.addActionListener(actionListener(action));";
}
});
}
}
public static void addActionListener(final AbstractButton b, final Runnable action) {
if (b != null) {
swing(new Runnable() {
public void run() {
try {
b.addActionListener(actionListener(action));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "b.addActionListener(actionListener(action));";
}
});
}
}
public static boolean isChecked(final JCheckBox checkBox) {
return checkBox != null && (boolean) swing(new F0() {
public Boolean get() {
try {
return checkBox.isSelected();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret checkBox.isSelected();";
}
});
}
public static boolean isChecked(final JCheckBoxMenuItem mi) {
return mi != null && (boolean) swing(new F0() {
public Boolean get() {
try {
return mi.isSelected();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret mi.isSelected();";
}
});
}
public static Class hotwireOnce(String programID) {
return hotwireCached(programID, false);
}
public static A listGet(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
public static List mapToLines(Map map) {
List l = new ArrayList();
for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
return l;
}
public static String fromLines(Collection lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
public static String fromLines(String... lines) {
return fromLines(asList(lines));
}
public static IterableIterator toLines(File f) {
return linesFromFile(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;
}
public 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;
}
public static String beautifyStructure(String s) {
List tok = javaTok(s);
structure_addTokenMarkers(tok);
jreplace(tok, "lhm", "");
return join(tok);
}
public static String quickSubstring(String s, int i, int j) {
if (i == j)
return "";
return s.substring(i, j);
}
public static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
public static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
public static boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b))
return false;
m.m = new String[] { dropLast(l(b), a) };
return true;
}
public static NavigableMap synchroTreeMap() {
return Collections.synchronizedNavigableMap(new TreeMap());
}
public static Map synchroMap() {
return synchroHashMap();
}
public static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
public static int shorten_default = 100;
public static String shorten(String s) {
return shorten(s, shorten_default);
}
public static String shorten(String s, int max) {
return shorten(s, max, "...");
}
public static String shorten(String s, int max, String shortener) {
if (s == null)
return "";
if (max < 0)
return s;
return s.length() <= max ? s : substring(s, 0, min(s.length(), max - l(shortener))) + shortener;
}
public static String shorten(int max, String s) {
return shorten(s, max);
}
public static int parseHexChar(char c) {
if (c >= '0' && c <= '9')
return charDiff(c, '0');
if (c >= 'a' && c <= 'f')
return charDiff(c, 'a') + 10;
if (c >= 'A' && c <= 'F')
return charDiff(c, 'A') + 10;
return -1;
}
public static int min(int a, int b) {
return Math.min(a, b);
}
public static long min(long a, long b) {
return Math.min(a, b);
}
public static float min(float a, float b) {
return Math.min(a, b);
}
public static float min(float a, float b, float c) {
return min(min(a, b), c);
}
public static double min(double a, double b) {
return Math.min(a, b);
}
public static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
public static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
public static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
public static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
public static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
public static String assertIsIdentifier(String s) {
if (!isIdentifier(s))
throw fail("Not an identifier: " + quote(s));
return s;
}
public static Class getOuterClass(Class c) {
return getOuterClass(c, null);
}
public static Class getOuterClass(Class c, Object classFinder) {
try {
String s = c.getName();
int i = s.lastIndexOf('$');
String name = substring(s, 0, i);
if (classFinder != null)
return (Class) callF(classFinder, name);
return Class.forName(name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static HashMap instanceFieldsMap(Object o) {
Class c = o.getClass();
HashMap map;
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map;
}
public static Method fastIntern_method;
public static String fastIntern(String s) {
try {
if (s == null)
return null;
if (fastIntern_method == null) {
fastIntern_method = findMethodNamed(javax(), "internPerProgram");
if (fastIntern_method == null)
upgradeJavaXAndRestart();
}
return (String) fastIntern_method.invoke(null, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Map> callOpt_noArgs_cache = newDangerousWeakHashMap();
public static Object callOpt_noArgs(Object o, String method) {
try {
if (o == null)
return null;
if (o instanceof Class)
return callOpt(o, method);
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);
}
}
public 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;
}
public static int javaTok_n, javaTok_elements;
public static boolean javaTok_opt;
public static List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
public static List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
public static String[] match2(List pat, List tok) {
int i = pat.indexOf("...");
if (i < 0)
return match2_match(pat, tok);
pat = new ArrayList(pat);
pat.set(i, "*");
while (pat.size() < tok.size()) {
pat.add(i, "*");
pat.add(i + 1, "");
}
return match2_match(pat, tok);
}
public 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)))
return null;
}
return result.toArray(new String[result.size()]);
}
public 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;
}
public static Method findMethod(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Method m = findMethod_static((Class) o, method, args, false);
if (m == null)
return null;
m.setAccessible(true);
return m;
} else {
Method m = findMethod_instance(o, method, args, false);
if (m == null)
return null;
m.setAccessible(true);
return m;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Method findMethod_static(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 || !findMethod_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
public static Method findMethod_instance(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) && findMethod_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
public static boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
public static boolean isLetterOrDigit(char c) {
return Character.isLetterOrDigit(c);
}
public static List tok_combineCurlyBrackets_keep(List tok) {
List l = new ArrayList();
for (int i = 0; i < l(tok); i++) {
String t = tok.get(i);
if (odd(i) && eq(t, "{")) {
int j = findEndOfCurlyBracketPart(tok, i);
l.add(joinSubList(tok, i, j));
i = j - 1;
} else
l.add(t);
}
return l;
}
public static boolean startsWithAndEndsWith(String s, String prefix, String suffix) {
return startsWith(s, prefix) && endsWith(s, suffix);
}
public static List dropFirstThreeAndLastThree(List l) {
return dropFirstAndLast(3, l);
}
public static Object dm_os() {
return creator();
}
public static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
public static volatile PersistableThrowable lastException_lastException;
public static PersistableThrowable lastException() {
return lastException_lastException;
}
public static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
public static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
public static long psI(String snippetID) {
return parseSnippetID(snippetID);
}
public static File localSnippetFile(long snippetID) {
return localSnippetsDir(snippetID + ".text");
}
public static File localSnippetFile(String snippetID) {
return localSnippetFile(parseSnippetID(snippetID));
}
public static String getFileInfoField(File f, String field) {
return getOneLineFileInfoField(f, field);
}
public static File dropExtension(File f) {
return f == null ? null : fileInSameDir(f, dropExtension(f.getName()));
}
public static String dropExtension(String s) {
return takeFirst(s, smartLastIndexOf(s, '.'));
}
public static String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(File f, String defaultContents) {
try {
checkFileNotTooBigToRead(f);
if (f == null || !f.exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(f);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (Exception __e) {
throw rethrow(__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 str(builder);
}
public static File javaxDataDir_dir;
public static File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
public static File javaxDataDir(String... subs) {
return newFile(javaxDataDir(), subs);
}
public static String htmlQuery(Map params) {
return params.isEmpty() ? "" : "?" + makePostData(params);
}
public static String htmlQuery(Object... data) {
return htmlQuery(litmap(data));
}
public static Object[] muricaCredentials() {
String pass = muricaPassword();
return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0];
}
public static File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
public static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
public static String standardCredentials() {
String user = standardCredentialsUser();
String pass = standardCredentialsPass();
if (nempty(user) && nempty(pass))
return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
return "";
}
public static boolean saveTextFileIfDifferent(File f, String contents) {
if (eq(loadTextFile(f), contents))
return false;
{
saveTextFile(f, contents);
return true;
}
}
public static File javaxCachesDir_dir;
public static File javaxCachesDir() {
return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
public static File javaxCachesDir(String sub) {
return newFile(javaxCachesDir(), sub);
}
public static String baseClassName(String className) {
return substring(className, className.lastIndexOf('.') + 1);
}
public static String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
public static String prependIfNempty(String prefix, String s) {
return empty(s) ? s : prefix + s;
}
public static DialogIO talkToSubBot(final long vport, final DialogIO io) {
return talkToSubBot(String.valueOf(vport), io);
}
public static DialogIO talkToSubBot(final String subBot, final DialogIO io) {
if (subBot == null)
return io;
return new talkToSubBot_IO(subBot, io);
}
public static class talkToSubBot_IO extends DialogIO {
public String subBot;
public DialogIO io;
public talkToSubBot_IO(String subBot, DialogIO io) {
this.io = io;
this.subBot = subBot;
}
public boolean isStillConnected() {
return io.isStillConnected();
}
public String readLineImpl() {
return io.readLineImpl();
}
public boolean isLocalConnection() {
return io.isLocalConnection();
}
public Socket getSocket() {
return io.getSocket();
}
public void close() {
io.close();
}
public void sendLine(String line) {
io.sendLine(format3("please forward to bot *: *", subBot, line));
}
}
public static DialogIO talkTo(int port) {
return talkTo("localhost", port);
}
public static int talkTo_defaultTimeout = 10000;
public static int talkTo_timeoutForReads = 0;
public static ThreadLocal