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;
}
static boolean startsWithAndEndsWith(String s, String prefix, String suffix) {
return startsWith(s, prefix) && endsWith(s, suffix);
}
static boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static boolean containsNewLines(String s) {
return containsNewLine(s);
}
static String jlabel_textAsHTML_center(String text) {
return ""
+ replace(htmlencode(text), "\n", " ")
+ "
";
}
//static final Map> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init);
static class getOpt_Map extends WeakHashMap {
getOpt_Map() {
if (getOpt_special == null) getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
//print("getOpt clear");
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
//static final Map> getOpt_cache = _registerWeakMap(synchroMap(new getOpt_Map));
static HashMap getOpt_special; // just a marker
/*static void getOpt_special_init(Map map) {
map.put(Class.class, getOpt_special);
map.put(S.class, getOpt_special);
}*/
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
/*if (o instanceof S)
ret getOpt(getBot((S) o), field);*/
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
f.setAccessible(true);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
if (getOpt_cache != null) getOpt_cache.put(c, map);
return map;
}
static String fsI(String id) {
return formatSnippetID(id);
}
static String fsI(long id) {
return formatSnippetID(id);
}
static File loadBinarySnippet(String snippetID) { try {
long id = parseSnippetID(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile(snippetID);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static boolean loadBufferedImageFixingGIFs_debug;
static ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal();
static Image loadBufferedImageFixingGIFs(File file) { try {
if (!file.exists()) return null;
// Load anything but GIF the normal way
if (!isGIF(file))
return ImageIO.read(file);
if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": checking gif");
// Get GIF reader
ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
// Give it the stream to decode from
reader.setInput(ImageIO.createImageInputStream(file));
int numImages = reader.getNumImages(true);
// Get 'metaFormatName'. Need first frame for that.
IIOMetadata imageMetaData = reader.getImageMetadata(0);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
// Find out if GIF is bugged
boolean foundBug = false;
for (int i = 0; i < numImages && !foundBug; i++) {
// Get metadata
IIOMetadataNode root = (IIOMetadataNode)reader.getImageMetadata(i).getAsTree(metaFormatName);
// Find GraphicControlExtension node
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
// Get delay value
String delay = ((IIOMetadataNode)node).getAttribute("delayTime");
// Check if delay is bugged
if (Integer.parseInt(delay) == 0) {
foundBug = true;
}
break;
}
}
}
if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
// Load non-bugged GIF the normal way
Image image;
if (!foundBug) {
image = Toolkit.getDefaultToolkit().createImage(f2s(file));
} else {
// Prepare streams for image encoding
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
{
ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream); try {
// Get GIF writer that's compatible with reader
ImageWriter writer = ImageIO.getImageWriter(reader);
// Give it the stream to encode to
writer.setOutput(ios);
writer.prepareWriteSequence(null);
for (int i = 0; i < numImages; i++) {
// Get input image
BufferedImage frameIn = reader.read(i);
// Get input metadata
IIOMetadataNode root = (IIOMetadataNode)reader.getImageMetadata(i).getAsTree(metaFormatName);
// Find GraphicControlExtension node
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
// Get delay value
String delay = ((IIOMetadataNode)node).getAttribute("delayTime");
// Check if delay is bugged
if (Integer.parseInt(delay) == 0) {
// Overwrite with a valid delay value
((IIOMetadataNode)node).setAttribute("delayTime", "10");
}
break;
}
}
// Create output metadata
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
// Copy metadata to output metadata
metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
// Create output image
IIOImage frameOut = new IIOImage(frameIn, null, metadata);
// Encode output image
writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
}
writer.endWriteSequence();
} finally { _close(ios); }}
// Create image using encoded data
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); } }
static int toInt(Object o) {
if (o == null) return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt((String) o);
throw fail("woot not int: " + getClassName(o));
}
static int toInt(long l) {
if (l != (int) l) throw fail("Too large for int: " + l);
return (int) l;
}
static boolean isSubstanceLAF() {
return substanceLookAndFeelEnabled();
}
// menuMaker = voidfunc(JPopupMenu)
// return true if menu could be added
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; }
}
// r : runnable or voidfunc(bool)
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;
}
static void toggleAlwaysOnTop(JFrame frame) {
frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
}
static void shootWindowGUI_external(JFrame frame) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame);
}
static void shootWindowGUI_external(final JFrame frame, int delay) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame, delay);
}
static A vm_generalMap_get(Object key) {
return (A) vm_generalMap().get(key);
}
static A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () { A get() { try { return nuObject(c, args); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret nuObject(c, args);"; }});
}
static A oneOf(List l) {
return l.isEmpty() ? null : l.get(new Random().nextInt(l.size()));
}
static char oneOf(String s) {
return empty(s) ? '?' : s.charAt(random(l(s)));
}
static String oneOf(String... l) {
return oneOf(asList(l));
}
static 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;
}
static void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null) tl.set(l = new ArrayList());
l.add(a);
}
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;
}
static void pcallFAll(Collection l, Object... args) {
if (l != null) for (Object f : cloneList(l)) pcallF(f, args);
}
static void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
hideCredentials(str(getInnerException(e)))) + "\n");
}
static void nohupJavax(final String javaxargs) {
{ Thread _t_0 = new Thread() {
public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs); } catch (Throwable __e) { _handleException(__e); } }
};
startThread(_t_0); }
}
static void nohupJavax(final String javaxargs, final String vmArgs) {
{ Thread _t_1 = new Thread() {
public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs); } catch (Throwable __e) { _handleException(__e); } }
};
startThread(_t_1); }
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static ArrayList cloneListSynchronizingOn(Collection l, Object mutex) {
if (l == null) return new ArrayList();
synchronized(mutex) {
return new ArrayList (l);
}
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static Throwable getInnerException(Throwable e) {
if (e == null) return null;
while (e.getCause() != null)
e = e.getCause();
return e;
}
static Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
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;
}
static 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 Map vm_generalWeakSubMap(Object name) {
synchronized(get(javax(), "generalMap")) {
Map map = (Map) ( vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = newWeakMap());
return map;
}
}
static WeakReference weakRef(A a) {
return newWeakReference(a);
}
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
return null;
}
static volatile boolean disableCertificateValidation_attempted;
static void disableCertificateValidation() { try {
if (disableCertificateValidation_attempted) return;
disableCertificateValidation_attempted = true;
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}};
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) { return true; }
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Throwable __e) { _handleException(__e); }
} catch (Exception __e) { throw rethrow(__e); } }
static boolean networkAllowanceTest(String url) {
return isAllowed("networkAllowanceTest", url);
}
static final boolean loadPageThroughProxy_enabled = false;
static String loadPageThroughProxy(String url) {
return null;
}
static void sleepSeconds(double s) {
if (s > 0) sleep(round(s*1000));
}
static String tb_mainServer_default = "http://tinybrain.de:8080";
static Object tb_mainServer_override; // func -> S
static String tb_mainServer() {
if (tb_mainServer_override != null) return (String) callF(tb_mainServer_override);
return trim(loadTextFile(tb_mainServer_file(),
tb_mainServer_default));
}
static File tb_mainServer_file() {
return getProgramFile("#1001638", "mainserver.txt");
}
static boolean tb_mainServer_isDefault() {
return eq(tb_mainServer(), tb_mainServer_default);
}
static A printWithTime(A a) {
print(hmsWithColons() + ": " + a);
return a;
}
static A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
static void setHeaders(URLConnection con) throws IOException {
String computerID = getComputerID_quick();
if (computerID != null) try {
con.setRequestProperty("X-ComputerID", computerID);
con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
} catch (Throwable e) {
//printShortException(e);
}
}
static 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 GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
static GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
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);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\"': ch = '\"'; break;
case '\\': 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;
// Hex Unicode: u????
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + s.charAt(i + 2) + s.charAt(i + 3)
+ s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar; // added by Stefan
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s; // not quoted - return original
}
static String toHex(byte[] bytes) {
return bytesToHex(bytes);
}
static String toHex(byte[] bytes, int ofs, int len) {
return bytesToHex(bytes, ofs, len);
}
static byte[] utf8(String s) {
return toUtf8(s);
}
static Matcher regexpMatcher(String pat, String s) {
return compileRegexp(pat).matcher(unnull(s));
}
static A or(A a, A b) {
return a != null ? a : b;
}
static URLConnection openConnection(URL url) { try {
ping();
callOpt(javax(), "recordOpenURLConnection", str(url));
return url.openConnection();
} catch (Exception __e) { throw rethrow(__e); } }
static 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 String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static String fromUtf8(byte[] bytes) { try {
return new String(bytes, "UTF-8");
} catch (Exception __e) { throw rethrow(__e); } }
static ThreadLocal < VF1 < File > > checkFileNotTooBigToRead_tl = new ThreadLocal();
static void checkFileNotTooBigToRead(File f) {
callF(checkFileNotTooBigToRead_tl.get(), f);
}
static File javaxCodeDir_dir; // can be set to work on different base dir
static File javaxCodeDir() {
return javaxCodeDir_dir != null ? javaxCodeDir_dir : new File(userHome(), "JavaX-Code");
}
static String getType(Object o) {
return getClassName(o);
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static void logQuotedWithTime(String s) {
logQuotedWithTime(standardLogFile(), s);
}
static void logQuotedWithTime(File logFile, String s) {
logQuoted(logFile, logQuotedWithTime_format(s));
}
static void logQuotedWithTime(String logFile, String s) {
logQuoted(logFile, logQuotedWithTime_format(s));
}
static String logQuotedWithTime_format(String s) {
return /*formatGMTWithDate_24*/(now()) + " " + s;
}
static File javaxDataDir_dir; // can be set to work on different base dir
static File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static File javaxDataDir(String... subs) {
return newFile(javaxDataDir(), subs);
}
static JTextArea wrappedTextArea(final JTextArea ta) {
enableWordWrapForTextArea(ta);
return ta;
}
static JTextArea wrappedTextArea() {
return wrappedTextArea(jtextarea());
}
static JTextArea wrappedTextArea(String text) {
JTextArea ta = wrappedTextArea();
setText(ta, text);
return ta;
}
static A onClick(final A c, final Object runnable) {
if (c != null) { swing(new Runnable() { public void run() { try {
c.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
callF(runnable, e);
}
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(MouseEv..."; }}); }
return c;
}
// re-interpreted for buttons
static void onClick(JButton btn, final Object runnable) {
onEnter(btn, runnable);
}
static void disposeWindow(final Window window) {
if (window != null) { swing(new Runnable() { public void run() { try {
window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); // call listeners
myFrames_list.remove(window);
window.dispose();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //..."; }}); }
}
static void disposeWindow(final Component c) {
disposeWindow(getWindow(c));
}
static void disposeWindow(Object o) {
if (o != null) disposeWindow(((Component) o));
}
static void disposeWindow() {
disposeWindow(heldInstance(Component.class));
}
static int withMargin_defaultWidth = 6;
static JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
static JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
static JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
return swing(new F0() { JPanel get() { try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
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 Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
static int toMS_int(double seconds) {
return toInt_checked((long) (seconds*1000));
}
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);
}
static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
// PersistableThrowable doesn't hold GC-disturbing class references in backtrace
static volatile PersistableThrowable lastException_lastException;
static PersistableThrowable lastException() {
return lastException_lastException;
}
static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static String unnull(String s) {
return s == null ? "" : s;
}
static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
//ifclass Symbol
static String baseClassName(String className) {
return substring(className, className.lastIndexOf('.')+1);
}
static String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
static String prependIfNempty(String prefix, String s) {
return empty(s) ? s : prefix + s;
}
static ReentrantLock fairLock() {
return new ReentrantLock(true);
}
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); } }
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 = "http://ai1.space/images/raw/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); } }
static String getSnippetTitle(long id) {
return getSnippetTitle(fsI(id));
}
static boolean isNormalQuoted(String s) {
int l = l(s);
if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"')) return false;
int j = 1;
while (j < l)
if (s.charAt(j) == '"')
return j == l-1;
else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
return false;
}
static boolean isMultilineQuoted(String s) {
if (!startsWith(s, "[")) return false;
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
return i < s.length() && s.charAt(i) == '[';
}
static List _registerWeakMap_preList;
static A _registerWeakMap(A map) {
if (javax() == null) {
// We're in class init
if (_registerWeakMap_preList == null) _registerWeakMap_preList = synchroList();
_registerWeakMap_preList.add(map);
return map;
}
try {
call(javax(), "_registerWeakMap", map);
} catch (Throwable e) {
printException(e);
print("Upgrade JavaX!!");
}
return map;
}
static void _onLoad_registerWeakMap() {
assertNotNull(javax());
if (_registerWeakMap_preList == null) return;
for (Object o : _registerWeakMap_preList)
_registerWeakMap(o);
_registerWeakMap_preList = null;
}
static Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
static void setOpt(Object o, String field, Object value) { try {
if (o == null) return;
Class c = o.getClass();
HashMap map;
if (getOpt_cache == null)
map = getOpt_makeCache(c); // in class init
else synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
// It's probably a subclass of Map. Use raw method
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null)
smartSet(f, o, value); // possible improvement: skip setAccessible
} catch (Exception __e) { throw rethrow(__e); } }
static void setOpt(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
f.setAccessible(true);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Object[] mapToParams(Map map) {
return mapToObjectArray(map);
}
static String htmlQuote(String s) {
return "\"" + htmlencode_forParams(s) + "\"";
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
static boolean eqic(char a, char b) {
if (a == b) return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2) return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
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);
}
static ArrayList emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
// Try to match capacity
static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
// get correct type at once
static ArrayList emptyList(Class c) {
return new ArrayList();
}
static List dropFirstAndLast(int n, List l) {
return new ArrayList(subList(l, n, l(l)-n));
}
static List dropFirstAndLast(List l) {
return dropFirstAndLast(1, l);
}
static String dropFirstAndLast(String s) {
return substring(s, 1, l(s)-1);
}
static String javaTok_substringN(String s, int i, int j) {
if (i == j) return "";
if (j == i+1 && s.charAt(i) == ' ') return " ";
return s.substring(i, j);
}
static String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
static List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j-i
&& s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static boolean odd(int i) {
return (i & 1) != 0;
}
static boolean odd(long i) {
return (i & 1) != 0;
}
static boolean odd(BigInteger i) { return odd(toInt(i)); }
// i must point at the (possibly imaginary) opening bracket
// index returned is index of closing bracket + 1
static int findEndOfCurlyBracketPart(List cnc, int i) {
int j = i+2, level = 1;
while (j < cnc.size()) {
if (eq(cnc.get(j), "{")) ++level;
else if (eq(cnc.get(j), "}")) --level;
if (level == 0)
return j+1;
++j;
}
return cnc.size();
}
static String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
static String joinSubList(List l, int i) {
return join(subList(l, i));
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, char c) {
return nempty(a) && a.charAt(0) == c;
}
static boolean startsWith(List a, List b) {
if (a == null || l(b) > l(a)) return false;
for (int i = 0; i < l(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
static boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la-lb, b, 0, lb);
}
static boolean containsNewLine(String s) {
return contains(s, '\n'); // screw \r, nobody needs it
}
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;
}
static String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
static String htmlencode(Object o) {
return htmlencode(str(o));
}
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 >= 0x100)
out.append("").append(charToHex(c)).append(';');
else*/ if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&')
out.append("").append((int) c).append(';');
else
out.append(c);
}
return out.toString();
}
static void clear(Collection c) {
if (c != null) c.clear();
}
static void put(Map map, A a, B b) {
if (map != null) map.put(a, b);
}
static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
// If you change this, also change DiskSnippetCache_fileToLibID
static File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
// Data files are immutable, use centralized cache
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = DiskSnippetCache_file(snippetID);
return file.exists() ? file : null;
}
public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(DiskSnippetCache_file(snippetID), data);
}
static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL(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;
}
static long fileSize(String path) { return getFileSize(path); }
static long fileSize(File f) { return getFileSize(f); }
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));
}
// TODO: check if we hit the "LOADING" message
if (fileSize(f) == 0) throw fail();
System.err.println("Bytes loaded: " + fileSize(f));
} catch (Throwable e) {
printStackTrace(e);
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); } }
static byte[] isGIF_magic = bytesFromHex("47494638"); // Actual signature is longer, but we're lazy
static boolean isGIF(byte[] data) {
return byteArrayStartsWith(data, isGIF_magic);
}
static boolean isGIF(File f) {
return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
}
static String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static void setVar(IVar v, A value) {
if (v != null) v.set(value);
}
static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
static int parseInt(char c) {
return Integer.parseInt(str(c));
}
static boolean substanceLookAndFeelEnabled() {
return startsWith(getLookAndFeel(), "org.pushingpixels.");
}
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 /*SubstanceRootPaneUI*/ ui = rootPane.getUI();
return (JComponent) call(ui, "getTitlePane");
}
return null;
}
// TODO: get rid of map (just look for adapter in listeners)
static Map componentPopupMenu_map;
static ThreadLocal componentPopupMenu_mouseEvent;
static void componentPopupMenu_init() {
{ swing(new Runnable() { public void run() { try {
if (componentPopupMenu_map == null)
componentPopupMenu_map = or((Map) getOpt(creator(), "componentPopupMenu_map"), (Map) (Map) newWeakHashMap());
if (componentPopupMenu_mouseEvent == null)
componentPopupMenu_mouseEvent = or((ThreadLocal) getOpt(creator(), "componentPopupMenu_mouseEvent"), new ThreadLocal());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (componentPopupMenu_map == null)\r\n componentPopupMenu_map = or((Map() { Boolean get() { try { return checkBox.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret checkBox.isSelected();"; }});
}
static boolean isChecked(final JCheckBoxMenuItem mi) {
return mi != null && (boolean) swing(new F0() { Boolean get() { try { return mi.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret mi.isSelected();"; }});
}
static Class hotwireOnce(String programID) {
return hotwireCached(programID, false);
}
static Map vm_generalMap_map;
static Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static Object nuObject(String className, Object... args) { try {
return nuObject(classForName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }
// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
ret nuObject(_getClass(realm, className), args);
}*/
static A nuObject(Class c, Object... args) { try {
if (args.length == 0) return nuObjectWithoutArguments(c); // cached!
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return (A) m.newInstance(args);
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found"
+ (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static A listGet(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static A popLast(List l) {
return liftLast(l);
}
static Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null) return e;
while (e.getClass() == RuntimeException.class
&& e.getCause() != null && eq(e.getMessage(), str(e.getCause())))
e = e.getCause();
return e;
}
static String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix)) return s;
return replacement + substring(s, l(prefix));
}
static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static String className(Object o) {
return getClassName(o);
}
static Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static Map newWeakMap() {
return newWeakHashMap();
}
static WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static volatile Object isAllowed_function; // func(S, O[]) -> bool
static volatile boolean isAllowed_all = true;
static boolean isAllowed(String askingMethod, Object... args) {
// check on VM level
Object f = vm_generalMap_get("isAllowed_function");
if (f != null && !isTrue(callF(f, askingMethod, args))) return false;
// check locally
return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
}
static long round(double d) {
return Math.round(d);
}
static File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
static String hmsWithColons() {
return hmsWithColons(now());
}
static String hmsWithColons(long time) {
return new SimpleDateFormat("HH:mm:ss").format(time);
}
static String getComputerID_quick() {
return computerID();
}
static int gzInputStream_defaultBufferSize = 65536;
static GZIPInputStream gzInputStream(File f) { try {
return gzInputStream(new FileInputStream(f));
} catch (Exception __e) { throw rethrow(__e); } }
static GZIPInputStream gzInputStream(File f, int bufferSize) { try {
return gzInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) { throw rethrow(__e); } }
static GZIPInputStream gzInputStream(InputStream in) {
return gzInputStream(in, gzInputStream_defaultBufferSize);
}
static GZIPInputStream gzInputStream(InputStream in, int bufferSize) { try {
return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
} catch (Exception __e) { throw rethrow(__e); } }
static Map compileRegexp_cache = syncMRUCache(10);
static 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 long parseLong(String s) {
if (s == null) return 0;
return Long.parseLong(dropSuffix("L", s));
}
static long parseLong(Object s) {
return Long.parseLong((String) s);
}
static String _userHome;
static String userHome() {
if (_userHome == null) {
if (isAndroid())
_userHome = "/storage/sdcard0/";
else
_userHome = System.getProperty("user.home");
//System.out.println("userHome: " + _userHome);
}
return _userHome;
}
static File userHome(String path) {
return new File(userDir(), path);
}
static File standardLogFile() {
return getProgramFile("log");
}
static void logQuoted(String logFile, String line) {
logQuoted(getProgramFile(logFile), line);
}
static void logQuoted(File logFile, String line) {
appendToFile(logFile, quote(line) + "\n");
}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static void enableWordWrapForTextArea(final JTextArea ta) {
if (ta != null) { swing(new Runnable() { public void run() { try {
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ta.setLineWrap(true);\r\n ta.setWrapStyleWord(true);"; }}); }
}
static JTextArea jtextarea() {
return jTextArea();
}
static JTextArea jtextarea(String text) {
return jTextArea(text);
}
static JTextField onEnter(final JTextField tf, final Object action) {
if (action == null || tf == null) return tf;
tf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
tf.selectAll();
callF(action);
} catch (Throwable __e) { messageBox(__e); }}});
return tf;
}
static JButton onEnter(JButton btn, final Object action) {
if (action == null || btn == null) return btn;
btn.addActionListener(actionListener(action));
return btn;
}
static JList onEnter(JList list, Object action) {
list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
return list;
}
static JComboBox onEnter(final JComboBox cb, final Object action) {
{ swing(new Runnable() { public void run() { try {
if (cb.isEditable()) {
JTextField text = (JTextField) cb.getEditor().getEditorComponent();
onEnter(text, action);
} else {
cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
cb.getActionMap().put("enter", abstractAction("", new Runnable() { public void run() { try { cb.hidePopup(); callF(action);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.hidePopup(); callF(action);"; }}));
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (cb.isEditable()) {\r\n JTextField text = (JTextField) cb.getEditor().g..."; }}); }
return cb;
}
static JTable onEnter(final JTable table, final Object action) {
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
table.getActionMap().put("Enter", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
callF(action, table.getSelectedRow());
}
});
return table;
}
/*static JTextArea onEnter(final JTextArea ta, fO action) {
addKeyListener(ta, enterKeyListener(action));
ret ta;
}*/
static JTextField onEnter(Object action, JTextField tf) {
return onEnter(tf, action);
}
static A heldInstance(Class c) {
List l = holdInstance_l.get();
for (int i = l(l)-1; i >= 0; i--) {
Object o = l.get(i);
if (isInstanceOf(o, c))
return (A) o;
}
throw fail("No instance of " + className(c) + " held");
}
static int toInt_checked(long l) {
if (l != (int) l) throw fail("Too large for int: " + l);
return (int) l;
}
static Map emptyMap() {
return new HashMap();
}
static boolean isLocalSnippetID(String snippetID) {
return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID));
}
static boolean isLocalSnippetID(long snippetID) {
return snippetID >= 1000 && snippetID <= 9999;
}
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");
}
static boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static String muricaCredentialsQuery() {
return htmlQuery(muricaCredentials());
}
static boolean isGeneralFileServerSnippet(long id) {
return id >= 1400000 && id < 1500000;
}
static String standardCredentials_noCookies() {
return standardCredentials() + "&noCookies=1";
}
static void saveTextFileIfChanged(File f, String contents) {
saveTextFileIfDifferent(f, contents);
}
static File snippetTitle_cacheFile(String snippetID) {
return javaxCachesDir("Snippet Titles/" + psI(snippetID));
}
static char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s)-1);
}
static void printException(Throwable e) {
printStackTrace(e);
}
static void setOpt_raw(Object o, String field, Object value) { try {
if (o == null) return;
if (o instanceof Class) setOpt_raw((Class) o, field, value);
else {
Field f = setOpt_raw_findField(o.getClass(), field);
if (f != null) {
f.setAccessible(true);
smartSet(f, o, value);
}
}
} catch (Exception __e) { throw rethrow(__e); } }
static void setOpt_raw(Class c, String field, Object value) { try {
if (c == null) return;
Field f = setOpt_raw_findStaticField(c, field);
if (f != null) {
f.setAccessible(true);
smartSet(f, null, value);
}
} catch (Exception __e) { throw rethrow(__e); } }
static Field setOpt_raw_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Field setOpt_raw_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
// take care of common case (long to int)
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; }
throw e;
}
}
static 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 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 >= 0x100)
out.append("").append(charToHex(c)).append(';');
else*/ if (c > 127 || c == '"' || c == '<' || c == '>') {
out.append("");
out.append((int) c);
out.append(';');
} else
out.append(c);
}
return out.toString();
}
static String asString(Object o) {
return o == null ? null : o.toString();
}
static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static float max(float[] c) {
if (c.length == 0) return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x) x = d;
return x;
}
static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static File getGlobalCache() {
File file = new File(javaxCachesDir(), "Binary Snippets");
file.mkdirs();
return file;
}
/** writes safely (to temp file, then rename) */
public static byte[] saveBinaryFile(String fileName, byte[] contents) { try {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
FileOutputStream fileOutputStream = newFileOutputStream(tempFileName);
fileOutputStream.write(contents);
fileOutputStream.close();
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
vmBus_send("wroteFile", file);
return contents;
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] saveBinaryFile(File fileName, byte[] contents) {
return saveBinaryFile(fileName.getPath(), contents);
}
static String dataSnippetLink(String snippetID) {
long id = parseSnippetID(snippetID);
if (id >= 1100000 && id < 1200000)
return "http://ai1.space/images/raw/" + id;
if (id >= 1400000 && id < 1500000)
return "http://butter.botcompany.de:8080/files/" + id + "?_pass=" + muricaPassword();
if (id >= 1200000 && id < 1300000) { // Woody files, actually
String pw = muricaPassword();
if (empty(pw)) throw fail("Please set 'murica password by running #1008829");
return "http://butter.botcompany.de:8080/1008823/raw/" + id + "?_pass=" + pw; // XXX, although it typically gets hidden when printing
} else
return "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
+ id + "&contentType=application/binary";
}
static ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal();
static ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal();
static byte[] loadBinaryPage(String url) { try {
print("Loading " + url);
return loadBinaryPage(loadPage_openConnection(new URL(url)));
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] loadBinaryPage(URLConnection con) { try {
Map extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders);
setHeaders(con);
for (String key : keys(extraHeaders))
con.setRequestProperty(key, extraHeaders.get(key));
return loadBinaryPage_noHeaders(con);
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] loadBinaryPage_noHeaders(URLConnection con) { try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
InputStream inputStream = con.getInputStream();
loadBinaryPage_responseHeaders.set(con.getHeaderFields());
long len = 0;
try { len = con.getContentLength/*Long*/(); } catch (Throwable e) { printStackTrace(e); }
int n = 0;
while (true) {
int ch = inputStream.read();
if (ch < 0)
break;
buf.write(ch);
if (++n % 100000 == 0)
println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
}
inputStream.close();
return buf.toByteArray();
} catch (Exception __e) { throw rethrow(__e); } }
static A addAndReturn(Collection c, A a) {
if (c != null) c.add(a);
return a;
}
static void loadBinaryPageToFile(String url, File file) { try {
print("Loading " + url);
loadBinaryPageToFile(openConnection(new URL(url)), file);
} catch (Exception __e) { throw rethrow(__e); } }
static void loadBinaryPageToFile(URLConnection con, File file) { try {
setHeaders(con);
loadBinaryPageToFile_noHeaders(con, file);
} catch (Exception __e) { throw rethrow(__e); } }
static void loadBinaryPageToFile_noHeaders(URLConnection con, File file) { try {
File ftemp = new File(f2s(file) + "_temp");
FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
try {
InputStream inputStream = con.getInputStream();
long len = 0;
try { len = con.getContentLength/*Long*/(); } catch (Throwable e) { printStackTrace(e); }
String pat = " {*}" + (len != 0 ? "/" + len : "") + " bytes loaded.";
copyStreamWithPrints(inputStream, buf, pat);
inputStream.close();
buf.close();
file.delete();
renameFile_assertTrue(ftemp, file);
} finally {
if (buf != null) buf.close();
}
} catch (Exception __e) { throw rethrow(__e); } }
static List allToString(Collection c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
static List allToString(Object[] c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
static byte[] bytesFromHex(String s) {
return hexToBytes(s);
}
static boolean byteArrayStartsWith(byte[] a, byte[] b) {
if (a == null || b == null) return false;
if (a.length < b.length) return false;
for (int i = 0; i < b.length; i++)
if (a[i] != b[i])
return false;
return true;
}
static byte[] loadBeginningOfBinaryFile(File file, int maxBytes) {
return loadBinaryFilePart(file, 0, maxBytes);
}
static String getLookAndFeel() {
return getClassName(UIManager.getLookAndFeel());
}
static JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) {
return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane");
}
static TreeMap hotwireCached_cache = new TreeMap();
static Lock hotwireCached_lock = lock();
static Class hotwireCached(String programID) {
return hotwireCached(programID, true);
}
static Class hotwireCached(String programID, boolean runMain) {
return hotwireCached(programID, runMain, false);
}
static Class hotwireCached(String programID, boolean runMain, boolean dependent) {
Lock __626 = hotwireCached_lock; lock(__626); try {
programID = formatSnippetID(programID);
Class c = hotwireCached_cache.get(programID);
if (c == null) {
c = hotwire(programID);
if (dependent)
makeDependent(c);
if (runMain)
callMain(c);
hotwireCached_cache.put(programID, c);
}
return c;
} finally { unlock(__626); } }
static Map classForName_cache = synchroHashMap();
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); } }
static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static Object nuObjectWithoutArguments(String className) { try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) { throw rethrow(__e); } }
static A nuObjectWithoutArguments(Class c) { try {
if (nuObjectWithoutArguments_cache == null)
// in class init
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 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());
}
static List getClasses(Object[] array) {
List l = new ArrayList();
for (Object o : array) l.add(_getClass(o));
return l;
}
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;
}
static 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 File getProgramDir() {
return programDir();
}
static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
static String _computerID;
static Lock computerID_lock = lock();
public static String computerID() {
if (_computerID == null) {
Lock __516 = computerID_lock; lock(__516); try {
if (_computerID != null) return _computerID;
File file = computerIDFile();
_computerID = loadTextFile(file.getPath());
if (_computerID == null) {
// legacy load
_computerID = loadTextFile(userDir(".tinybrain/computer-id"));
if (_computerID == null)
_computerID = makeRandomID(12, new SecureRandom());
saveTextFile(file, _computerID);
}
} finally { unlock(__516); } }
return _computerID;
}
static A _registerIOWrap(A wrapper, Object wrapped) {
return wrapper;
}
static Map syncMRUCache(int size) {
return synchroMap(new MRUCache(size));
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static File userDir() {
return new File(userHome());
}
static File userDir(String path) {
return new File(userHome(), path);
}
static Lock appendToFile_lock = lock();
static boolean appendToFile_keepOpen;
static HashMap appendToFile_writers = new HashMap();
static void appendToFile(String path, String s) { try {
Lock __195 = appendToFile_lock; lock(__195); try { // Let's just generally synchronize this to be safe.
mkdirsForFile(new File(path));
path = getCanonicalPath(path);
Writer writer = appendToFile_writers.get(path);
if (writer == null) {
//print("[Logging to " + path + "]");
writer = new BufferedWriter(new OutputStreamWriter(
newFileOutputStream(path, true), "UTF-8"));
if (appendToFile_keepOpen)
appendToFile_writers.put(path, writer);
}
writer.write(s);
if (!appendToFile_keepOpen)
writer.close();
} finally { unlock(__195); } } catch (Exception __e) { throw rethrow(__e); } }
static void appendToFile(File path, String s) {
if (path != null)
appendToFile(path.getPath(), s);
}
static void cleanMeUp_appendToFile() {
AutoCloseable __198 = tempCleaningUp(); try {
Lock __196 = appendToFile_lock; lock(__196); try {
closeAllWriters(values(appendToFile_writers));
appendToFile_writers.clear();
} finally { unlock(__196); } } finally { _close(__198); }}
static JTextArea jTextArea() {
return jTextArea("");
}
static JTextArea jTextArea(final String text) {
return swingNu(JTextArea.class, text);
}
static KeyListener enterKeyListener(final Object action) {
return new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER)
pcallF(action);
}
};
}
static Runnable rCallOnSelectedListItem(final JList list, final Object action) {
return new Runnable() { public void run() { try { pcallF(action, getSelectedItem(list)) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, getSelectedItem(list))"; }};
}
static AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
static boolean isInstanceOf(Object o, Class type) {
return type.isInstance(o);
}
static File localSnippetFile(long snippetID) {
return localSnippetsDir(snippetID + ".text");
}
static File localSnippetFile(String snippetID) {
return localSnippetFile(parseSnippetID(snippetID));
}
static String getFileInfoField(File f, String field) {
return getOneLineFileInfoField(f, field);
}
static File dropExtension(File f) {
return f == null ? null : fileInSameDir(f, dropExtension(f.getName()));
}
static String dropExtension(String s) {
return takeFirst(s, smartLastIndexOf(s, '.'));
}
static String htmlQuery(Map params) {
return params.isEmpty() ? "" : "?" + makePostData(params);
}
static String htmlQuery(Object... data) {
return htmlQuery(litmap(data));
}
static Object[] muricaCredentials() {
String pass = muricaPassword();
return nempty(pass) ? new Object[] {"_pass", pass } : new Object[0];
}
static String standardCredentials() {
String user = standardCredentialsUser();
String pass = standardCredentialsPass();
if (nempty(user) && nempty(pass))
return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
return "";
}
static void saveTextFileIfDifferent(File f, String contents) {
if (!eq(loadTextFile(f), contents))
saveTextFile(f, contents);
}
static File javaxCachesDir_dir; // can be set to work on different base dir
static File javaxCachesDir() {
return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
static File javaxCachesDir(String sub) {
return newFile(javaxCachesDir(), sub);
}
static 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 FileOutputStream newFileOutputStream(File path) throws IOException {
return newFileOutputStream(path.getPath());
}
static FileOutputStream newFileOutputStream(String path) throws IOException {
return newFileOutputStream(path, false);
}
static FileOutputStream newFileOutputStream(File path, boolean append) throws IOException {
return newFileOutputStream(path.getPath(), append);
}
static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
mkdirsForFile(path);
FileOutputStream f = new FileOutputStream(path, append);
_registerIO(f, path, true);
return f;
}
static void vmBus_send(String msg, Object... args) {
Object arg = empty(args) ? null
: l(args) == 1 ? args[0]
: args;
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static volatile boolean muricaPassword_pretendNotAuthed;
static String muricaPassword() {
if (muricaPassword_pretendNotAuthed) return null;
return trim(loadTextFile(muricaPasswordFile()));
}
static A println(A a) {
return print(a);
}
public static File mkdirsFor(File file) {
return mkdirsForFile(file);
}
static void copyStreamWithPrints(InputStream in, OutputStream out, String pat) { try {
byte[] buf = new byte[65536];
int total = 0;
while (true) {
int n = in.read(buf);
if (n <= 0) return;
out.write(buf, 0, n);
if ((total+n)/100000 > total/100000)
print(pat.replace("{*}", str(roundDownTo(total, 100000))));
total += n;
}
} catch (Exception __e) { throw rethrow(__e); } }
static void renameFile_assertTrue(File a, File b) { try {
if (!a.exists()) throw fail("Source file not found: " + f2s(a));
if (b.exists()) throw fail("Target file exists: " + f2s(b));
mkdirsForFile(b);
if (!a.renameTo(b))
throw fail("Can't rename " + f2s(a) + " to " + f2s(b));
} catch (Exception __e) { throw rethrow(__e); } }
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;
}
static 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 Component childWithClassNameEndingWith(Component c, String suffix) {
if (endsWith(className(c), suffix)) return c;
Component x;
for (Component comp : getComponents(c))
if ((x = childWithClassNameEndingWith(comp, suffix)) != null) return x;
return null;
}
static Class> hotwire(String src) {
assertFalse(_inCore());
Class j = getJavaX();
if (isAndroid()) {
synchronized(j) { // hopefully this goes well...
List libraries = new ArrayList();
File srcDir = (File) call(j, "transpileMain", src, libraries);
if (srcDir == null)
throw fail("transpileMain returned null (src=" + quote(src) + ")");
Object androidContext = get(j, "androidContext");
return (Class) call(j, "loadx2android", srcDir, src);
}
} else {
Class c = (Class) ( call(j, "hotwire", src));
hotwire_copyOver(c);
return c;
}
}
static Object makeDependent_postProcess;
static void makeDependent(Object c) {
if (c == null) return;
assertTrue("Not a class", c instanceof Class);
dependentClasses(); // cleans up the list
hotwire_classes.add(new WeakReference(c));
Object local_log = getOpt(mc(), "local_log");
if (local_log != null)
setOpt(c, "local_log", local_log);
/*if (isTrue(getOpt(c, 'ping_actions_shareable)))
setOpt(c, +ping_actions);*/
Object print_byThread = getOpt(mc(), "print_byThread");
if (print_byThread != null)
setOpt(c, "print_byThread", print_byThread);
callF(makeDependent_postProcess, c);
}
static A callMain(A c, String... args) {
callOpt(c, "main", new Object[] {args});
return c;
}
static void callMain() {
callMain(mc());
}
static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static Class _getClass(Object o) {
return o == null ? null
: o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static File programDir_mine; // set this to relocate program's data
static File programDir() {
return programDir(getProgramID());
}
static File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetID(snippetID));
if (me) {
String c = caseID();
if (nempty(c)) dir = newFile(dir, c);
}
return dir;
}
static File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
static File computerIDFile() {
return javaxDataDir("Basic Info/computer-id.txt");
}
static String makeRandomID(int length) {
return makeRandomID(length, defaultRandomGenerator());
}
static 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);
}
/** writes safely (to temp file, then rename) */
static File saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
File file = new File(fileName);
mkdirsForFile(file);
String tempFileName = fileName + "_temp";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists()) try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) { printStackTrace(e); }
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
vmBus_send("wroteFile", file);
return file;
} finally {
action.done();
}
}
static File saveTextFile(File fileName, String contents) { try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) { throw rethrow(__e); } }
public static File mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) { // is null if file is in current dir
dir.mkdirs();
if (!dir.isDirectory())
if (dir.isFile()) throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
else throw fail("Unknown IO exception during mkdirs of " + f2s(file));
}
return file;
}
public static String mkdirsForFile(String path) {
mkdirsForFile(new File(path));
return path;
}
static String getCanonicalPath(String path) { try {
return new File(path).getCanonicalPath();
} catch (Exception __e) { throw rethrow(__e); } }
static AutoCloseable tempCleaningUp() {
return tempSetTL(ping_isCleanUpThread, true);
}
static void closeAllWriters(Collection extends Writer> l) {
for (Writer w : unnull(l)) { try {
w.close();
} catch (Throwable __e) { _handleException(__e); }}
}
static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
static String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
static File localSnippetsDir() {
return javaxDataDir("Personal Programs");
}
static File localSnippetsDir(String sub) {
return newFile(localSnippetsDir(), sub);
}
static String getOneLineFileInfoField(File f, String field) {
File infoFile = associatedInfosFile(f);
List lines = lines(loadTextFile(infoFile));
return firstStartingWithIC_drop(lines, field + ": ");
}
static File fileInSameDir(File f, String newName) {
return newFile(parentFile(f), newName);
}
static List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
static List takeFirst(int n, List l) {
return takeFirst(l, n);
}
static String takeFirst(int n, String s) { return substring(s, 0, n); }
static String takeFirst(String s, int n) { return substring(s, 0, n); }
static List takeFirst(int n, Iterable i) {
List l = new ArrayList();
Iterator it = i.iterator();
for (int _repeat_691 = 0; _repeat_691 < n; _repeat_691++) { if (it.hasNext()) l.add(it.next()); else break; }
return l;
}
static int smartLastIndexOf(String s, char c) {
if (s == null) return 0;
int i = s.lastIndexOf(c);
return i >= 0 ? i : l(s);
}
static String makePostData(Map map) {
List l = new ArrayList();
for (Map.Entry e : map.entrySet()) {
String key = (String) ( e.getKey());
Object val = e.getValue();
if (val != null) {
String value = str(val); //structureOrText(val);
l.add(urlencode(key) + "=" + urlencode(/*escapeMultichars*/(value)));
}
}
return join("&", l);
}
static String makePostData(Object... params) {
return makePostData(litorderedmap(params));
}
static HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length-1; i += 2)
if (x[i+1] != null)
map.put(x[i], x[i+1]);
}
static String standardCredentialsUser() {
return trim(loadTextFile(new File(userHome(), ".tinybrain/username")));
}
static String standardCredentialsPass() {
return trim(loadTextFile(new File(userHome(), ".tinybrain/userpass")));
}
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static void _registerIO(Object object, String path, boolean opened) {
}
static Set vm_busListeners_live() {
return vm_generalIdentityHashSet("busListeners");
}
static Map vm_busListenersByMessage_live() {
return vm_generalHashMap("busListenersByMessage");
}
static File muricaPasswordFile() {
return new File(javaxSecretDir(), "murica/muricaPasswordFile");
}
static int roundDownTo(int x, int n) {
return x/n*n;
}
static long roundDownTo(long x, long n) {
return x/n*n;
}
static int shorten_default = 100;
static String shorten(String s) { return shorten(s, shorten_default); }
static String shorten(String s, int max) {
return shorten(s, max, "...");
}
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;
}
static String shorten(int max, String s) { return shorten(s, max); }
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;
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x) x = d;
return x;
}
static List getComponents(final Component c) {
return !(c instanceof Container) ? emptyList() : asList(swing(new F0() { Component[] get() { try { return ((Container) c).getComponents(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret ((Container) c).getComponents();"; }}));
}
static boolean _inCore() {
return false;
}
static List hotwire_copyOver_after = synchroList();
static void hotwire_copyOver(Class c) {
// TODO: make a mechanism for making such "inheritable" fields
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 List dependentClasses() {
return cleanUpAndGetWeakReferencesList(hotwire_classes);
}
static Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static Class getClass(Object realm, String name) { try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) { throw rethrow(__e); } }
static String classNameToVM(String name) {
return name.replace(".", "$");
}
static List> hotwire_classes = synchroList();
static Class> hotwireDependent(String src) {
Class c = hotwire(src);
makeDependent(c);
return c;
}
static boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b)) return false;
return parseSnippetID(a) == parseSnippetID(b);
}
static volatile String caseID_caseID;
static String caseID() { return caseID_caseID; }
static void caseID(String id) {
caseID_caseID = id;
}
static Random defaultRandomGenerator() {
return ThreadLocalRandom.current();
}
static List beginCriticalAction_inFlight = synchroList();
static class CriticalAction {
String description;
CriticalAction() {}
CriticalAction(String description) {
this.description = description;}
void done() {
beginCriticalAction_inFlight.remove(this);
}
}
static CriticalAction beginCriticalAction(String description) {
ping();
CriticalAction c = new CriticalAction(description);
beginCriticalAction_inFlight.add(c);
return c;
}
static void cleanMeUp_beginCriticalAction() {
int n = 0;
while (nempty(beginCriticalAction_inFlight)) {
int m = l(beginCriticalAction_inFlight);
if (m != n) {
n = m;
try {
print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
} catch (Throwable __e) { _handleException(__e); }
}
sleepInCleanUp(10);
}
}
public static void copyFile(File src, File dest) { try {
FileInputStream inputStream = new FileInputStream(src.getPath());
FileOutputStream outputStream = newFileOutputStream(dest.getPath());
try {
copyStream(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
} catch (Exception __e) { throw rethrow(__e); } }
static AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static List concatLists(Collection ... lists) {
List l = new ArrayList();
for (Collection list : lists)
if (list != null)
l.addAll(list);
return l;
}
static List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
for (Collection list : lists)
if (list != null)
l.addAll(list);
return l;
}
static String strOrNull(Object o) {
return o == null ? null : str(o);
}
static File associatedInfosFile(File f) {
return replaceExtension(f, ".infos");
}
static String lines(Collection lines) { return fromLines(lines); }
static List lines(String s) { return toLines(s); }
static String firstStartingWithIC_drop(Collection l, final String prefix) {
for (String s : unnull(l))
if (swic(s, prefix))
return substring(s, l(prefix));
return null;
}
static String firstStartingWithIC_drop(String prefix, Collection l) {
return firstStartingWithIC_drop(l, prefix);
}
static File parentFile(File f) {
return dirOfFile(f);
}
static List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
static List newSubListOrSame(List l, int startIndex, int endIndex) {
if (l == null) return null;
startIndex = max(0, startIndex);
endIndex = min(l(l), endIndex);
if (startIndex >= endIndex) return ll();
if (startIndex == 0 && endIndex == l(l)) return l;
return cloneList(l.subList(startIndex, endIndex));
}
static LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static Set vm_generalIdentityHashSet(Object name) {
synchronized(get(javax(), "generalMap")) {
Set set = (Set) ( vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = syncIdentityHashSet());
return set;
}
}
static Map vm_generalHashMap(Object name) {
synchronized(get(javax(), "generalMap")) {
Map m = (Map) ( vm_generalMap_get(name));
if (m == null)
vm_generalMap_put(name, m = syncHashMap());
return m;
}
}
static File javaxSecretDir_dir; // can be set to work on different base dir
static File javaxSecretDir() {
return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
}
static File javaxSecretDir(String sub) {
return newFile(javaxSecretDir(), sub);
}
static int charDiff(char a, char b) {
return (int) a-(int) b;
}
static int charDiff(String a, char b) {
return charDiff(stringToChar(a), b);
}
static void setOptIfNotNull(Object o, String field, Object value) {
if (value != null) setOpt(o, field, value);
}
static Object mainBot;
static Object getMainBot() {
return mainBot;
}
static List cleanUpAndGetWeakReferencesList(List> l) {
if (l == null) return null;
synchronized(l) {
List out = new ArrayList();
for (int i = 0; i < l(l); i++) {
A a = l.get(i).get();
if (a == null)
l.remove(i--);
else
out.add(a);
}
return out;
}
}
static String n2(long l) { return formatWithThousands(l); }
static String n2(Collection l) { return n2(l(l)); }
static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static String n2(Map m, String singular) {
return n2(l(m), singular);
}
static String n2(Object[] a, String singular) { return n2(l(a), singular); }
static String n2(Object[] a, String singular, String plural) { return n_fancy2(a, singular, plural); }
static List collect(Collection c, String field) {
return collectField(c, field);
}
static List collect(String field, Collection c) {
return collectField(c, field);
}
static void sleepInCleanUp(long ms) { try {
if (ms < 0) return;
Thread.sleep(ms);
} catch (Exception __e) { throw rethrow(__e); } }
static void copyStream(InputStream in, OutputStream out) { try {
byte[] buf = new byte[65536];
while (true) {
int n = in.read(buf);
if (n <= 0) return;
out.write(buf, 0, n);
}
} catch (Exception __e) { throw rethrow(__e); } }
static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}
static File replaceExtension(File f, String extOld, String extNew) {
return newFile(replaceExtension(f2s(f), extOld, extNew));
}
static File replaceExtension(File f, String extNew) {
return replaceExtension(f, fileExtension(f), extNew);
}
static String replaceExtension(String s, String extOld, String extNew) {
s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s);
return s + addPrefixOptIfNempty(".", extNew);
}
static String replaceExtension(String name, String extNew) {
return replaceExtension(name, fileExtension(name), extNew);
}
// usually L
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();
}
static String fromLines(String... lines) {
return fromLines(asList(lines));
}
static IterableIterator toLines(File f) {
return linesFromFile(f);
}
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;
}
static int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static File dirOfFile(File f) {
return f == null ? null : f.getParentFile();
}
static Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static Map syncHashMap() {
return synchroHashMap();
}
static char stringToChar(String s) {
if (l(s) != 1) throw fail("bad stringToChar: " + s);
return firstChar(s);
}
static String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
static double fraction(double d) {
return d % 1;
}
static String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
static String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
static String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
static String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
static List collectField(Collection c, String field) {
List l = new ArrayList();
if (c != null) for (Object a : c)
l.add(getOpt(a, field));
return l;
}
static List collectField(String field, Collection c) {
return collectField(c, field);
}
static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null) return null;
A old = tl.get();
tl.set(value);
return old;
}
static String fileExtension(File f) {
if (f == null) return null;
return fileExtension(f.getName());
}
static String fileExtension(String s) {
return substring(s, smartLastIndexOf(s, '.'));
}
static String dropSuffixIC(String suffix, String s) {
return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static String addPrefixOptIfNempty(String prefix, String s) {
return addPrefixIfNotEmpty2(prefix, s);
}
static 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 Set synchronizedSet() {
return synchroHashSet();
}
static Set synchronizedSet(Set set) {
return Collections.synchronizedSet(set);
}
static Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
static char firstChar(String s) {
return s.charAt(0);
}
static String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
static String addPrefixIfNotEmpty2(String prefix, String s) {
return empty(s) ? "" : addPrefix(prefix, s);
}
static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
public Object next() { throw fail(); }
public boolean hasNext() { return false; }
};
static CloseableIterableIterator emptyCloseableIterableIterator() {
return emptyCloseableIterableIterator_instance;
}
static CloseableIterableIterator linesFromReader(Reader r) {
final BufferedReader br = bufferedReader(r);
return iteratorFromFunction_f0_autoCloseable(new F0() { String get() { try { return readLineFromReaderWithClose(br); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret readLineFromReaderWithClose(br);"; }}, _wrapIOCloseable(r));
}
static BufferedReader utf8bufferedReader(InputStream in) { try {
return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedReader utf8bufferedReader(File f) { try {
return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) { throw rethrow(__e); } }
static Set synchroHashSet() {
return Collections.synchronizedSet(new HashSet ());
}
static String addPrefix(String prefix, String s) {
return s.startsWith(prefix) ? s : prefix + s;
}
static BufferedReader bufferedReader(Reader r) {
return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
}
static CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) {
class IFF2 extends CloseableIterableIterator {
A a;
boolean done;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done) throw fail();
A _a = a;
a = null;
return _a;
}
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 String readLineFromReaderWithClose(BufferedReader r) { try {
String s = r.readLine();
if (s == null) r.close();
return s;
} catch (Exception __e) { throw rethrow(__e); } }
static 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 FileInputStream newFileInputStream(File path) throws IOException {
return newFileInputStream(path.getPath());
}
static FileInputStream newFileInputStream(String path) throws IOException {
FileInputStream f = new FileInputStream(path);
_registerIO(f, path, true);
return f;
}
// immutable, has strong refs
final static class _MethodCache {
final Class c;
final HashMap> cache = new HashMap();
_MethodCache(Class c) {
this.c = c;
_init();
}
void _init() {
Class _c = c;
while (_c != null) {
for (Method m : _c.getDeclaredMethods()) {
m.setAccessible(true);
multiMapPut(cache, m.getName(), m);
}
_c = _c.getSuperclass();
}
}
// Returns only matching methods
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); } }
}static abstract class VF1 {
abstract void get(A a);
}static class BetterLabel extends JLabel {
boolean autoToolTip = true;
BetterLabel() {
// Listeners given out to componentPopupMenu must not directly
// reference the outer object (-> weak map problem).
final WeakReference < BetterLabel > me = new WeakReference(this);
componentPopupMenu(this, BetterLabel_menuItems(me));
}
BetterLabel(String text) {
this();
this.setText(text);
}
public void setText(String text) {
super.setText(text);
if (autoToolTip)
if (!swic(text, "")) // HTML labels make super-huge, confusing tool tips
setToolTipText(nullIfEmpty(text));
}
}
// moved outside of class for GC reasons (see above)
static VF1 BetterLabel_menuItems(final WeakReference me) {
return new VF1() { public void get(JPopupMenu menu) { try {
addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(me.get().getText());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(me.get().getText());"; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(me..."; }};
}// elements are put to front when added (not when accessed)
static class MRUCache extends LinkedHashMap {
int maxSize = 10;
MRUCache() {}
MRUCache(int maxSize) {
this.maxSize = maxSize;}
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > maxSize;
}
}static abstract class CloseableIterableIterator extends IterableIterator implements AutoCloseable {
public void close() throws Exception {}
}static class Var implements IVar {
A v; // you can access this directly if you use one thread
Var() {}
Var(A v) {
this.v = v;}
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() { return v; }
public synchronized boolean has() { return v != null; }
public synchronized void clear() { v = null; }
public String toString() { return str(get()); }
}static class PersistableThrowable {
String className;
String msg;
String stacktrace;
PersistableThrowable() {}
PersistableThrowable(Throwable e) {
if (e == null)
className = "Crazy Null Error";
else {
className = getClassName(e).replace('/', '.');
msg = e.getMessage();
stacktrace = getStackTrace_noRecord(e);
}
}
public String toString() {
return nempty(msg) ? className + ": " + msg : className;
}
}static abstract class F0 {
abstract A get();
}static abstract class LiveValue {
abstract Class getType();
abstract A get();
abstract void onChange(Runnable l);
abstract void removeOnChangeListener(Runnable l);
void onChangeAndNow(Runnable l) {
onChange(l);
callF(l);
}
}// you still need to implement hasNext() and next()
static abstract class IterableIterator implements Iterator , Iterable {
public Iterator iterator() {
return this;
}
public void remove() {
unsupportedOperation();
}
}static interface IVar {
void set(A a);
A get();
boolean has();
void clear();
}static class Pair implements Comparable> {
A a;
B b;
Pair() {}
Pair(A a, B b) {
this.b = b;
this.a = a;}
public int hashCode() {
return hashCodeFor(a) + 2*hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Pair)) return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
public String toString() {
return "<" + a + ", " + b + ">";
}
public int compareTo(Pair p) {
if (p == null) return 1;
int i = ((Comparable ) a).compareTo(p.a);
if (i != 0) return i;
return ((Comparable) b).compareTo(p.b);
}
}
static A setToolTipText(final A c, final Object toolTip) {
if (c == null) return null;
{ swing(new Runnable() { public void run() { try {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ..."; }}); }
return c;
}
static A setToolTipText(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
static String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
static List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
static String copyTextToClipboard(String text) {
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
vmBus_send("newClipboardContents", text);
return text;
}
static void onChange(JSpinner spinner, Object r) {
spinner.addChangeListener(changeListener(r));
}
static A onChange(A b, Object r) {
b.addItemListener(itemListener(r));
return b;
}
static void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
static void onChange(final JSlider 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));"; }}); }
}
static void 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)"; }});
}
static Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static UnsupportedOperationException unsupportedOperation() {
throw new UnsupportedOperationException();
}
static int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
static boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static boolean isEmpty(Object[] a) { return a == null || a.length == 0; }
static boolean isEmpty(byte[] a) { return a == null || a.length == 0; }
static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static ChangeListener changeListener(final Object r) {
return new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(r);
}
};
}
static ItemListener itemListener(final Object r) {
return new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pcallF(r);
}
};
}
// action = runnable or method name
static 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) // JCheckBox and others
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
call(r);
}
});
else
print("Warning: onUpdate doesn't know " + getClassName(c));
}
static void onUpdate(List extends JComponent> l, Object r) {
for (JComponent c : l)
onUpdate(c, r);
}
static boolean isEditableComboBox(final JComboBox cb) {
return cb != null && swing(new F0() { Boolean get() { try { return cb.isEditable(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret cb.isEditable();"; }});
}
static JTextField textFieldFromComboBox(JComboBox cb) {
return (JTextField) cb.getEditor().getEditorComponent();
}
static 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 Iterator emptyIterator() {
return Collections.emptyIterator();
}
static String selectedItem(JList l) {
return getSelectedItem(l);
}
static String selectedItem(JComboBox cb) {
return getSelectedItem(cb);
}
}