values(Map map) {
return map == null ? emptyList() : map.values();
}
static public Collection values(Object map) {
return values((Map) map);
}
static public Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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!" : ""));
}
static public boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static public JTextArea jTextAreaWithUndo() {
return jTextAreaWithUndo("");
}
static public JTextArea jTextAreaWithUndo(final String text) {
return jenableUndoRedo(swingNu(JTextArea.class, text));
}
static public boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static public boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
static public boolean containsNewLines(String s) {
return containsNewLine(s);
}
static public String jlabel_textAsHTML_center(String text) {
return "" + replace(htmlencode(text), "\n", " ") + "
";
}
static public boolean headless() {
return isHeadless();
}
static public String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
static public String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
static public boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static public CloseableIterableIterator linesFromFile(File f) {
try {
if (!f.exists())
return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
return linesFromReader(utf8bufferedReader(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public CloseableIterableIterator linesFromFile(String path) {
return linesFromFile(newFile(path));
}
static public String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
static public double fraction(double d) {
return d % 1;
}
static public String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
static public String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
static public String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
static public String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
static public String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
static public List collectField(Iterable c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
static public List collectField(String field, Iterable c) {
return collectField(c, field);
}
static public Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static public Class getClass(Object realm, String name) {
try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String classNameToVM(String name) {
return name.replace(".", "$");
}
static public String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public String imageServerLink(String md5OrID) {
if (possibleMD5(md5OrID))
return "https://botcompany.de/images/md5/" + md5OrID;
return imageServerLink(parseSnippetID(md5OrID));
}
static public String imageServerLink(long id) {
return "https://botcompany.de/images/" + id;
}
static public boolean networkAllowanceTest(String url) {
return isAllowed("networkAllowanceTest", url);
}
static final public boolean loadPageThroughProxy_enabled = false;
static public String loadPageThroughProxy(String url) {
return null;
}
static public void sleepSeconds(double s) {
if (s > 0)
sleep(round(s * 1000));
}
static public A printWithTime(A a) {
return printWithTime("", a);
}
static public A printWithTime(String s, A a) {
print(hmsWithColons() + ": " + s, a);
return a;
}
static public Map vm_generalSubMap(Object name) {
synchronized (get(javax(), "generalMap")) {
Map map = (Map) (vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = synchroMap());
return map;
}
}
static public InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
UnknownHostException lastException = null;
for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) {
try {
if (con instanceof HttpURLConnection)
if (((HttpURLConnection) con).getResponseCode() == 500)
throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con))));
return con.getInputStream();
} catch (UnknownHostException e) {
lastException = e;
print("Retrying because of: " + e);
continue;
}
}
throw lastException;
}
static public GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
static public GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
static public String toHex(byte[] bytes) {
return bytesToHex(bytes);
}
static public String toHex(byte[] bytes, int ofs, int len) {
return bytesToHex(bytes, ofs, len);
}
static public byte[] utf8(String s) {
return toUtf8(s);
}
static public Matcher regexpMatcher(String pat, String s) {
return compileRegexp(pat).matcher(unnull(s));
}
static public URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) {
con.setConnectTimeout(toInt(timeout));
con.setReadTimeout(toInt(timeout));
if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
print("Warning: Timeouts not set by JDK.");
return con;
}
static public URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
if (con.getConnectTimeout() == 0) {
con.setConnectTimeout(toInt(timeout));
if (con.getConnectTimeout() != timeout)
print("Warning: URL connect timeout not set by JDK.");
}
if (con.getReadTimeout() == 0) {
con.setReadTimeout(toInt(timeout));
if (con.getReadTimeout() != timeout)
print("Warning: URL read timeout not set by JDK.");
}
return con;
}
static public String getComputerID_quick() {
return computerID();
}
static public String or2(String a, String b) {
return nempty(a) ? a : b;
}
static public String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
static public File muricaPasswordFile() {
return new File(javaxSecretDir(), "murica/muricaPasswordFile");
}
static public int roundDownTo(int n, int x) {
return x / n * n;
}
static public long roundDownTo(long n, long x) {
return x / n * n;
}
static public A popLast(List l) {
return liftLast(l);
}
static public List popLast(int n, List l) {
return liftLast(n, l);
}
static public A[] arrayOfSameType(A[] a, int n) {
return newObjectArrayOfSameType(a, n);
}
static public List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static public List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static public List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return l.subList(startIndex, endIndex);
}
static public boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static public File programDir_mine;
static public File programDir() {
return programDir(getProgramID());
}
static public File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
if (me) {
String c = caseID();
if (nempty(c))
dir = newFile(dir, c);
}
return dir;
}
static public File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
static public String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static public Class getMainClass() {
return mc();
}
static public Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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);
}
}
static public ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static public AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static public Map classForName_cache = synchroHashMap();
static public Class classForName(String name) {
try {
if (classForName_cache == null)
return Class.forName(name);
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);
}
}
static public Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static public Object nuObjectWithoutArguments(String className) {
try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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);
}
}
static public Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
static public Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static public Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static public Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static public List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static public A jenableUndoRedo(final A textcomp) {
{
swing(new Runnable() {
public void run() {
try {
final UndoManager undo = new UndoManager();
vm_generalWeakSet("Undo Managers").add(undo);
textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() {
public void run() {
try {
if (undo.canUndo())
undo.undo();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (undo.canUndo()) undo.undo()";
}
}));
textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() {
public void run() {
try {
if (undo.canRedo())
undo.redo();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (undo.canRedo()) undo.redo()";
}
}));
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final new UndoManager undo;\r\n vm_generalWeakSet(\"Undo Managers\").add(undo)...";
}
});
}
return textcomp;
}
static public A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static public boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static public boolean containsNewLine(String s) {
return contains(s, '\n');
}
static public 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;
}
static public List replace(A a, A b, List l) {
return replace(l, a, b);
}
static public String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static public String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
static public String htmlencode(Object o) {
return htmlencode(str(o));
}
static public 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 == '&') {
int cp = s.codePointAt(i);
out.append("");
out.append(intToHex_flexLength(cp));
out.append(';');
i += Character.charCount(cp) - 1;
} else
out.append(c);
}
return out.toString();
}
static public String strOrNull(Object o) {
return o == null ? null : str(o);
}
static public CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
public Object next() {
throw fail();
}
public boolean hasNext() {
return false;
}
};
static public CloseableIterableIterator emptyCloseableIterableIterator() {
return emptyCloseableIterableIterator_instance;
}
static public CloseableIterableIterator linesFromReader(Reader r) {
final BufferedReader br = bufferedReader(r);
return iteratorFromFunction_f0_autoCloseable(new F0() {
public String get() {
try {
return readLineFromReaderWithClose(br);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret readLineFromReaderWithClose(br);";
}
}, _wrapIOCloseable(r));
}
static public BufferedReader utf8bufferedReader(InputStream in) {
try {
return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public BufferedReader utf8bufferedReader(File f) {
try {
return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
static public boolean possibleMD5(String s) {
return isMD5(s);
}
static volatile public Object isAllowed_function;
static volatile public boolean isAllowed_all = true;
static public boolean isAllowed(String askingMethod, Object... args) {
Object f = vm_generalMap_get("isAllowed_function");
if (f != null && !isTrue(callF(f, askingMethod, args)))
return false;
return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
}
static public long round(double d) {
return Math.round(d);
}
static public String hmsWithColons() {
return hmsWithColons(now());
}
static public String hmsWithColons(long time) {
return new SimpleDateFormat("HH:mm:ss").format(time);
}
static public Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static public Map synchroMap() {
return synchroHashMap();
}
static public Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static public String joinNemptiesWithColonSpace(String... strings) {
return joinNempties(": ", strings);
}
static public String joinNemptiesWithColonSpace(Collection strings) {
return joinNempties(": ", strings);
}
static public String tryToReadErrorStreamFromURLConnection(URLConnection conn) {
try {
if (conn instanceof HttpURLConnection)
return stream2string(((HttpURLConnection) conn).getErrorStream());
return null;
} catch (Throwable __e) {
return null;
}
}
static public int gzInputStream_defaultBufferSize = 65536;
static public GZIPInputStream gzInputStream(File f) {
try {
return gzInputStream(new FileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public GZIPInputStream gzInputStream(File f, int bufferSize) {
try {
return gzInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public GZIPInputStream gzInputStream(InputStream in) {
return gzInputStream(in, gzInputStream_defaultBufferSize);
}
static public GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
try {
return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len * 2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs + i]);
stringBuilder.append(s.substring(s.length() - 2, s.length()));
}
return stringBuilder.toString();
}
static public byte[] toUtf8(String s) {
try {
return s.getBytes("UTF-8");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map compileRegexp_cache = syncMRUCache(10);
static public java.util.regex.Pattern compileRegexp(String pat) {
java.util.regex.Pattern p = compileRegexp_cache.get(pat);
if (p == null) {
compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat));
}
return p;
}
static public String _computerID;
static public Lock computerID_lock = lock();
public static String computerID() {
if (_computerID == null) {
Lock __0 = computerID_lock;
lock(__0);
try {
if (_computerID != null)
return _computerID;
File file = computerIDFile();
_computerID = loadTextFile(file.getPath());
if (_computerID == null) {
_computerID = loadTextFile(userDir(".tinybrain/computer-id"));
if (_computerID == null)
_computerID = makeRandomID(12, new SecureRandom());
saveTextFile(file, _computerID);
}
} finally {
unlock(__0);
}
}
return _computerID;
}
static public File javaxSecretDir_dir;
static public File javaxSecretDir() {
return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
}
static public File javaxSecretDir(String sub) {
return newFile(javaxSecretDir(), sub);
}
static public A liftLast(List l) {
if (empty(l))
return null;
int i = l(l) - 1;
A a = l.get(i);
l.remove(i);
return a;
}
static public List liftLast(int n, List l) {
int i = l(l) - n;
List part = cloneSubList(l, i);
removeSubList(l, i);
return part;
}
static public A[] newObjectArrayOfSameType(A[] a, int n) {
return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
}
static public boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b))
return false;
return parseSnippetID(a) == parseSnippetID(b);
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static volatile public String caseID_caseID;
static public String caseID() {
return caseID_caseID;
}
static public void caseID(String id) {
caseID_caseID = id;
}
static public Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static public Set vm_generalWeakSet(Object name) {
synchronized (get(javax(), "generalMap")) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = newWeakHashSet());
return set;
}
}
static public String intToHex_flexLength(int i) {
return Integer.toHexString(i);
}
static public BufferedReader bufferedReader(Reader r) {
return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
}
static public CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) {
class IFF2 extends CloseableIterableIterator {
public A a;
public boolean done = false;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
return _a;
}
public void getNext() {
if (done || a != null)
return;
a = f.get();
done = a == null;
}
public void close() throws Exception {
if (closeable != null)
closeable.close();
}
}
;
return new IFF2();
}
static public String readLineFromReaderWithClose(BufferedReader r) {
try {
String s = r.readLine();
if (s == null)
r.close();
return s;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
return c == null ? null : new AutoCloseable() {
public String toString() {
return "c.close();\r\n _registerIO(c, null, false);";
}
public void close() throws Exception {
c.close();
_registerIO(c, null, false);
}
};
}
static public A _registerIOWrap(A wrapper, Object wrapped) {
return wrapper;
}
static public FileInputStream newFileInputStream(File path) throws IOException {
return newFileInputStream(path.getPath());
}
static public FileInputStream newFileInputStream(String path) throws IOException {
FileInputStream f = new FileInputStream(path);
_registerIO(f, path, true);
return f;
}
static public boolean isMD5(String s) {
return l(s) == 32 && isLowerHexString(s);
}
static public B mapPutOrRemove(Map map, A key, B value) {
if (map != null && key != null)
if (value != null)
return map.put(key, value);
else
return map.remove(key);
return null;
}
static public String joinNempties(String sep, String... strings) {
return joinStrings(sep, strings);
}
static public String joinNempties(String sep, Collection strings) {
return joinStrings(sep, strings);
}
static public String stream2string(InputStream in) {
return utf8streamToString(in);
}
static public Map syncMRUCache(int size) {
return synchroMap(new MRUCache(size));
}
static public File computerIDFile() {
return javaxDataDir("Basic Info/computer-id.txt");
}
static public String makeRandomID(int length) {
return makeRandomID(length, defaultRandomGenerator());
}
static public String makeRandomID(int length, Random random) {
char[] id = new char[length];
for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
static public String makeRandomID(Random r, int length) {
return makeRandomID(length, r);
}
static public List cloneSubList(List l, int startIndex, int endIndex) {
return newSubList(l, startIndex, endIndex);
}
static public List cloneSubList(List l, int startIndex) {
return newSubList(l, startIndex);
}
static public void removeSubList(List l, int from, int to) {
if (l != null)
subList(l, from, to).clear();
}
static public void removeSubList(List l, int from) {
if (l != null)
subList(l, from).clear();
}
static public Set newWeakHashSet() {
return synchroWeakHashSet();
}
static public boolean isLowerHexString(String s) {
for (int i = 0; i < l(s); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
} else
return false;
}
return true;
}
static public String joinStrings(String sep, String... strings) {
return joinStrings(sep, Arrays.asList(strings));
}
static public String joinStrings(String sep, Collection strings) {
StringBuilder buf = new StringBuilder();
for (String s : unnull(strings)) if (nempty(s)) {
if (nempty(buf))
buf.append(sep);
buf.append(s);
}
return str(buf);
}
static public String utf8streamToString(InputStream in) {
return readerToString(utf8bufferedReader(in));
}
static public Random defaultRandomGenerator() {
return ThreadLocalRandom.current();
}
static public List newSubList(List l, int startIndex, int endIndex) {
return cloneList(subList(l, startIndex, endIndex));
}
static public List newSubList(List l, int startIndex) {
return cloneList(subList(l, startIndex));
}
static public Set synchroWeakHashSet() {
return Collections.newSetFromMap((Map) newWeakHashMap());
}
static public String readerToString(Reader r) {
try {
try {
StringBuilder buf = new StringBuilder();
int n = 0;
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
}
return buf.toString();
} finally {
r.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
final static public class _MethodCache {
final public Class c;
final public HashMap> cache = new HashMap();
public _MethodCache(Class c) {
this.c = c;
_init();
}
public void _init() {
Class _c = c;
while (_c != null) {
for (Method m : _c.getDeclaredMethods()) if (!isAbstract(m) && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
_c = _c.getSuperclass();
}
for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
}
public Method findMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Method findStaticMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (isStaticMethod(me) && call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static public class LineBuffer {
public VF1 onLine;
public StringBuilder currentLine = new StringBuilder();
public LineBuffer() {
}
public LineBuffer(VF1 onLine) {
this.onLine = onLine;
}
public void append(String s) {
append(s, onLine);
}
public void append(String s, VF1 onLine) {
currentLine.append(s);
if (contains(s, '\n')) {
int i = 0, j;
s = str(currentLine);
while ((j = indexOf(s, i, '\n')) >= 0) {
String line = dropTrailingBackslashR(substring(s, i, j));
callF(onLine, line);
i = j + 1;
}
currentLine = new StringBuilder(substring(s, i));
}
}
public int size() {
return l(currentLine);
}
}
static public class Var implements IVar {
public Var() {
}
public Var(A v) {
this.v = v;
}
public A v;
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() {
return v;
}
public synchronized boolean has() {
return v != null;
}
public synchronized void clear() {
v = null;
}
public String toString() {
return str(get());
}
}
static abstract public class IterableIterator implements Iterator , Iterable {
public Iterator iterator() {
return this;
}
public void remove() {
unsupportedOperation();
}
}
static abstract public class F2 {
abstract public C get(A a, B b);
}
static public class MRUCache extends LinkedHashMap {
public int maxSize = 10;
public MRUCache() {
}
public MRUCache(int maxSize) {
this.maxSize = maxSize;
}
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > maxSize;
}
public Object _serialize() {
return ll(maxSize, cloneLinkedHashMap(this));
}
static public MRUCache _deserialize(List l) {
MRUCache m = new MRUCache();
m.maxSize = (int) first(l);
m.putAll((LinkedHashMap) second(l));
return m;
}
}
static public interface IF0 {
public A get();
}
static abstract public class CloseableIterableIterator extends IterableIterator implements AutoCloseable {
public void close() throws Exception {
}
}
static public class TailFile implements AutoCloseable {
public File file;
public int interval;
public Object onData;
public long l;
public Flag stopped = new Flag();
public java.util.Timer timer;
public ReliableSingleThread thread;
volatile public boolean hasIdled, debug;
public TailFile() {
}
public TailFile(final File file, int interval, Object onData) {
this.onData = onData;
this.interval = interval;
this.file = file;
thread = new ReliableSingleThread(new Runnable() {
public void run() {
try {
update();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "update()";
}
});
}
public void update() {
long l2 = l(file);
if (l2 < l)
l = 0;
if (l2 == l)
hasIdled = true;
else
try {
if (debug)
print("New data in " + f2s(file) + ": " + n2(l2 - l, "byte"));
for (String s : loadTextFilePart_iterator(file, l, l2)) pcallF(onData, s);
l = l2;
} catch (Throwable __e) {
_handleException(__e);
}
}
public void start() {
timer = doEvery(interval, new Runnable() {
public void run() {
try {
if (!stopped.isUp())
thread.trigger();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!stopped.isUp()) thread.trigger()";
}
});
}
public void stop() {
timer.cancel();
timer = null;
if (stopped.raise())
thread.triggerAndWait();
}
public void close() {
stop();
}
public boolean started() {
return timer != null;
}
public void debugOn() {
if (debug)
return;
debug = true;
print("Watching file: " + f2s(file));
}
}
static public interface IResourceLoader {
public String loadSnippet(String snippetID);
public String getTranspiled(String snippetID);
public int getSnippetType(String snippetID);
public String getSnippetTitle(String snippetID);
public File loadLibrary(String snippetID);
public File pathToJavaXJar();
public File getSnippetJar(String snippetID, String transpiledSrc);
}
static public interface IVF1 {
public void get(A a);
}
static public interface IVF2 {
public void get(A a, B b);
}
abstract static public class DynPrintLogAndEnabled extends DynPrintLog {
volatile public boolean enabled = true;
transient public JPanel buttons;
public JComponent visualize() {
return dm_visualizeWithEnabled(super.visualize());
}
public JComponent visualizeWithoutEnabled() {
return super.visualize();
}
public JComponent dm_visualizeWithEnabled(JComponent main) {
return centerAndSouthWithMargins(main, buttons = makeControlArea());
}
public JPanel makeControlArea() {
return jrightalignedline(makeEnabledCheckBox());
}
static public JCheckBox makeEnabledCheckBox() {
return dm_fieldCheckBox("enabled");
}
public void setEnabled(boolean b) {
setField("enabled", b);
}
}
static public class Cache {
public Object maker;
public A value;
public long loaded;
static public boolean debug = false;
public long changeCount;
public Lock lock = lock();
public Cache() {
}
public Cache(Object maker) {
this.maker = maker;
}
public Cache(IF0 maker) {
this.maker = maker;
}
public A get() {
if (hasLock(lock))
return value;
Lock __0 = lock;
lock(__0);
try {
if (loaded == 0) {
value = make();
changeCount++;
loaded = sysNow();
}
return value;
} finally {
unlock(__0);
}
}
public void clear() {
Lock __1 = lock;
lock(__1);
try {
if (debug && loaded != 0)
print("Clearing cache");
value = null;
changeCount++;
loaded = 0;
} finally {
unlock(__1);
}
}
public void clear(double seconds) {
Lock __2 = lock;
lock(__2);
try {
if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000)
clear();
} finally {
unlock(__2);
}
}
public void set(A a) {
Lock __3 = lock;
lock(__3);
try {
value = a;
++changeCount;
loaded = sysNow();
} finally {
unlock(__3);
}
}
public A make() {
return (A) callF(maker);
}
}
static public class ReliableSingleThread implements Runnable {
public boolean _isTransient() {
return true;
}
public Object runnable;
public String name = "Single Thread";
public boolean cancelBeforeTrigger = false;
public F0 enter;
public int cancelTimeOut = 10000;
public boolean trigger = false;
public Thread thread;
public WeakReference threadBeingCancelled;
public ReliableSingleThread(Object runnable) {
this.runnable = runnable;
}
public void trigger() {
go();
}
synchronized public void go() {
if (cancelBeforeTrigger)
cancel();
trigger = true;
if (!running()) {
AutoCloseable __1 = callF(enter);
try {
thread = startThread(name, new Runnable() {
public void run() {
try {
AutoCloseable __2 = callF(enter);
try {
_run();
} finally {
_close(__2);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp callF(enter);\r\n _run();";
}
});
} finally {
_close(__1);
}
}
}
public void run() {
go();
}
public void get() {
go();
}
synchronized public boolean running() {
return thread != null;
}
public void triggerAndWait() {
trigger();
waitUntilDone();
}
public void waitUntilDone() {
while (running()) sleep(1);
}
public void _run() {
try {
while (licensed()) {
Thread oldThread;
synchronized (this) {
if (!trigger) {
thread = null;
break;
}
oldThread = getWeakRef(threadBeingCancelled);
trigger = false;
}
if (oldThread != null && oldThread != currentThread())
oldThread.join(cancelTimeOut);
pcallF(runnable);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
synchronized public void cancel() {
if (thread == null)
return;
threadBeingCancelled = new WeakReference(thread);
cancelAndInterruptThread(thread);
thread = null;
}
public void cancelAndTrigger() {
cancel();
trigger();
}
synchronized public boolean triggered() {
return trigger;
}
public void cleanMeUp() {
cancel();
}
public ReliableSingleThread cancelBeforeTrigger() {
cancelBeforeTrigger = true;
return this;
}
}
static public interface IVar extends IF0 {
public void set(A a);
public A get();
default public boolean has() {
return get() != null;
}
default public void clear() {
set(null);
}
}
static public class Flag implements Runnable {
public boolean up = false;
public synchronized boolean raise() {
if (!up) {
up = true;
notifyAll();
return true;
} else
return false;
}
public synchronized void waitUntilUp() {
while (!up) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void waitUntilUp(long timeout) {
if (!up) {
try {
wait(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized boolean isUp() {
return up;
}
public boolean get() {
return isUp();
}
public String toString() {
return isUp() ? "up" : "down";
}
public void waitForThisOr(Flag otherFlag) {
try {
while (!isUp() && !otherFlag.isUp()) Thread.sleep(50);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void run() {
raise();
}
}
static public boolean isAbstract(Class c) {
return (c.getModifiers() & Modifier.ABSTRACT) != 0;
}
static public boolean isAbstract(Method m) {
return (m.getModifiers() & Modifier.ABSTRACT) != 0;
}
static public boolean reflection_isForbiddenMethod(Method m) {
return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}
static public void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static public Set allInterfacesImplementedBy(Class c) {
if (c == null)
return null;
HashSet set = new HashSet();
allInterfacesImplementedBy_find(c, set);
return set;
}
static public void allInterfacesImplementedBy_find(Class c, Set set) {
if (c.isInterface() && !set.add(c))
return;
do {
for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set);
} while ((c = c.getSuperclass()) != null);
}
static public Method findMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args);
}
static public 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;
}
static public boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static public Method findStaticMethod(Class c, String method, Object... args) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (!m.getName().equals(method))
continue;
if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static public boolean findStaticMethod_checkArgs(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length)
return false;
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i])))
return false;
return true;
}
static public String dropTrailingBackslashR(String s) {
int i = l(s);
while (i > 0 && s.charAt(i - 1) == '\r') --i;
return substring(s, 0, i);
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public UnsupportedOperationException unsupportedOperation() {
throw new UnsupportedOperationException();
}
static public LinkedHashMap cloneLinkedHashMap(Map map) {
return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
}
static public A second(List l) {
return get(l, 1);
}
static public A second(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
if (!it.hasNext())
return null;
it.next();
return it.hasNext() ? it.next() : null;
}
static public A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static public char second(String s) {
return charAt(s, 1);
}
static public B second(Either e) {
return e == null ? null : e.bOpt();
}
static public int loadTextFilePart_iterator_chunkSize = 65536;
static public Iterable loadTextFilePart_iterator(File file, long start, long end) {
try {
if (end - start <= loadTextFilePart_iterator_chunkSize)
return ll(loadTextFilePart(file, start, end));
final FileInputStream in = newFileInputStream(file);
in.skip(start);
final byte[] buf = new byte[loadTextFilePart_iterator_chunkSize];
final UTF8Processor p = new UTF8Processor();
return iteratorFF(new F0() {
public Object get() {
try {
String s = readChunkThroughUTF8Processor(p, in, buf);
if (nempty(s))
return s;
in.close();
return endMarker();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S s = readChunkThroughUTF8Processor(p, in, buf);\r\n //print(\"Chunk read: \" ...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public FixedRateTimer doEvery(long delay, final Object r) {
return doEvery(delay, delay, r);
}
static public FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
return vmBus_timerStarted(timer);
}
static public FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
}
static public FixedRateTimer doEvery(double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), r);
}
static public boolean hasLock(Lock lock) {
return ((ReentrantLock) lock).isHeldByCurrentThread();
}
static public long sysNow() {
ping();
return System.nanoTime() / 1000000;
}
static public void clear(Collection c) {
if (c != null)
c.clear();
}
static public void clear(Map map) {
if (map != null)
map.clear();
}
static public Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static public Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static public Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static public Class _run(String progID, String... args) {
Class main = hotwire(progID);
callMain(main, args);
return main;
}
static public A getWeakRef(Reference ref) {
return ref == null ? null : ref.get();
}
static public void cancelAndInterruptThread(Thread t) {
if (t == null)
return;
cancelThread(t);
t.interrupt();
}
static public A set(A o, String field, Object value) {
if (o == null)
return null;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
static public void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static public Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static public Method findMethod_cached(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
_MethodCache cache = callOpt_getCache(((Class) o));
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
return m;
return null;
} else {
_MethodCache cache = callOpt_getCache(o.getClass());
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (findMethod_checkArgs(m, args, false))
return m;
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
static public char charAt(String s, int i) {
return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
}
static public String loadTextFilePart(File file, long start, long end) {
return fromUtf8(loadBinaryFilePart(file, start, end));
}
static public IterableIterator iteratorFF(Object f) {
return iteratorFromFunction_withEndMarker(f);
}
static public IterableIterator iteratorFF(F0 f) {
return iteratorFromFunction_withEndMarker(f);
}
static public String readChunkThroughUTF8Processor(UTF8Processor p, InputStream in, byte[] buf) {
try {
StringBuilder input = new StringBuilder();
int n = in.read(buf);
for (int i = 0; i < n; i++) input.append(p.processByte(buf[i]));
return input.toString();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object endMarker() {
return iteratorFromFunction_endMarker;
}
static public int shorten_default = 100;
static public String shorten(String s) {
return shorten(s, shorten_default);
}
static public String shorten(String s, int max) {
return shorten(s, max, "...");
}
static public 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;
}
static public String shorten(int max, String s) {
return shorten(s, max);
}
static public TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) {
return new SmartTimerTask(r, timer, delay, _threadInfo());
}
static public class SmartTimerTask extends TimerTask implements IFieldsToList {
public Object r;
public java.util.Timer timer;
public long delay;
public Object threadInfo;
public SmartTimerTask() {
}
public SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) {
this.threadInfo = threadInfo;
this.delay = delay;
this.timer = timer;
this.r = r;
}
public String toString() {
return shortClassName(this) + "(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")";
}
public Object[] _fieldsToList() {
return new Object[] { r, timer, delay, threadInfo };
}
public long lastRun;
public void run() {
if (!licensed())
timer.cancel();
else {
_threadInheritInfo(threadInfo);
AutoCloseable __1 = tempActivity(r);
try {
lastRun = fixTimestamp(lastRun);
long now = now();
if (now >= lastRun + delay * 0.9) {
lastRun = now;
if (eq(false, pcallF(r)))
timer.cancel();
}
} finally {
_close(__1);
}
}
}
}
static public A vmBus_timerStarted(A timer) {
vmBus_send("timerStarted", timer, costCenter());
return timer;
}
static public long toMS(double seconds) {
return (long) (seconds * 1000);
}
static public String defaultThreadName_name;
static public String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static public Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
static public Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static public Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
static public Map _registerThread_threads;
static public Object _onRegisterThread;
static public Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static public void _registerThread() {
_registerThread(Thread.currentThread());
}
static public Class> hotwire(String src) {
assertFalse(_inCore());
Class j = getJavaX();
if (isAndroid()) {
synchronized (j) {
List libraries = new ArrayList();
File srcDir = (File) call(j, "transpileMain", src, libraries);
if (srcDir == null)
throw fail("transpileMain returned null (src=" + quote(src) + ")");
Object androidContext = get(j, "androidContext");
return (Class) call(j, "loadx2android", srcDir, src);
}
} else {
Class c = (Class) (call(j, "hotwire", src));
hotwire_copyOver(c);
return c;
}
}
static public A callMain(A c, String... args) {
callOpt(c, "main", new Object[] { args });
return c;
}
static public void callMain() {
callMain(mc());
}
static public void cancelThread(Thread t) {
if (t == null)
return;
ping();
synchronized (ping_actions) {
ping_actions.put(t, "cancelled");
ping_anyActions = true;
}
}
static public void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
if (type == int.class && value instanceof Long)
value = ((Long) value).intValue();
if (type == LinkedHashMap.class && value instanceof Map) {
f.set(o, asLinkedHashMap((Map) value));
return;
}
try {
if (f.getType() == Concept.Ref.class) {
f.set(o, ((Concept) o).new Ref((Concept) value));
return;
}
if (o instanceof Concept.Ref) {
f.set(o, ((Concept.Ref) o).get());
return;
}
} catch (Throwable _e) {
}
throw e;
}
}
static public Object iteratorFromFunction_endMarker = new Object();
static public IterableIterator iteratorFromFunction_withEndMarker(final Object f) {
class IFF extends IterableIterator {
public A a;
public boolean have, done;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
have = false;
return _a;
}
public void getNext() {
if (done || have)
return;
Object o = callF(f);
if (o == iteratorFromFunction_endMarker) {
done = true;
return;
}
a = (A) o;
have = true;
}
}
;
return new IFF();
}
static public IterableIterator iteratorFromFunction_withEndMarker(final F0 f) {
return iteratorFromFunction_withEndMarker_f0(f);
}
static public String fromUtf8(byte[] bytes) {
try {
return bytes == null ? null : new String(bytes, "UTF-8");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] loadBinaryFilePart(File file, long start, long end) {
try {
RandomAccessFile raf = new RandomAccessFile(file, "r");
int n = toInt(min(raf.length(), end - start));
byte[] buffer = new byte[n];
try {
raf.seek(start);
raf.readFully(buffer, 0, n);
return buffer;
} finally {
raf.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public int min(int a, int b) {
return Math.min(a, b);
}
static public long min(long a, long b) {
return Math.min(a, b);
}
static public float min(float a, float b) {
return Math.min(a, b);
}
static public float min(float a, float b, float c) {
return min(min(a, b), c);
}
static public double min(double a, double b) {
return Math.min(a, b);
}
static public double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static public float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static public byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
static public short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
static public int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
static public String shortClassName(Object o) {
if (o == null)
return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
static public AutoCloseable tempActivity(Object r) {
return null;
}
static public long fixTimestamp(long timestamp) {
return timestamp > now() ? 0 : timestamp;
}
static public Object costCenter() {
return mc();
}
static public Runnable _topLevelErrorHandling(final Runnable runnable) {
final Object info = _threadInfo();
return new Runnable() {
public void run() {
try {
try {
_threadInheritInfo(info);
runnable.run();
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }";
}
};
}
static public WeakReference weakRef(A a) {
return newWeakReference(a);
}
static public boolean _inCore() {
return false;
}
static public List hotwire_copyOver_after = synchroList();
static public void hotwire_copyOver(Class c) {
for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field));
setOptIfNotNull(c, "mainBot", getMainBot());
setOpt(c, "creator_class", new WeakReference(mc()));
pcallFAll(hotwire_copyOver_after, c);
}
static public LinkedHashMap asLinkedHashMap(Map map) {
if (map instanceof LinkedHashMap)
return (LinkedHashMap) map;
LinkedHashMap m = new LinkedHashMap();
if (map != null)
synchronized (collectionMutex(map)) {
m.putAll(map);
}
return m;
}
static public IterableIterator iteratorFromFunction_withEndMarker_f0(final F0 f) {
class IFF2 extends IterableIterator {
public A a;
public boolean have, done;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
have = false;
return _a;
}
public void getNext() {
if (done || have)
return;
Object o = f.get();
if (o == iteratorFromFunction_endMarker) {
done = true;
return;
}
a = (A) o;
have = true;
}
}
;
return new IFF2();
}
static public String shortenClassName(String name) {
if (name == null)
return null;
int i = lastIndexOf(name, "$");
if (i < 0)
i = lastIndexOf(name, ".");
return i < 0 ? name : substring(name, i + 1);
}
static public WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
static public void setOptIfNotNull(Object o, String field, Object value) {
if (value != null)
setOpt(o, field, value);
}
static public Object mainBot;
static public Object getMainBot() {
return mainBot;
}
static public int lastIndexOf(String a, String b) {
return a == null || b == null ? -1 : a.lastIndexOf(b);
}
static public int lastIndexOf(String a, char b) {
return a == null ? -1 : a.lastIndexOf(b);
}
static public int lastIndexOf(List l, int i, A a) {
if (l == null)
return -1;
for (i = min(l(l), i) - 1; i >= 0; i--) if (eq(l.get(i), a))
return i;
return -1;
}
static public interface IFieldsToList {
public Object[] _fieldsToList();
}
static public class UTF8Processor {
public byte[] buffer = new byte[5];
public int count = 0;
public String processByte(byte nextByte) {
try {
buffer[count++] = nextByte;
if (count == expectedBytes()) {
String result = new String(buffer, 0, count, "UTF-8");
count = 0;
return result;
}
return "";
} catch (Exception __e) {
throw rethrow(__e);
}
}
public int expectedBytes() {
int num = buffer[0] & 255;
if (num < 0x80)
return 1;
if (num < 0xe0)
return 2;
if (num < 0xf0)
return 3;
if (num < 0xf8)
return 4;
return 5;
}
}
static public class FixedRateTimer extends java.util.Timer {
public FixedRateTimer() {
this(false);
}
public FixedRateTimer(boolean daemon) {
this(defaultTimerName(), daemon);
}
public FixedRateTimer(String name) {
this(name, false);
}
public FixedRateTimer(String name, boolean daemon) {
super(name, daemon);
_registerTimer(this);
}
public List entries = synchroList();
static public class Entry implements IFieldsToList {
public TimerTask task;
public long firstTime;
public long period;
public Entry() {
}
public Entry(TimerTask task, long firstTime, long period) {
this.period = period;
this.firstTime = firstTime;
this.task = task;
}
public String toString() {
return shortClassName(this) + "(" + task + ", " + firstTime + ", " + period + ")";
}
public Object[] _fieldsToList() {
return new Object[] { task, firstTime, period };
}
}
public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
entries.add(new Entry(task, now() + delay, period));
super.scheduleAtFixedRate(task, delay, period);
}
public void cancel() {
entries.clear();
super.cancel();
}
public int purge() {
entries.clear();
return super.purge();
}
public FixedRateTimer changeRate(int newPeriod) {
Object r = ((SmartTimerTask) first(entries).task).r;
cancel();
return doEvery(newPeriod, r);
}
}
static public JPanel centerAndSouthWithMargins(Component c, Component s) {
return applyDefaultMargin(centerAndSouth(c, withTopMargin(s)));
}
static public JPanel jrightalignedline(Component... components) {
return jrightAlignedLine(components);
}
static public JPanel jrightalignedline(List components) {
return jrightAlignedLine(components);
}
static public JCheckBox dm_fieldCheckBox(String field) {
return dm_fieldCheckBox(humanizeFormLabel(field), field);
}
static public JCheckBox dm_fieldCheckBox(String text, String field) {
if (isIdentifier(text) && !isIdentifier(field)) {
String temp = field;
field = text;
text = temp;
}
return jLiveValueCheckBox(text, dm_fieldLiveValue(field));
}
static public String defaultTimerName_name;
static public String defaultTimerName() {
if (defaultTimerName_name == null)
defaultTimerName_name = "A timer by " + programID();
return defaultTimerName_name;
}
static public Set _registerTimer_list = newWeakHashSet();
static public void _registerTimer(java.util.Timer timer) {
_registerTimer_list.add(timer);
}
static public void cleanMeUp__registerTimer() {
cancelTimers(getAndClearList(_registerTimer_list));
}
static public A applyDefaultMargin(final A c) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMarg...";
}
});
}
return c;
}
static public JPanel centerAndSouth(final Component c, final Component s) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
if (s != null)
panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT...";
}
});
}
static public int withTopMargin_defaultWidth = 6;
static public JPanel withTopMargin(Component c) {
return withTopMargin(withTopMargin_defaultWidth, c);
}
static public JPanel withTopMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
static public JPanel jrightAlignedLine(final Component... components) {
return swing(new F0() {
public RightAlignedLine get() {
try {
return new RightAlignedLine(components);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret RightAlignedLine(components);";
}
});
}
static public JPanel jrightAlignedLine(List extends Component> components) {
return jrightAlignedLine(asArray(Component.class, components));
}
static public Map humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5");
static public String humanizeFormLabel(String s) {
if (containsSpace(s))
return s;
return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID"));
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public JCheckBox jLiveValueCheckBox(String text, final SimpleLiveValue lv) {
final JCheckBox cb = jCheckBox(text);
bindCheckBoxToLiveValue(cb, lv);
return cb;
}
static public SimpleLiveValue dm_fieldLiveValue(String fieldName) {
return dm_fieldLiveValue(dm_current_mandatory(), fieldName);
}
static public SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
Lock __0 = module.lock;
lock(__0);
try {
AutoCloseable __2 = module.enter();
try {
Class type = getFieldType(module, fieldName);
final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName));
dm_watchField(fieldName, new Runnable() {
public void run() {
try {
Object o = get(module, fieldName);
value.set(o);
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting \" + fi...";
}
});
value.onChange(new Runnable() {
public void run() {
try {
module.setField(fieldName, value.get());
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting 2 \" + ...";
}
});
return value;
} finally {
_close(__2);
}
} finally {
unlock(__0);
}
}
static public void cancelTimers(Collection timers) {
for (Object timer : timers) cancelTimer(timer);
}
static public Object[] asArray(List l) {
return toObjectArray(l);
}
static public A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static public HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static public void litmap_impl(Map map, Object... x) {
if (x != null)
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
static public boolean containsSpace(String s) {
return containsSpaces(s);
}
static public String firstToUpper(String s) {
if (empty(s))
return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
static public List replaceElementsUsingMap(Iterable l, final Map map) {
return map(l, new F1 () {
public A get(A a) {
try {
return getOrKeep(map, a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "getOrKeep(map, a)";
}
});
}
static public List splitCamelCase(String s) {
return ai_splitCamelCase(s);
}
static public boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static public JCheckBox jCheckBox() {
return swingNu(JCheckBox.class);
}
static public JCheckBox jCheckBox(boolean checked) {
return swingNu(JCheckBox.class, "", checked);
}
static public JCheckBox jCheckBox(String text, boolean checked) {
return swingNu(JCheckBox.class, text, checked);
}
static public JCheckBox jCheckBox(String text) {
return swingNu(JCheckBox.class, text);
}
static public JCheckBox jCheckBox(String text, boolean checked, final Object onChange) {
JCheckBox cb = jCheckBox(checked, onChange);
cb.setText(text);
return cb;
}
static public JCheckBox jCheckBox(boolean checked, final Object onChange) {
final JCheckBox cb = jCheckBox(checked);
cb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(onChange, cb.isSelected());
}
});
return cb;
}
static public A bindCheckBoxToLiveValue(final A cb, final SimpleLiveValue lv) {
bindLiveValueListenerToComponent(cb, lv, new Runnable() {
public void run() {
try {
setChecked(cb, isTrue(lv.get()));
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se...";
}
});
onChange(cb, new Runnable() {
public void run() {
try {
lv.set(isChecked(cb));
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se...";
}
});
return cb;
}
static public Class getFieldType(Object o, String field) {
return fieldType(o, field);
}
static public void dm_watchField(String field, Runnable onChange) {
new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange);
}
static public void cancelTimer(javax.swing.Timer timer) {
if (timer != null)
timer.stop();
}
static public void cancelTimer(java.util.Timer timer) {
if (timer != null)
timer.cancel();
}
static public void cancelTimer(Object o) {
if (o instanceof java.util.Timer)
cancelTimer((java.util.Timer) o);
else if (o instanceof javax.swing.Timer)
cancelTimer((javax.swing.Timer) o);
else if (o instanceof AutoCloseable) {
try {
((AutoCloseable) o).close();
} catch (Throwable __e) {
_handleException(__e);
}
}
}
static public Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static public boolean containsSpaces(String s) {
return indexOf(s, ' ') >= 0;
}
static public List map(Iterable l, Object f) {
return map(f, l);
}
static public List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
static public List map(Iterable l, F1 f) {
return map(f, l);
}
static public List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(callF(f, o));
return x;
}
static public List map(IF1 f, Iterable l) {
return map(l, f);
}
static public List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(IF1 f, A[] l) {
return map(l, f);
}
static public List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static public A getOrKeep(Map map, A a) {
if (map == null)
return a;
A v = map.get(a);
return v != null ? v : a;
}
static public List ai_splitCamelCase(String s) {
int j = 0;
List l = new ArrayList();
if (isAllUpperCase(s)) {
l.add(s);
return l;
}
for (int i = 0; i < l(s); i++) if (i > j && isUpperCaseLetter(s.charAt(i))) {
l.add(substring(s, j, i));
j = i;
}
if (j < l(s))
l.add(substring(s, j));
return l;
}
static public 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;
}
static public void setChecked(JCheckBox checkBox, boolean b) {
if (checkBox != null) {
swing(new Runnable() {
public void run() {
try {
if (isChecked(checkBox) != b)
checkBox.setSelected(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (isChecked(checkBox) != b)\r\n checkBox.setSelected(b);";
}
});
}
}
static public void setChecked(JCheckBoxMenuItem mi, boolean b) {
if (mi != null) {
swing(new Runnable() {
public void run() {
try {
mi.setSelected(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "mi.setSelected(b);";
}
});
}
}
static public A onChange(A spinner, Object r) {
{
swing(new Runnable() {
public void run() {
try {
spinner.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "spinner.addChangeListener(changeListener(r));";
}
});
}
return spinner;
}
static public A onChange(A b, Object r) {
{
swing(new Runnable() {
public void run() {
try {
b.addItemListener(itemListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "b.addItemListener(itemListener(r));";
}
});
}
return b;
}
static public void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
static public A onChange(A slider, final Object r) {
{
swing(new Runnable() {
public void run() {
try {
slider.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "slider.addChangeListener(changeListener(r));";
}
});
}
return slider;
}
static public JComboBox onChange(Object r, JComboBox cb) {
return onChange(cb, r);
}
static public JComboBox onChange(JComboBox cb, final Object r) {
if (isEditableComboBox(cb))
onChange(textFieldFromComboBox(cb), r);
else
onSelectedItem(cb, new VF1() {
public void get(String s) {
try {
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r)";
}
});
return cb;
}
static public 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();";
}
});
}
static public 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();";
}
});
}
static public boolean isAllUpperCase(String s) {
return hasLettersAllUpperCase(s);
}
static public boolean isUpperCaseLetter(char c) {
return Character.isUpperCase(c);
}
static public ChangeListener changeListener(final Object r) {
return new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(r);
}
};
}
static public ItemListener itemListener(final Object r) {
return new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pcallF(r);
}
};
}
static public void onUpdate(JComponent c, final Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
call(r);
}
public void removeUpdate(DocumentEvent e) {
call(r);
}
public void changedUpdate(DocumentEvent e) {
call(r);
}
});
else if (c instanceof ItemSelectable)
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
call(r);
}
});
else
print("Warning: onUpdate doesn't know " + getClassName(c));
}
static public void onUpdate(List extends JComponent> l, Object r) {
for (JComponent c : l) onUpdate(c, r);
}
static public 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();";
}
});
}
static public JTextField textFieldFromComboBox(JComboBox cb) {
return (JTextField) cb.getEditor().getEditorComponent();
}
static public JComboBox onSelectedItem(final JComboBox cb, final VF1 f) {
addActionListener(cb, new Runnable() {
public void run() {
try {
pcallF(f, selectedItem(cb));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcallF(f, selectedItem(cb))";
}
});
return cb;
}
static public boolean hasLettersAllUpperCase(String s) {
return hasLetters(s) && !containsLowerCase(s);
}
static public void addActionListener(JTextField tf, final Runnable action) {
onEnter(tf, action);
}
static public 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));";
}
});
}
}
static public 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));";
}
});
}
}
static public String selectedItem(JList l) {
return getSelectedItem(l);
}
static public String selectedItem(JComboBox cb) {
return getSelectedItem(cb);
}
static public boolean hasLetters(String s) {
for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i)))
return true;
return false;
}
static public boolean containsLowerCase(String s) {
for (int i = 0; i < l(s); i++) if (isLowerCase(s.charAt(i)))
return true;
return false;
}
static public boolean isLowerCase(char c) {
return Character.isLowerCase(c);
}
static public class SimpleLiveValue extends LiveValue {
public Class type;
volatile public A value;
transient public List onChange = synchroList();
public SimpleLiveValue(Class type) {
this.type = type;
}
public SimpleLiveValue(Class type, A value) {
this.value = value;
this.type = type;
}
public Class getType() {
return type;
}
public A get() {
return value;
}
public void onChange(Runnable l) {
onChange.add(l);
}
public void onChangeAndNow(Runnable l) {
onChange(l);
callF(l);
}
public void removeOnChangeListener(Runnable l) {
onChange.remove(l);
}
public void fireChanged() {
pcallFAll(onChange);
}
public void set(A a) {
if (neq(value, a)) {
value = a;
fireChanged();
}
}
}
static public interface IF2 {
public C get(A a, B b);
}
static abstract public class LiveValue {
abstract public Class getType();
abstract public A get();
abstract public void onChange(Runnable l);
abstract public void removeOnChangeListener(Runnable l);
public void onChangeAndNow(Runnable l) {
onChange(l);
callF(l);
}
}
static public class Dyn_FieldWatcher {
public DynModule module;
public String field;
public Object value;
public Runnable action;
transient public IF1 cloneValue;
public Object cloneValue(Object o) {
return cloneValue != null ? cloneValue.get(o) : cloneValue_base(o);
}
final public Object cloneValue_fallback(IF1 _f, Object o) {
return _f != null ? _f.get(o) : cloneValue_base(o);
}
public Object cloneValue_base(Object o) {
return o;
}
public Dyn_FieldWatcher(DynModule module, String field, Runnable action) {
this(module, field, action, null);
}
public Dyn_FieldWatcher(DynModule module, String field, Runnable action, IF1 cloneValue) {
this.cloneValue = cloneValue;
this.action = action;
this.field = field;
this.module = module;
value = cloneValue(get(module, field));
module.onChange(new Runnable() {
public void run() {
try {
check();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "check();";
}
});
module.onFieldChange(new VF1() {
public void get(String f) {
try {
if (eq(f, field))
check();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(f, field))\r\n check();";
}
});
}
public void check() {
Object newValue = cloneValue(get(module, field));
if (eq(value, newValue))
return;
value = newValue;
dm_q(module, action);
}
}
static public class RightAlignedLine extends JPanel {
public RightAlignedLine(Component... components) {
setLayout(LetterLayout.rightAlignedRow());
for (Component component : components) add(component);
}
public void add(String text) {
add(new JLabel(text));
}
}
static public class LetterLayout implements LayoutManager {
public String[] lines;
public Map map = new TreeMap();
public RC[] rows;
public RC[] cols;
public Cell[][] cells;
public int spacingX = 10, spacingY = 10;
public int insetTop, insetBottom, insetLeft, insetRight;
public int template;
public boolean formWideLeftSide, formWideRightSide;
static final public int STALACTITE = 1, LEFT_ALIGNED_ROW = 2, CENTERED_ROW = 3, FORM = 4, RIGHT_ALIGNED_ROW = 5;
public boolean debug = false;
public void setLeftBorder(int border) {
insetLeft = border;
}
public void setRightBorder(int border) {
insetRight = border;
}
public static JComponent withBorder(JComponent component, int border) {
JPanel panel = new JPanel(new LetterLayout("C").setBorder(border));
panel.add("C", component);
return panel;
}
public static JPanel panel(String... lines) {
return new JPanel(new LetterLayout(lines));
}
public static JPanel stalactitePanel() {
return new JPanel(stalactite());
}
static public class DummyComponent extends JComponent {
}
static public class Cell {
public boolean aux = false;
public int minWidth, minHeight;
public Component component;
public int colspan, rowspan;
public double weightX, weightY;
}
static public class RC {
public int min;
public double weightSum;
public int start;
public int minEnd;
}
public LetterLayout(int template) {
this.template = template;
}
public LetterLayout(String... lines) {
this.lines = lines;
}
public void removeLayoutComponent(Component component) {
map.values().remove(component);
}
public void layoutContainer(Container container) {
prepareLayout(container);
if (debug)
System.out.println("Container size: " + container.getSize());
Insets insets = getInsets(container);
for (int r = 0; r < rows.length; r++) {
for (int i = 0; i < cols.length; ) {
Cell cell = cells[i][r];
if (cell.aux)
++i;
else {
if (cell.component != null) {
int x1 = cols[i].start;
int y1 = rows[r].start;
int x2 = i + cell.colspan < cols.length ? cols[i + cell.colspan].start - spacingX : container.getWidth() - insets.right;
int y2 = r + cell.rowspan < rows.length ? rows[r + cell.rowspan].start - spacingY : container.getHeight() - insets.bottom;
if (debug)
System.out.println("Layouting (" + i + ", " + r + ", " + cell.component.getClass().getName() + "): " + x1 + " " + y1 + " " + x2 + " " + y2);
cell.component.setBounds(x1, y1, x2 - x1, y2 - y1);
}
i += cells[i][r].colspan;
}
}
}
}
final public void prepareLayout(Container container) {
applyTemplate(container);
int numRows = lines.length, numCols = lines[0].length();
for (int i = 1; i < numRows; i++) if (lines[i].length() != numCols)
throw new IllegalArgumentException("Lines have varying length");
cells = new Cell[numCols][numRows];
rows = new RC[numRows];
cols = new RC[numCols];
for (int r = 0; r < numRows; r++) rows[r] = new RC();
for (int i = 0; i < numCols; i++) cols[i] = new RC();
for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r] = new Cell();
for (int r = 0; r < numRows; r++) {
String line = lines[r];
for (int i = 0; i < numCols; ) {
Cell cell = cells[i][r];
if (cell.aux) {
++i;
continue;
}
char ch = line.charAt(i);
int iNext = i;
do ++iNext; while (iNext < numCols && ch == line.charAt(iNext));
int rNext = r;
do ++rNext; while (rNext < numRows && ch == lines[rNext].charAt(i));
cell.weightX = numCols == 1 || iNext > i + 1 ? 1.0 : 0.0;
cell.weightY = numRows == 1 || rNext > r + 1 ? 1.0 : 0.0;
Component c = map.get(String.valueOf(ch));
cell.component = c;
if (c != null) {
cell.minWidth = c.getMinimumSize().width + spacingX;
cell.minHeight = getMinimumHeight(c) + spacingY;
}
cell.colspan = iNext - i;
cell.rowspan = rNext - r;
if (cell.colspan == 1)
cols[i].min = Math.max(cols[i].min, cell.minWidth);
if (cell.rowspan == 1)
rows[r].min = Math.max(rows[r].min, cell.minHeight);
for (int r2 = r; r2 < rNext; r2++) for (int i2 = i; i2 < iNext; i2++) if (r2 != r || i2 != i)
cells[i2][r2].aux = true;
i = iNext;
}
}
while (true) {
for (int i = 0; i < numCols; i++) {
int minStart = i == 0 ? 0 : cols[i - 1].minEnd;
double weightStart = i == 0 ? 0.0 : cols[i - 1].weightSum;
for (int r = 0; r < numRows; r++) {
Cell cell = cells[i][r];
if (!cell.aux) {
RC rc = cols[i + cell.colspan - 1];
rc.minEnd = Math.max(rc.minEnd, minStart + cell.minWidth);
rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightX);
}
}
}
for (int r = 0; r < numRows; r++) {
int minStart = r == 0 ? 0 : rows[r - 1].minEnd;
double weightStart = r == 0 ? 0.0 : rows[r - 1].weightSum;
for (int i = 0; i < numCols; i++) {
Cell cell = cells[i][r];
if (!cell.aux) {
RC rc = rows[r + cell.rowspan - 1];
rc.minEnd = Math.max(rc.minEnd, minStart + cell.minHeight);
rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightY);
}
}
}
if (allWeightsZero(cols)) {
for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightX = 1.0;
continue;
}
if (allWeightsZero(rows)) {
for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightY = 1.0;
continue;
}
break;
}
Insets insets = getInsets(container);
determineStarts(cols, insets.left, container.getWidth() - insets.left - insets.right + spacingX, spacingX);
determineStarts(rows, insets.top, container.getHeight() - insets.top - insets.bottom + spacingY, spacingY);
}
final public boolean allWeightsZero(RC[] rcs) {
for (int i = 0; i < rcs.length; i++) if (rcs[i].weightSum != 0.0)
return false;
return true;
}
static public int getMinimumHeight(Component c) {
return c.getMinimumSize().height;
}
final public void applyTemplate(Container container) {
if (template == STALACTITE) {
Component[] components = container.getComponents();
lines = new String[components.length + 2];
map.clear();
for (int i = 0; i < components.length; i++) {
String s = String.valueOf(makeIndexChar(i));
map.put(s, components[i]);
lines[i] = s;
}
lines[components.length] = lines[components.length + 1] = " ";
} else if (template == FORM) {
Component[] components = container.getComponents();
int numRows = components.length / 2;
lines = new String[numRows + 2];
map.clear();
for (int row = 0; row < numRows; row++) {
String lower = String.valueOf(makeIndexChar(row));
String upper = String.valueOf(makeAlternateIndexChar(row));
Component rightComponent = components[row * 2 + 1];
if (rightComponent instanceof DummyComponent)
upper = lower;
lines[row] = (formWideLeftSide ? lower + lower : lower) + (formWideRightSide ? upper + upper : upper);
map.put(lower, components[row * 2]);
if (!(rightComponent instanceof DummyComponent))
map.put(upper, rightComponent);
}
lines[numRows] = lines[numRows + 1] = (formWideLeftSide ? " " : " ") + (formWideRightSide ? " " : " ");
} else if (template == LEFT_ALIGNED_ROW) {
lines = new String[] { makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
} else if (template == CENTERED_ROW) {
lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
} else if (template == RIGHT_ALIGNED_ROW) {
lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) };
}
}
final public String makeSingleRow(Container container) {
Component[] components = container.getComponents();
StringBuffer buf = new StringBuffer();
map.clear();
for (int i = 0; i < components.length; i++) {
String s = String.valueOf(makeAlternateIndexChar(i));
map.put(s, components[i]);
buf.append(s);
}
return buf.toString();
}
static public void determineStarts(RC[] rcs, int start, int totalSize, int spacing) {
int minTotal = rcs[rcs.length - 1].minEnd;
double weightSum = rcs[rcs.length - 1].weightSum;
int spare = (int) ((totalSize - minTotal) / (weightSum == 0.0 ? 1.0 : weightSum));
int x = start, minSum = 0;
double prevWeightSum = 0.0;
for (int i = 0; i < rcs.length; i++) {
int width = rcs[i].minEnd - minSum + (int) ((rcs[i].weightSum - prevWeightSum) * spare) - spacing;
rcs[i].start = x;
x += width + spacing;
prevWeightSum = rcs[i].weightSum;
minSum = rcs[i].minEnd;
}
}
public void addLayoutComponent(String s, Component component) {
map.put(s, component);
}
public Dimension minimumLayoutSize(Container container) {
prepareLayout(container);
Insets insets = getInsets(container);
Dimension result = new Dimension(insets.left + cols[cols.length - 1].minEnd + insets.right - spacingX, insets.top + rows[rows.length - 1].minEnd + insets.bottom - spacingY);
return result;
}
final public Insets getInsets(Container container) {
Insets insets = container.getInsets();
return new Insets(insets.top + insetTop, insets.left + insetLeft, insets.bottom + insetBottom, insets.right + insetRight);
}
public Dimension preferredLayoutSize(Container container) {
return minimumLayoutSize(container);
}
public LetterLayout setSpacing(int x, int y) {
spacingX = x;
spacingY = y;
return this;
}
public LetterLayout setSpacing(int spacing) {
return setSpacing(spacing, spacing);
}
public LetterLayout setBorder(int top, int left, int bottom, int right) {
insetTop = top;
insetLeft = left;
insetBottom = bottom;
insetRight = right;
return this;
}
public LetterLayout setBorder(int inset) {
return setBorder(inset, inset, inset, inset);
}
public LetterLayout setTopBorder(int inset) {
insetTop = inset;
return this;
}
public static LetterLayout stalactite() {
return new LetterLayout(STALACTITE);
}
public static LetterLayout leftAlignedRow() {
return new LetterLayout(LEFT_ALIGNED_ROW);
}
public static LetterLayout leftAlignedRow(int spacing) {
return leftAlignedRow().setSpacing(spacing);
}
public static LetterLayout centeredRow() {
return new LetterLayout(CENTERED_ROW);
}
public static LetterLayout rightAlignedRow() {
return new LetterLayout(RIGHT_ALIGNED_ROW);
}
public static JPanel rightAlignedRowPanel(JComponent... components) {
return makePanel(new LetterLayout(RIGHT_ALIGNED_ROW), components);
}
static public JPanel makePanel(LetterLayout letterLayout, JComponent[] components) {
JPanel panel = new JPanel(letterLayout);
for (JComponent component : components) {
panel.add(component);
}
return panel;
}
public static LetterLayout form() {
LetterLayout letterLayout = new LetterLayout(FORM);
letterLayout.formWideLeftSide = true;
letterLayout.formWideRightSide = true;
return letterLayout;
}
public static LetterLayout formWideRightSide() {
LetterLayout letterLayout = new LetterLayout(FORM);
letterLayout.formWideRightSide = true;
return letterLayout;
}
public static Component getDummyComponent() {
return new DummyComponent();
}
public static JPanel newPanel(String... lines) {
return new JPanel(new LetterLayout(lines));
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public static char makeIndexChar(int idx) {
return (char) ('a' + idx * 2);
}
public static char makeAlternateIndexChar(int idx) {
return (char) ('b' + idx * 2);
}
public static char LEFT_CHAR = ',', RIGHT_CHAR = '.';
public static void main(String[] args) {
System.out.println((int) makeIndexChar(0));
System.out.println((int) makeAlternateIndexChar(0));
System.out.println((int) makeIndexChar(32000));
System.out.println((int) makeAlternateIndexChar(32000));
System.out.println((int) LEFT_CHAR);
System.out.println((int) RIGHT_CHAR);
}
}
static public Q dm_q() {
return dm_current_mandatory().q();
}
static public void dm_q(Runnable r) {
dm_inQ(r);
}
static public void dm_q(DynModule module, Runnable r) {
module.q().add(r);
}
static public A dm_q(IF0 f) {
return dm_evalInQ(if0ToF0(f));
}
static public void add(BitSet bs, int i) {
bs.set(i);
}
static public boolean add(Collection c, A a) {
return c != null && c.add(a);
}
static public void add(Container c, Component x) {
addToContainer(c, x);
}
static public void dm_inQ(Runnable r) {
dm_q().add(r);
}
static public A dm_evalInQ(F0 f) {
return dm_evalInQ(dm_current_mandatory(), f);
}
static public A dm_evalInQ(IF0 f) {
return dm_evalInQ(dm_current_mandatory(), if0ToF0(f));
}
static public A dm_evalInQ(DynModule module, F0 f) {
return evalInQ(module.q(), f);
}
static public F0 if0ToF0(IF0 f) {
return f == null ? null : new F0 () {
public A get() {
try {
return f.get();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret f.get();";
}
};
}
static public void addToContainer(final Container a, final Component b) {
if (a != null && b != null) {
swing(new Runnable() {
public void run() {
try {
a.add(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.add(b);";
}
});
}
}
static public A evalInQ(Q q, final F0 f) {
if (isInQ(q))
return callF(f);
final Var> var = new Var();
q.add(new Runnable() {
public void run() {
try {
try {
var.set(main.eitherA(callF(f)));
} catch (Throwable e) {
var.set(main. eitherB(e));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "try {\r\n var.set(main. eitherA(callF(f)));\r\n } catch (Th...";
}
});
return returnOrThrow_either(waitForVarToBeNotNull(var));
}
static public boolean isInQ(Q q) {
return q != null && isCurrentThread(q.rst.thread);
}
static public Either eitherA(A a) {
return new Either(1, a);
}
static public Either eitherB(B b) {
return new Either(2, b);
}
static public A returnOrThrow_either(Either e) {
if (isEitherB(e))
throw rethrow(e.b());
return eitherAOpt(e);
}
static public A waitForVarToBeNotNull(Var v) {
try {
synchronized (v) {
while (!v.has()) v.wait();
return v.get();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isCurrentThread(Thread t) {
return t != null && t == currentThread();
}
static public boolean isEitherB(Either e) {
return eitherIsB(e);
}
static public A eitherAOpt(Either e) {
return e != null && e.isA() ? e.a() : null;
}
static public boolean eitherIsB(Either e) {
return e != null && e.isB();
}
static public class Either {
public byte which;
public Object value;
public Either() {
}
public Either(int which, Object value) {
this.which = (byte) which;
this.value = value;
}
public boolean isA() {
return which == 1;
}
public boolean isB() {
return which == 2;
}
public A a() {
if (which != 1)
_failMe();
return (A) value;
}
public B b() {
if (which != 2)
_failMe();
return (B) value;
}
public A aOpt() {
return which != 1 ? null : (A) value;
}
public B bOpt() {
return which != 2 ? null : (B) value;
}
public void _failMe() {
throw fail("Either object is of wrong type: " + shortClassName(value));
}
public String toString() {
return "Either" + (isA() ? "A" : "B") + "(" + value + ")";
}
}
static public String b(Object contents, Object... params) {
return tag("b", contents, params);
}
static public boolean isA(Either e) {
return eitherIsA(e);
}
static public String tag(String tag) {
return htag(tag);
}
static public String tag(String tag, Object contents, Object... params) {
return htag(tag, str(contents), params);
}
static public String tag(String tag, StringBuilder contents, Object... params) {
return htag(tag, contents, params);
}
static public String tag(String tag, StringBuffer contents, Object... params) {
return htag(tag, contents, params);
}
static public boolean eitherIsA(Either e) {
return e != null && e.isA();
}
static public String htag(String tag) {
return htag(tag, "");
}
static public String htag(String tag, Object contents, Object... params) {
String openingTag = hopeningTag(tag, params);
String s = str(contents);
if (empty(s) && neqic(tag, "script"))
return dropLast(openingTag) + "/>";
return openingTag + s + "" + tag + ">";
}
static public String hopeningTag(String tag, Map params) {
return hopeningTag(tag, mapToParams(params));
}
static public String hopeningTag(String tag, Object... params) {
StringBuilder buf = new StringBuilder();
buf.append("<" + tag);
for (int i = 0; i < l(params); i += 2) {
String name = (String) get(params, i);
Object val = get(params, i + 1);
if (nempty(name) && val != null) {
if (val == html_valueLessParam())
buf.append(" " + name);
else {
String s = str(val);
if (!empty(s))
buf.append(" " + name + "=" + htmlQuote(s));
}
}
}
buf.append(">");
return str(buf);
}
static public boolean neqic(String a, String b) {
return !eqic(a, b);
}
static public boolean neqic(char a, char b) {
return !eqic(a, b);
}
static public Object[] mapToParams(Map map) {
return mapToObjectArray(map);
}
static public Object html_valueLessParam_cache;
static public Object html_valueLessParam() {
if (html_valueLessParam_cache == null)
html_valueLessParam_cache = html_valueLessParam_load();
return html_valueLessParam_cache;
}
static public Object html_valueLessParam_load() {
return new Object();
}
static public String htmlQuote(String s) {
return "\"" + htmlencode_forParams(s) + "\"";
}
static public Object[] mapToObjectArray(Map map) {
List l = new ArrayList();
for (Object o : keys(map)) {
l.add(o);
l.add(map.get(o));
}
return toObjectArray(l);
}
static public Object[] mapToObjectArray(Object f, Collection l) {
int n = l(l);
Object[] array = new Object[n];
if (n != 0) {
Iterator it = iterator(l);
for (int i = 0; i < n; i++) array[i] = callF(f, it.next());
}
return array;
}
static public Object[] mapToObjectArray(Object f, Object[] l) {
int n = l(l);
Object[] array = new Object[n];
for (int i = 0; i < n; i++) array[i] = callF(f, l[i]);
return array;
}
static public Object[] mapToObjectArray(Collection l, IF1 f) {
return mapToObjectArray(f, l);
}
static public String htmlencode_forParams(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 == '>') {
out.append("");
out.append((int) c);
out.append(';');
} else
out.append(c);
}
return out.toString();
}
}