Warning : session_start(): open(/var/lib/php/sessions/sess_p90l4ditnchkmtt23hhnnkgmaf, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import javax.swing.undo.UndoManager;
import java.awt.datatransfer.StringSelection;
import java.nio.file.Path;
class main {
static class ProgramPackager {
File jarFile;
String mainProgramID;
String mainClassName;
Set excludeSnippets;
Collection extraSnippets;
// setting this to false currently breaks everything because transpilation MD5s are no longer available
boolean includeSources = true;
boolean includeBinaries = false;
boolean includeCompiler = true;
VF1 copyAdditionalFiles = new VF1() { public void get(ZipOutputStream jar) { try {
file2zip(jar, programFile("gazelle-concepts.zip"));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "file2zip(jar, programFile(\"gazelle-concepts.zip\"));"; }};
ProgramPackager(File jarFile, String mainProgramID, String mainClassName) {
this.mainClassName = mainClassName;
this.mainProgramID = mainProgramID;
this.jarFile = jarFile;}
ProgramPackager(File jarFile, String mainProgramID) {
this.mainProgramID = mainProgramID;
this.jarFile = jarFile;
mainClassName = tok_mainClassNameFromJavaXSnippet(mainProgramID);
//assertNotNull("Please set mainClassName in " + mainProgramID, mainClassName);
if (mainClassName == null) mainClassName = "main";
}
Set snippetIDs;
Map> trace;
void go() { try {
Pair programJarAndSrc = CompilerBot.compileSnippet2(mainProgramID);
if (snippetIDs == null) {
IProgressShower p = tempProgressBar("Collecting dependencies", 100); try {
trace = new HashMap();
snippetIDs = recursivelyCollectSnippetIDsFromTranspiled_multi(
itemPlusList(mainProgramID, extraSnippets),
"trace_out" , minimalNotifyingMap(trace, new Runnable() { public void run() { try {
p.setValue(l(trace));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "p.setValue(l(trace));"; }}),
"exclude" , excludeSnippets);
} finally { _close(p); }}
IProgressShower p = tempProgressBar("JAR", or_nonZeroLong(fileSize(jarFile), megabytes(30))); try {
{
ZipOutputStream jar = zipOutputStream(jarFile); try {
AutoCloseable __1 = tempShowFileSizeProgress(p, jarFile); try {
makeManifestWithMainClass(jar, mainClassName);
zip2zip_exceptManifest2(programJarAndSrc.a, jar,
// exclude those:
litset("main.java"));
zip_addTextFile(jar, "back-references.txt",
renderMap_colon_lines(reverseMultiMap_tree(pseudoToRealMultiMap(trace)).data));
Map titles = getSnippetTitles_cached(snippetIDs);
zip_addTextFile(jar, "snippet-titles.struct", indentedStruct(titles));
TreeMap types = new TreeMap();
for (String snippetID : snippetIDs) {
{ if (isPseudoSnippetID(snippetID)) continue; }
int type = getSnippetType(snippetID);
types.put(snippetID, type);
if (type == snippetType_image()) {
File img = loadLibrary(snippetID);
addFileToZip(jar, img, psI(snippetID) + "." + (isGIF(img) ? "gif" : "png"));
} else if (type == snippetType_data())
addFileToZip(jar, loadLibrary(snippetID), psI(snippetID) + ".bin");
else try {
String text = loadSnippet(snippetID);
if (text != null)
zip_addTextFile(jar, psI(snippetID) + ".text", text);
if (isJavaxCompilableSnippetTypeExceptInclude(type)) {
if (includeSources) {
String transpilation = getServerTranspiled2(snippetID);
zip_addTextFile(jar, psI(snippetID) + ".transpiled", transpilation);
}
if (includeBinaries && !sameSnippetID(snippetID, mainProgramID)) {
File snippetJar = pairA(hotwire_compile(snippetID));
print("Adding binary: " + snippetID + " / " + f2s(snippetJar));
file2zip(jar, snippetJar);
}
}
} catch (Throwable __e) { _handleException(__e); }
}
//S typeStruct = indentedStruct(types);
String typeStruct = "tm{\n" +
mapToLines(types,
(snippetID, type) -> " " + quote(snippetID) + "=" + type + ", //" + snippetTypeName(type))
+ "}";
zip_addTextFile(jar, "snippet-types.struct", typeStruct);
File javaxJar = pathToJavaxJar();
print("Copying: " + javaxJar);
if (!includeCompiler)
zip2zip_withPredicate(javaxJar, jar, s ->
!startsWithOneOf(s, "META-INF/", "org/eclipse/")
&& !eq(s, "transpilationDate"));
else
zip2zip_exceptManifest2(javaxJar, jar, litset("transpilationDate"));
callF(copyAdditionalFiles, jar);
} finally { _close(__1); }} finally { _close(jar); }} // jar close
makeExecutable(jarFile);
fileSavedInfoBox(jarFile);
} finally { _close(p); }} catch (Exception __e) { throw rethrow(__e); } }
}
static void file2zip(ZipOutputStream outZip, File f, String name) {
addFileToZip(outZip, f, name);
}
static void file2zip(ZipOutputStream outZip, File f) {
addFileToZip(outZip, f);
}
static File programFile(String name) {
return prepareProgramFile(name);
}
static File programFile(String progID, String name) {
return prepareProgramFile(progID, name);
}
static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
static String tok_mainClassNameFromJavaXSnippet(String snippetID) {
return secondJavaToken(jextract("mainClassName ", loadSnippet(snippetID)));
}
static IProgressShower tempProgressBar(String text) {
return tempProgressBar(text, 1);
}
static IProgressShower tempProgressBar(String text, double total) {
JProgressBar bar = showProgressWindow(text, total);
return new IProgressShower() {
public void setValue(double value) {
setProgressBarValue(bar, iround(value));
}
public void setTotal(double total) {
setProgressBarTotal(bar, iround(total));
}
public void setText(String text) {
setProgressBarText(bar, text);
}
public void close() {
disposePIFrame(bar);
}
};
}
// optional parameter trace_out for collecting the reference tree
// optional parameter exclude: set of excluded
static Set recursivelyCollectSnippetIDsFromTranspiled_multi(Collection snippetIDs, Object... __) {
Set exclude = (Set) (optPar("exclude",__));
return transitiveHullOfFunction_multipleInputs(new F1>() { public Collection get(String snippetID) { try {
return collectionMinusSet(collectSnippetIDsInTranspiledSnippet(snippetID), exclude);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "collectionMinusSet(collectSnippetIDsInTranspiledSnippet(snippetID), exclude)"; }}, snippetIDs, __);
}
static List itemPlusList(A a, Collection l) {
return concatLists(ll(a), l);
}
static Map minimalNotifyingMap(Map map, Runnable notify) {
return new AbstractMap () {
public Set> entrySet() { throw unimplemented(); }
public B put(A a, B b) {
B result = map.put(a, b);
pcallF(notify);
return result;
}
};
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(short[] a) { return a == null ? 0 : a.length; }
static int l(long[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(double[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Iterator i) { return iteratorCount_int_close(i); } // consumes the iterator && closes it if possible
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); }
static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o == null ? 0
: o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: o instanceof Collection ? l((Collection) o)
: o instanceof Object[] ? l((Object[]) o)
: o instanceof boolean[] ? l((boolean[]) o)
: o instanceof byte[] ? l((byte[]) o)
: o instanceof char[] ? l((char[]) o)
: o instanceof short[] ? l((short[]) o)
: o instanceof int[] ? l((int[]) o)
: o instanceof float[] ? l((float[]) o)
: o instanceof double[] ? l((double[]) o)
: o instanceof long[] ? l((long[]) o)
: (Integer) call(o, "size");
}
static void _close(AutoCloseable c) {
if (c != null) try {
c.close();
} catch (Throwable e) {
// Some classes stupidly throw an exception on double-closing
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else throw rethrow(e);
}
}
static long or_nonZeroLong(long a, long b) {
return a != 0 ? a : b;
}
static long fileSize(String path) { return getFileSize(path); }
static long fileSize(File f) { return getFileSize(f); }
static long megabytes(long n) {
return n*(1024*1024);
}
static ZipOutputStream zipOutputStream(String path) {
return newZipOutputStream(path);
}
static ZipOutputStream zipOutputStream(File zip) {
return newZipOutputStream(zip);
}
static AutoCloseable tempShowFileSizeProgress(IProgressShower p, File f, Object... __) {
if (p == null || f == null) return null;
return timerAsAutocloseable(doEvery(optPar("interval",__, 100), new Runnable() { public void run() { try {
p.setValue(fileSize(f));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "p.setValue(fileSize(f));"; }}));
}
static void makeManifestWithMainClass(ZipOutputStream outZip, String mainClass) { try {
outZip.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
outZip.write(toUtf8("Manifest-Version: 1.0\n" +
"Main-Class: " + mainClass + "\n\n"));
} catch (Exception __e) { throw rethrow(__e); } }
static void zip2zip_exceptManifest2(File inZip, ZipOutputStream outZip, Set filesWritten) { try {
ZipFile zipFile = new ZipFile(inZip);
try {
Enumeration entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.isDirectory()) continue;
//if (eq(entry.getName(), "META-INF/MANIFEST.MF")) continue;
if (startsWith(entry.getName(), "META-INF/")) continue;
if (!filesWritten.add(entry.getName())) continue;
outZip.putNextEntry(new ZipEntry(entry.getName()));
copyStreamAndCloseInput(zipFile.getInputStream(entry), outZip);
}
} finally {
zipFile.close();
}
} catch (Exception __e) { throw rethrow(__e); } }
static HashSet litset(A... items) {
return lithashset(items);
}
static void zip_addTextFile(ZipOutputStream outZip, String name, String text) { try {
if (text == null) return;
outZip.putNextEntry(new ZipEntry(name));
byte[] utf8 = toUtf8(text);
outZip.write(utf8, 0, l(utf8));
} catch (Exception __e) { throw rethrow(__e); } }
static String renderMap_colon_lines(Map map) {
return lines(mapMapToList(new F2() { public Object get(Object a, Object b) { try { return str(a) + ": " + str(b); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "str(a) + \": \" + str(b)"; }}, map));
}
static MultiMap reverseMultiMap_tree(MultiMap map) {
MultiMap mm = (MultiMap) treeMultiMap();
for (A key : keys(map))
for (B value : map.get(key))
mm.put(value, key);
return mm;
}
static > MultiMap pseudoToRealMultiMap(Map map) {
MultiMap mm = new MultiMap();
for (A key : keys(map))
mm.putAll(key, map.get(key));
return mm;
}
static Map getSnippetTitles_cached(Collection ids) { try {
List remaining = new ArrayList();
HashMap map = new HashMap();
for (String id : ids) {
String title = getSnippetTitle_cached_probe(id);
if (title != null)
map.put(fsI(id), title);
else
remaining.add(id);
}
Map map2 = getSnippetTitles(remaining);
for (String id : keys(map2))
getSnippetTitle_cached_put(id, map2.get(id));
map.putAll(map2);
return map;
} catch (Exception __e) { throw rethrow(__e); } }
static String indentedStruct(Object o) {
return indentedStructure(o);
}
static boolean isPseudoSnippetID(String s) {
return sameSnippetID(s, "#3999999");
}
static int getSnippetType(String id) {
if (!isSnippetID(id)) return 0;
return getSnippetType(psI(id));
}
static int getSnippetType(long id) {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.getSnippetType(fsI(id));
return getSnippetType_noResourceLoader(id);
}
static int getSnippetType_noResourceLoader(long id) { try {
if (isLocalSnippetID(id)) return localSnippetType(id);
if (isGeneralFileServerSnippet(id)) return snippetType_data();
if (isImageServerSnippet(id)) return snippetType_image();
return parseInt(trim(loadPageSilently(new URL(tb_mainServer() + "/tb-int/getfield.php?id=" + id + "&field=type" + standardCredentials()))));
} catch (Exception __e) { throw rethrow(__e); } }
static int snippetType_image() {
return 23;
}
static File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
static void addFileToZip(ZipOutputStream outZip, File f, String name) { try {
ping();
if (f == null || !f.isFile()) return;
AutoCloseable __1 = smartZipCompressionLevel(outZip, f); try {
outZip.putNextEntry(new ZipEntry(name));
copyFileToStream(f, outZip);
} finally { _close(__1); }} catch (Exception __e) { throw rethrow(__e); } }
static void addFileToZip(ZipOutputStream outZip, File f) {
if (f == null) return;
addFileToZip(outZip, f, f.getName());
}
static long psI(String snippetID) {
return parseSnippetID(snippetID);
}
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 int snippetType_data() {
return 37;
}
static boolean preferCached = false;
static boolean loadSnippet_debug = false;
static ThreadLocal loadSnippet_silent = new ThreadLocal();
static ThreadLocal loadSnippet_publicOnly = new ThreadLocal();
static int loadSnippet_timeout = 30000;
static String loadSnippet(String snippetID) { try {
if (snippetID == null) return null;
return loadSnippet(parseSnippetID(snippetID), preferCached);
} catch (Exception __e) { throw rethrow(__e); } }
static String loadSnippet(String snippetID, boolean preferCached) throws IOException {
return loadSnippet(parseSnippetID(snippetID), preferCached);
}
static IF1 loadSnippet;
static String loadSnippet(long snippetID) { return loadSnippet != null ? loadSnippet.get(snippetID) : loadSnippet_base(snippetID); }
final static String loadSnippet_fallback(IF1 _f, long snippetID) { return _f != null ? _f.get(snippetID) : loadSnippet_base(snippetID); }
static String loadSnippet_base(long snippetID) { try {
return loadSnippet(snippetID, preferCached);
} catch (Exception __e) { throw rethrow(__e); } }
static String loadSnippet(long snippetID, boolean preferCached) throws IOException {
if (isLocalSnippetID(snippetID))
return loadLocalSnippet(snippetID);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadSnippet(fsI(snippetID));
return loadSnippet_noResourceLoader(snippetID, preferCached);
}
static String loadSnippet_noResourceLoader(long snippetID, boolean preferCached) throws IOException {
String text;
// boss bot (old concept)
/*text = getSnippetFromBossBot(snippetID);
if (text != null) return text;*/
initSnippetCache();
text = DiskSnippetCache_get(snippetID);
if (preferCached && text != null)
return text;
try {
if (loadSnippet_debug && text != null) System.err.println("md5: " + md5(text));
String url = tb_mainServer() + "/getraw.php?id=" + snippetID + "&utf8=1";
if (nempty(text)) url += "&md5=" + md5(text);
if (!isTrue(loadSnippet_publicOnly.get()))
url += standardCredentials();
String text2 = loadSnippet_loadFromServer(url);
boolean same = eq(text2, "==*#*==");
if (loadSnippet_debug) print("loadSnippet: same=" + same);
if (!same) text = text2;
} catch (RuntimeException e) {
e.printStackTrace();
throw new IOException("Snippet #" + snippetID + " not found or not public");
}
try {
initSnippetCache();
DiskSnippetCache_put(snippetID, text);
} catch (IOException e) {
System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")");
}
return text;
}
static File DiskSnippetCache_dir;
public static void initDiskSnippetCache(File dir) {
DiskSnippetCache_dir = dir;
dir.mkdirs();
}
public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
}
private static File DiskSnippetCache_getFile(long snippetID) {
return new File(DiskSnippetCache_dir, "" + snippetID);
}
public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
}
public static File DiskSnippetCache_getDir() {
return DiskSnippetCache_dir;
}
public static void initSnippetCache() {
if (DiskSnippetCache_dir == null)
initDiskSnippetCache(getGlobalCache());
}
static String loadSnippet_loadFromServer(String url) {
Integer oldTimeout = setThreadLocal(loadPage_forcedTimeout_byThread, loadSnippet_timeout);
try {
return isTrue(loadSnippet_silent.get()) ? loadPageSilently(url) : loadPage(url);
} finally {
loadPage_forcedTimeout_byThread.set(oldTimeout);
}
}
static boolean isJavaxCompilableSnippetTypeExceptInclude(int type) {
return isJavaxApplicationSnippetType(type)
|| isJavaxModuleSnippetType(type)
|| type == snippetType_dynModule();
}
static boolean getServerTranspiled2_allowLocalFallback = true, getServerTranspiled2_localFallbackVerbose = true;
// to avoid checking server for transpilations too often when booting OS
static Map getServerTranspiled2_tempCache;
static String getServerTranspiled2(String id) {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.getTranspiled(id);
return getServerTranspiled2_noResourceLoader(id);
}
static String getServerTranspiled2_noResourceLoader(String id) {
id = fsIOpt(id);
String transpiled = mapGet(getServerTranspiled2_tempCache, id);
if (transpiled != null) return transpiled;
//if (getServerTranspiled2_tempCache != null) print("CACHE FAIL on " + id);
transpiled = loadCachedTranspilation(id);
String md5 = null;
if (machineIsOffline() || isOfflineMode() || isLocalSnippet(id)) return transpiled;
if (transpiled != null)
md5 = md5(transpiled);
String transpiledSrc;
try {
transpiledSrc = getServerTranspiled(formatSnippetID(id), md5);
} catch (Throwable e) {
if (!getServerTranspiled2_allowLocalFallback) rethrow(e);
printExceptionShort(e);
if (getServerTranspiled2_localFallbackVerbose) print("Fallback to local code");
return transpiled;
}
if (eq(transpiledSrc, "SAME")) {
if (!isTrue(loadPage_silent.get())) print("SAME");
return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiled);
}
return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiledSrc);
}
static boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b)) return false;
return parseSnippetID(a) == parseSnippetID(b);
}
static A pairA(Pair p) {
return p == null ? null : p.a;
}
static Object hotwire_onCompile; // voidfunc(Pair)
static boolean hotwire_serially = false;
static Lock hotwire_overInternalBot_lock = lock();
static boolean hotwire_compileOnServer = false;
static Class> hotwire_overInternalBot(String progID) {
return hotwire_overInternalBot(progID, "main");
}
static Class> hotwire_overInternalBot(String progID, String mainClass) { try {
Pair p;
try {
p = hotwire_compile(progID);
} catch (Throwable e) {
throw rethrow("Error hotwiring " + progID, e);
}
File jar = p.a;
assertTrue(jar.getAbsolutePath(), jar.isFile());
List files = hotwire_collectJars(jar);
// make class loader
JavaXClassLoader classLoader = hotwire_makeClassLoader(files);
classLoader.progID = progID;
return hotwire_finish(classLoader, progID, p.b, mainClass);
} catch (Exception __e) { throw rethrow(__e); } }
// returns pair(jar, transpiled src)
static Pair hotwire_compile(String progID) {
Pair p = hotwire_compileOnServer && !isLocalSnippetID(progID)
? compileSnippetThroughServer(progID)
: CompilerBot.compileSnippet2(progID);
Lock __0 = hotwire_serially ? hotwire_overInternalBot_lock : null; lock(__0); try {
callF(hotwire_onCompile, p);
return p;
} finally { unlock(__0); } }
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
static boolean print_silent = false; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal print_byThread; // special handling by thread - prefers F1
static volatile Object print_allThreads;
static volatile Object print_preprocess;
static void print() {
print("");
}
static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
// slightly overblown signature to return original object...
static A print(A o) {
ping_okInCleanUp();
if (print_silent) return o;
String s = o + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
try {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null) f = print_allThreads;
if (f != null)
// We do need the general callF machinery here as print_byThread is sometimes shared between modules
if (isFalse(
f instanceof F1 ? ((F1) f).get(s) :
callF(f, s))) return;
} catch (Throwable e) {
System.out.println(getStackTrace(e));
}
print_raw(s);
}
static void print_raw(String s) {
if (print_preprocess != null) s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
vmBus_send("printed",mc(), s);
}
static void print_autoRotate() {
}
static String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static String f2s(String s) { return f2s(newFile(s)); }
static String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));
static boolean _handleException_showThreadCancellations = false;
static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException) {
if (_handleException_showThreadCancellations)
System.out.println(getStackTrace_noRecord(e2));
return;
}
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
try {
printStackTrace2(e3); // not using pcall here - it could lead to endless loops
} catch (Throwable e4) {
System.out.println(getStackTrace(e3));
System.out.println(getStackTrace(e4));
}
}
}
static List mapToLines(Map map) {
List l = new ArrayList();
for (Object key : keys(map))
l.add(str(key) + " = " + str(map.get(key)));
return l;
}
static String mapToLines(Map map, Object f) {
return lines(map(map, f));
}
static String mapToLines(Object f, Map map) {
return lines(map(map, f));
}
static String mapToLines(Object f, Iterable l) {
return lines(map(f, l));
}
static String mapToLines(Iterable l, IF1 f) {
return mapToLines((Object) f, l);
}
static String mapToLines(IF1 f, Iterable l) {
return mapToLines((Object) f, l);
}
static String mapToLines(Map map, IF2 f) {
return lines(map(map, f));
}
static String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder((int) (l(s)*1.5+2));
quote_impl(s, out);
return out.toString();
}
static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\t')
out.append("\\t");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static String snippetTypeName_data = "\r\n [0] ? [80] New Tinybrain snippet [50] Microtheory [100] Document [52] User-supplied dialog [34] JavaX source code [42] JavaX fragment (include) [55] JavaX source code (desktop) [57] JavaX source code (Dynamic Module) [43] JavaX (incomplete) [38] JavaX translator [40] JavaX source code (Android) [54] JavaX module [47] JavaX General Test Case [39] JavaX (input.txt to output.txt) [44] JavaX (snippet commenter) [41] IOIOI [45] Question [48] Natural language [81] Space for snippets [101] Task description [51] Simplified Natural Language [7] Lua code [26] Lua code - Image recognition [12] Lua code - Image [28] Lua code - Visualizer [30] Lua code - Image transformer [8] Lua code - Chat-bot [9] Lua code - Test case [13] Lua code - Animation [14] Lua code - GUI [17] Lua code - System test [18] Lua code - Service bot [19] Lua code - Suggester [27] Lua code - Snippet commenter [29] Lua code - Snippet producer [31] Lua code - Image distinction (learner) [32] Lua code - Image distinction (executor) [33] Lua code - Snippet-to-snippet [24] Java GUI source (Text2GUI/Janino) [21] Java source code [25] Java image recognition code [22] Pseudo code [35] HTML [23] Image [20] Run Log [46] Information [37] Data [1] TB declarations [2] TB test case [3] Comment [4] Run report [5] Source file [6] TB solution tree [16] Input/output example [11] Object [102] Directory [103] Snippet type [104] Image recognition task [49] Blog post [53] AI Concepts [56] AI Drawing \r\n";
static Map snippetTypeName_map;
static String snippetTypeName(int type) {
if (snippetTypeName_map == null)
snippetTypeName_map = mapKeys("parseInt", pairsToMap(map("listToPair",regexpAllGroups(">\\[(\\d+)\\] ([^>]+)<", snippetTypeName_data))));
return snippetTypeName_map.get(type);
}
/*static S snippetTypeName(S type) {
ret snippetTypeName(parseIntOpt(type));
}*/
static File pathToJavaxJar() {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.pathToJavaXJar();
return pathToJavaxJar_noResourceLoader();
}
static File pathToJavaxJar_noResourceLoader() { try {
int x = latestInstalledJavaX();
File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar");
if (!xfile.isFile()) {
print("Saving " + f2s(xfile));
String url = x30JarServerURL();
byte[] data = loadBinaryPage(url);
if (data.length < 1000000)
throw fail("Could not load " + url);
saveBinaryFile(xfile.getPath(), data);
}
return xfile;
} catch (Exception __e) { throw rethrow(__e); } }
static void zip2zip_withPredicate(File inZip, ZipOutputStream outZip, IF1 predicate) { try {
ZipFile zipFile = new ZipFile(inZip);
Enumeration entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
{ if (!(predicate.get(entry.getName()))) continue; }
outZip.putNextEntry(new ZipEntry(entry.getName()));
InputStream fin = zipFile.getInputStream(entry);
copyStream(fin, outZip);
fin.close();
}
zipFile.close();
} catch (Exception __e) { throw rethrow(__e); } }
static void zip2zip_withPredicate(File inZip, File outZip, IF1 predicate) {
ZipOutputStream outStream = zipOutputStream(outZip); try {
zip2zip_withPredicate(inZip, outStream, predicate);
} finally { _close(outStream); }}
static boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x)) return true; return false;
}
static boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m)) return true; return false;
}
static boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static Map> callF_cache = newDangerousWeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static A callF(IF0 f) {
return f == null ? null : f.get();
}
static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Object f, Object... args) {
if (f instanceof String)
return callMCWithVarArgs((String) f, args); // possible SLOWDOWN over callMC
return safeCallF(f, args);
}
static Object safeCallF(Object f, Object... args) {
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1) return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
}
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static void makeExecutable(File file) { try {
if (!isWindows())
try {
makeExecutable_java7(file);
} catch (Throwable _e) {
warn("Java 6 fallback for makeExecutable");
backtick("chmod a+rx " + bashQuote(file));
}
} catch (Exception __e) { throw rethrow(__e); } }
static void fileSavedInfoBox(File f) {
infoBox("Saved " + fileInfo(f));
}
static int loadPage_defaultTimeout = 60000;
static ThreadLocal loadPage_charset = new ThreadLocal();
static boolean loadPage_allowGzip = true, loadPage_debug;
static boolean loadPage_anonymous = false; // don't send computer ID
static int loadPage_verboseness = 100000;
static int loadPage_retries = 1; //60; // seconds
static ThreadLocal loadPage_silent = new ThreadLocal();
static volatile int loadPage_forcedTimeout; // ms
static ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal(); // ms
static ThreadLocal>> loadPage_responseHeaders = new ThreadLocal();
static ThreadLocal> loadPage_extraHeaders = new ThreadLocal();
static ThreadLocal loadPage_sizeLimit = new ThreadLocal();
public static String loadPageSilently(String url) { try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (Exception __e) { throw rethrow(__e); } }
public static String loadPageSilently(URL url) { try {
if (!networkAllowanceTest(str(url))) throw fail("Not allowed: " + url);
IOException e = null;
for (int tries = 0; tries < loadPage_retries; tries++)
try {
URLConnection con = loadPage_openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPageThroughProxy_enabled) {
print("Trying proxy because of: " + e);
try {
return loadPageThroughProxy(str(url));
} catch (Throwable e2) {
print(" " + exceptionToStringShort(e2));
}
} else if (loadPage_debug)
print(exceptionToStringShort(e));
if (tries < loadPage_retries-1) sleepSeconds(1);
}
throw e;
} catch (Exception __e) { throw rethrow(__e); } }
static String loadPage_preprocess(String url) {
if (url.startsWith("tb/")) // don't think we use this anymore
url = tb_mainServer() + "/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
static String loadPage(String url) { try {
url = loadPage_preprocess(url);
if (!isTrue(loadPage_silent.get()))
printWithTime("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (Exception __e) { throw rethrow(__e); } }
static String loadPage(URL url) {
return loadPage(url.toExternalForm());
}
static String loadPage(URLConnection con, URL url) throws IOException {
return loadPage(con, url, true);
}
static String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
Long limit = optPar(loadPage_sizeLimit);
if (addHeaders) try {
if (!loadPage_anonymous)
setHeaders(con);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
con.setRequestProperty("X-No-Cookies", "1");
for (String key : keys(extraHeaders))
con.setRequestProperty(key, extraHeaders.get(key));
} catch (Throwable e) {} // fails if within doPost
vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
loadPage_responseHeaders.set(con.getHeaderFields());
InputStream in = null;
try {
in = urlConnection_getInputStream(con);
//vm_generalSubMap("InputStream per thread").put(currentThread(), in);
if (loadPage_debug)
print("Put stream in map: " + currentThread());
String contentType = con.getContentType();
if (contentType == null) {
//printStruct("Headers: ", con.getHeaderFields());
throw new IOException("Page could not be read: " + hideCredentials(url));
}
//print("Content-Type: " + contentType);
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null) charset = loadPage_guessCharset(contentType);
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = newGZIPInputStream(in);
}
Reader r;
try {
r = new InputStreamReader(in, unquote(charset));
} catch (UnsupportedEncodingException e) {
print(toHex(utf8(charset)));
throw e;
}
boolean silent = isTrue(loadPage_silent.get());
StringBuilder buf = new StringBuilder();
int n = 0;
while (limit == null || n < limit) {
ping();
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
if (!silent && (n % loadPage_verboseness) == 0)
print(" " + n + " chars read");
}
return buf.toString();
} finally {
if (loadPage_debug)
print("loadPage done");
//vm_generalSubMap("InputStream per thread").remove(currentThread());
vm_generalSubMap("URLConnection per thread").remove(currentThread());
if (in != null) in.close();
}
}
static String loadPage_guessCharset(String contentType) {
Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
String match = m.matches() ? m.group(1) : null;
if (loadPage_debug)
print("loadPage: contentType=" + contentType + ", match: " + match);
/* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
//return or(match, "ISO-8859-1");
return or(match, "UTF-8");
}
static URLConnection loadPage_openConnection(URL url) {
URLConnection con = openConnection(url);
int timeout = toInt(loadPage_forcedTimeout_byThread.get());
if (timeout == 0) timeout = loadPage_forcedTimeout;
if (timeout != 0)
setURLConnectionTimeouts(con, loadPage_forcedTimeout);
else
setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
return con;
}
static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static int parseInt(char c) {
return Integer.parseInt(str(c));
}
static File prepareProgramFile(String name) {
return mkdirsForFile(getProgramFile(name));
}
static File prepareProgramFile(String progID, String name) {
return mkdirsForFile(getProgramFile(progID, name));
}
static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
static String secondJavaToken(String s) {
return second(javaTokC_iterator(s));
}
// returns from C to C
static String jextract(String pat, String s) {
return jextract(pat, javaTok(s));
}
static String jextract(String pat, List tok) {
List tokpat = javaTok(pat);
jfind_preprocess(tokpat);
int i = jfind(tok, tokpat);
if (i < 0) return null;
int j = i + l(tokpat) - 2;
return joinSubList(tok, i, j);
}
static JProgressBar showProgressWindow(double maxValue) {
return showProgressWindow(null, maxValue);
}
static JProgressBar showProgressWindow(String text, double maxValue) {
JProgressBar bar = jProgressBarWithText(iround(maxValue));
swingCall(bar, "setString", text);
centerFrame(packFrameVertically(500, showFrame(bar)));
return bar;
}
static void setProgressBarValue(JProgressBar bar, int value) {
swingCall(bar, "setValue", value);
}
static void setProgressBarValue(JProgressBar bar, int value, int total) {
setProgressBarTotal(bar, total);
setProgressBarValue(bar, value);
}
static int iround(double d) {
return (int) Math.round(d);
}
static int iround(Number n) {
return iround(toDouble(n));
}
static void setProgressBarTotal(JProgressBar bar, int total) {
swingCall(bar, "setMaximum", total);
}
static void setProgressBarText(JProgressBar bar, String text) {
swingCall(bar, "setString", text);
}
static void disposePIFrame(Component c) {
disposePossiblyInternalFrame(c);
}
static A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
static A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
static Object optPar(Object[] params, String name) {
return optParam(params, name);
}
static Object optPar(String name, Object[] params) {
return optParam(params, name);
}
static Object optPar(String name, Map params) {
return optParam(name, params);
}
static A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
static A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
// f : A -> Collection
// trace_out collects what the function returns
static Set transitiveHullOfFunction_multipleInputs(Object f, Collection inputs, Object... __) {
final HashSet seen = asHashSet(inputs);
final Integer max = (Integer) (optPar("max",__));
Map trace_out = (Map) (optPar("trace_out",__));
// Make pool of iterators
final LinkedList> pool = new LinkedList();
for (A input : unnull(inputs))
pool.add(iterator((Iterable) callF(f, input)));
int n = 0;
while (!empty(pool) && (max == null || n < max)) { ping();
Iterator it = first(pool);
if (!it.hasNext()) { removeFirst(pool); continue; }
// Get entry and check if seen already
A entry = it.next();
if (!seen.add(entry)) continue;
// found new entry - return and schedule for further analysis
Collection newStuff = (Collection ) (callF(f, entry));
mapPut(trace_out, entry, newStuff);
if (nempty(newStuff))
pool.add(iterator(newStuff));
++n;
}
return seen;
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o == null) return null;
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static Object get_raw(Object o, String field) { try {
if (o == null) return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static Object get(String field, Object o) {
return get(o, field);
}
static Collection collectionMinusSet(Collection l, Collection stuff) {
if (empty(stuff)) return l;
Set set = asSet(stuff);
Collection l2 = similarEmptyCollection(l);
for (A a : l) if (!set.contains(a)) l2.add(a);
return l2;
}
static Set collectSnippetIDsInTranspiledSnippet(String snippetID) {
if (isImageSnippetID(snippetID)) return new HashSet();
int type = getSnippetType(snippetID);
if (!isJavaxCompilableSnippetTypeExceptInclude(type))
return new HashSet();
String src = getServerTranspiled2(snippetID);
//Set set = collectSnippetIDsInText(src);
Set set = collectSnippetIDsInJavaSource(dropFirstLine(src)); // skip comments
List libs = map("fsI",regexpAll("[0-9]+", firstLine(src)));
print("Libs for " + snippetID + ": " + libs);
addAll(set, libs);
return set;
}
static List concatLists(Iterable ... lists) {
List l = new ArrayList();
if (lists != null) for (Iterable list : lists)
addAll(l, list);
return l;
}
static List concatLists(Collection extends Iterable > lists) {
List l = new ArrayList();
if (lists != null) for (Iterable list : lists)
addAll(l, list);
return l;
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
static Set> entrySet(Map map) {
return _entrySet(map);
}
static RuntimeException unimplemented() {
throw fail("TODO");
}
static RuntimeException unimplemented(String msg) {
throw fail("TODO: " + msg);
}
static void put(Map map, A a, B b) {
if (map != null) map.put(a, b);
}
static void put(List l, int i, A a) {
if (l != null && i >= 0 && i < l(l)) l.set(i, a);
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static A pcallF(F0 f) { try {
return f == null ? null : f.get();
} catch (Throwable __e) { return null; } }
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static void pcallF(VF1 f, A a) {
try {
{ if (f != null) f.get(a); }
} catch (Throwable __e) { _handleException(__e); }
}
static B pcallF(IF1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static int iteratorCount_int_close(Iterator i) { try {
int n = 0;
if (i != null) while (i.hasNext()) { i.next(); ++n; }
if (i instanceof AutoCloseable) ((AutoCloseable) i).close();
return n;
} catch (Exception __e) { throw rethrow(__e); } }
static Object call(Object o) {
return callF(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
//ret call_cached(o, method, args);
return call_withVarargs(o, method, args);
}
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 ZipOutputStream newZipOutputStream(String path) {
return newZipOutputStream(new File(path));
}
static ZipOutputStream newZipOutputStream(File zip) { try {
return new ZipOutputStream(newFileOutputStream(zip));
} catch (Exception __e) { throw rethrow(__e); } }
static AutoCloseable timerAsAutocloseable(final java.util.Timer timer) {
return timer == null ? null : new AutoCloseable() {
public void close() {
timer.cancel();
}
};
}
// firstDelay = delay
static FixedRateTimer doEvery(long delay, final Object r) {
return doEvery(delay, delay, r);
}
static FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
return vmBus_timerStarted(timer);
}
// reversed argument order for fun
static FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
}
static FixedRateTimer doEvery(double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), r);
}
static byte[] toUtf8(String s) { try {
return s.getBytes(utf8charset());
} catch (Exception __e) { throw rethrow(__e); } }
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
m.m = new String[] {substring(a, strL(b))};
return true;
}
static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a)) return false;
for (int i = 0; i < listL(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static void copyStreamAndCloseInput(InputStream in, OutputStream out) { try {
try {
copyStream(in, out);
} finally {
in.close();
}
} catch (Exception __e) { throw rethrow(__e); } }
static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
static String lines(Iterable lines) { return fromLines(lines); }
static String lines(Object[] lines) { return fromLines(asList(lines)); }
static List lines(String s) { return toLines(s); }
// f: func(key, value) -> entry
static List mapMapToList(Map map, Object f) {
return map(map, f);
}
static List mapMapToList(Object f, Map map) {
return map(f, map);
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static MultiMap treeMultiMap() {
return new MultiMap(true);
}
static MultiMap treeMultiMap(Comparator comparator) {
return new MultiMap(new TreeMap >(comparator));
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
// convenience shortcut for keys_gen
static Set keys(Object map) {
return keys((Map) map);
}
static Set keys(MultiMap mm) {
return mm.keySet();
}
static SnippetTitles getSnippetTitle_cached_cache = new SnippetTitles();
static String getSnippetTitle_cached(String id) {
return getSnippetTitle_cached_cache.get(id);
}
static void getSnippetTitle_cached_put(String id, String title) {
getSnippetTitle_cached_cache.put(id, title);
}
static boolean getSnippetTitle_cached_has(String id) {
return getSnippetTitle_cached_cache.has(id);
}
static String getSnippetTitle_cached_probe(String id) {
return getSnippetTitle_cached_cache.probe(id);
}
static String fsI(String id) {
return formatSnippetID(id);
}
static String fsI(long id) {
return formatSnippetID(id);
}
static boolean getSnippetTitles_verbose = false;
static Map getSnippetTitles(Collection ids) { try {
if (empty(ids)) return new HashMap();
String url = tb_mainServer() + "/tb-int/get-titles.php";
String ids2 = join(" ", parseSnippetIDs(ids));
return trimValues(transformKeys(jsonDecodeMap(
doPost(mapPlus(standardCredentialsMap(), "ids" , ids2),
url)), new F1() { public Object get(String id) { try { return fsI(id); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "fsI(id)"; }}));
} catch (Exception __e) { throw rethrow(__e); } }
static String indentedStructure(Object o) {
return indentStructureString(struct(o));
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
static boolean isLocalSnippetID(String snippetID) {
return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID));
}
static boolean isLocalSnippetID(long snippetID) {
return snippetID >= 1000 && snippetID <= 9999;
}
static int localSnippetType(String snippetID) {
return localSnippetType(psI(snippetID));
}
static int localSnippetType(long snippetID) {
return parseIntOpt(getFileInfoField(localSnippetFile(snippetID), "Type"));
}
static boolean isGeneralFileServerSnippet(long id) {
return id >= 1400000 && id < 1500000;
}
static boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static String tb_mainServer_default = "http://code.botcompany.de:8081";
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 String standardCredentials() {
String user = standardCredentialsUser();
String pass = standardCredentialsPass();
if (nempty(user) && nempty(pass))
return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
return "";
}
static File loadBinarySnippet(String snippetID) {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
return loadBinarySnippet_noResourceLoader(snippetID);
}
static File loadBinarySnippet_noResourceLoader(String snippetID) { try {
long id = parseSnippetID(snippetID);
if (isImageServerSnippet(id)) return loadImageAsFile(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile_noResourceLoader(snippetID);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll = false;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions = false;
static Map ping_actions = newWeakHashMap();
static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized(ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static ThreadLocal smartZipCompressionLevel_on = new ThreadLocal();
static AutoCloseable smartZipCompressionLevel(ZipOutputStream zip, File f) {
return smartZipCompressionLevel(zip, fileName(f));
}
static AutoCloseable smartZipCompressionLevel(final ZipOutputStream zip, String fileName) {
if (!isTrue(smartZipCompressionLevel_on.get())) return null;
int level = Deflater.DEFAULT_COMPRESSION;
if (isImageFileName(fileName) || eqicOneOf(fileExtension(fileName), ".zip", ".jar", ".gz", ".bin")) // assume .bin is a jar snippet or some such
level = Deflater.NO_COMPRESSION;
zip.setLevel(level);
return new AutoCloseable() { public String toString() { return "zip.setLevel(Deflater.DEFAULT_COMPRESSION);"; } public void close() throws Exception { zip.setLevel(Deflater.DEFAULT_COMPRESSION); }};
}
static void copyFileToStream(File src, OutputStream out) { try {
file2stream(src, out);
} catch (Exception __e) { throw rethrow(__e); } }
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0) throw fail("0 is not a snippet ID");
return id;
}
static 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 loadLocalSnippet(String snippetID) {
return loadLocalSnippet(psI(snippetID));
}
static String loadLocalSnippet(long snippetID) {
return loadTextFile(localSnippetFile(snippetID));
}
static String md5(String text) { try {
if (text == null) return "-";
return bytesToHex(md5_impl(toUtf8(text))); // maybe different than the way PHP does it...
} catch (Exception __e) { throw rethrow(__e); } }
static String md5(byte[] data) {
if (data == null) return "-";
return bytesToHex(md5_impl(data));
}
static byte[] md5_impl(byte[] data) { try {
return MessageDigest.getInstance("MD5").digest(data);
} catch (Exception __e) { throw rethrow(__e); } }
static String md5(File file) {
return md5OfFile(file);
}
static boolean nempty(Collection c) {
return !empty(c);
}
static boolean nempty(CharSequence s) {
return !empty(s);
}
static boolean nempty(Object[] o) { return !empty(o); }
static boolean nempty(byte[] o) { return !empty(o); }
static boolean nempty(int[] o) { return !empty(o); }
static boolean nempty(Map m) {
return !empty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean nempty(Object o) { return !empty(o); }
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
if (o instanceof ThreadLocal) // TODO: remove this
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static boolean isTrue(Boolean b) {
return b != null && b.booleanValue();
}
static String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
static String loadTextFile(File f, String defaultContents) { return loadTextFile(f, defaultContents, "UTF-8"); }
static String loadTextFile(File f, String defaultContents, String encoding) { try {
checkFileNotTooBigToRead(f);
if (f == null || !f.exists()) return defaultContents;
FileInputStream fileInputStream = new FileInputStream(f);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding);
return loadTextFile(inputStreamReader);
} catch (Exception __e) { throw rethrow(__e); } }
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
static String loadTextFile(String fileName, String defaultContents) {
return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
}
static String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer)))
builder.append(buffer, 0, n);
} finally {
reader.close();
}
return str(builder);
}
/** 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); } }
static File getGlobalCache() {
File file = new File(javaxCachesDir(), "Binary Snippets");
file.mkdirs();
return file;
}
static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null) return null;
A old = tl.get();
tl.set(value);
return old;
}
static boolean isJavaxApplicationSnippetType(int type) {
return type == snippetType_javaxSource() || type == snippetType_JavaXDesktop();
}
static boolean isJavaxModuleSnippetType(int type) {
return type == snippetType_javaxModule() || type == snippetType_javaxDesktopModule();
}
static int snippetType_dynModule() {
return 57;
}
static String fsIOpt(String s) {
return formatSnippetIDOpt(s);
}
static B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
static B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
static String loadCachedTranspilation(String id) { try {
return loadTextFilePossiblyGZipped(getCachedTranspilationFile(id));
} catch (Throwable __e) { return null; } }
static boolean machineIsOffline() {
return isFalse(callF(vmGeneralMap_get("areWeOnline")));
}
static boolean isOfflineMode() {
return eq("1", trim(loadProgramTextFile("#1005806", "offline-mode")));
}
static boolean isLocalSnippet(String snippetID) {
return isLocalSnippetID(snippetID);
}
static boolean isLocalSnippet(long snippetID) {
return isLocalSnippetID(snippetID);
}
static String getServerTranspiled(String snippetID) {
return getServerTranspiled(snippetID, null);
}
static boolean getServerTranspiled_printStackTrace = false;
// returns "SAME" if md5 matches
static String getServerTranspiled(String snippetID, String expectedMD5) { try {
if (getServerTranspiled_printStackTrace) printStackTrace();
long id = parseSnippetID(snippetID);
/*S t = getTranspilationFromBossBot(id);
if (t != null) return t;*/
String text = loadPage_utf8(tb_mainServer() + "/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id + "&utf8=1"
+ (l(expectedMD5) > 1 ? "&md5=" + urlencode(expectedMD5) : "")
+ standardCredentials());
if (nempty(text) && neq(text, "SAME"))
saveTranspiledCode(snippetID, text);
return text;
} catch (Exception __e) { throw rethrow(__e); } }
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static void printExceptionShort(Throwable e) { printExceptionShort("", e); }
static void printExceptionShort(String prefix, Throwable e) {
print(prefix, exceptionToStringShort(e));
}
static B mapPut_returnValue(Map map, A key, B value) {
mapPut(map, key, value);
return value;
}
static void lock(Lock lock) { try {
ping();
if (lock == null) return;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
printStackTrace(e);
rethrow(e);
}
// NO call to ping here! Make sure lock is always released.
} catch (Exception __e) { throw rethrow(__e); } }
static void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static ReentrantLock lock() {
return fairLock();
}
static void assertTrue(Object o) {
if (!(eq(o, true) /*|| isTrue(pcallF(o))*/))
throw fail(str(o));
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static List hotwire_collectJars(File jar) {
List libIDs = hotwire_libraryIDsFromJar_deleteJarOnFail(jar);
List files = ll(jar); // main program has to be first entry! (e.g. for hotwire_makeClassLoader_stickyAndSrcLibs)
for (String libID : libIDs)
files.add(loadLibraryOrSrcLib(libID));
return files;
}
static JavaXClassLoader hotwire_makeClassLoader(List files) {
Collection toShare = hotwire_classesToShare();
return nempty(toShare)
? new JavaXClassLoaderWithParent2(null, files, myClassLoader(), cloneList(toShare))
: new JavaXClassLoader(null, files);
}
static Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource) {
return hotwire_finish(classLoader, progID, javaSource, "main");
}
static Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource, String mainClass) { try {
// load & return main class
Class> theClass = classLoader.loadClass(mainClass);
Class j = getJavaX();
setOpt(theClass, "myJavaSource_code", javaSource);
synchronized(j) { // hopefully this goes well...
call(j, "setVars", theClass, progID);
callOpt(j, "addInstance", progID, theClass);
}
hotwire_copyOver(theClass);
vmBus_send("hotwireFinished",theClass, mc());
return theClass;
} catch (Exception __e) { throw rethrow(__e); } }
// returns (jar, transpiled src)
static Pair compileSnippetThroughServer(String progID) {
String transpiledSrc = getServerTranspiled2(progID);
String md5 = md5(transpiledSrc + "\n" + progID);
File jar = CompilerBot.getJarFile(md5);
if (jar == null || jar.length() <= 22) {
byte[] jarData = null;
boolean dontLoad = false;
IResourceLoader rl = vm_getResourceLoader();
if (rl != null) {
dontLoad = true;
File jar2 = rl.getSnippetJar(progID, transpiledSrc);
if (jar2 != null) return pair(jar2, transpiledSrc);
}
if (!dontLoad) { try {
jarData = loadBinaryPage("http://www.botcompany.de/jar/" + psI(progID) + "?md5=" + md5(transpiledSrc));
} catch (Throwable __e) { _handleException(__e); }}
if (!isJAR(jarData)) {
if (jarData != null) {
print(bytesToHex(takeFirstOfByteArray(8, jarData)));
print("fallback to CompilerBot: " + fromUtf8(takeFirstOfByteArray(80, jarData)));
}
return CompilerBot.compileSnippet2(progID);
}
saveBinaryFile(jar, jarData);
}
return pair(jar, transpiledSrc);
}
static void unlock(Lock lock, String msg) {
if (lock == null) return;
lock.unlock();
print("Unlocked: " + msg); // print afterwards to make sure the lock is always unlocked
}
static void unlock(Lock lock) {
if (lock == null) return;
lock.unlock();
}
static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1));
}
static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
// this syntax should be removed...
static Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static boolean isFalse(Object o) {
return eq(false, 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());
}
static String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0) return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i+1 < l && s.charAt(i+1) == '\n') ++i;
}
}
return out.toString();
}
static void print_append(Appendable buf, String s, int max) { try {
synchronized(buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) { throw rethrow(__e); } }
static void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(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 Class mc() {
return main.class;
}
static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static File newFile(String name) {
return name == null ? null : new File(name);
}
static File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static List synchroList() {
return synchroList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static ArrayList cloneList(Collection l) {
if (l == null) return new ArrayList();
synchronized(collectionMutex(l)) {
return new ArrayList (l);
}
}
static List map(Iterable l, Object f) { return map(f, l); }
static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null) for (Object o : l)
x.add(callF(f, o));
return x;
}
static List map(Iterable l, F1 f) { return map(f, l); }
static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(callF(f, o));
return x;
}
static List map(IF1 f, Iterable l) { return map(l, f); }
static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(f.get(o));
return x;
}
static List map(IF1 f, A[] l) { return map(l, f); }
static List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(f.get(o));
return x;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }
static List map(Object f, Map map) {
return map(map, f);
}
// map: func(key, value) -> list element
static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null) for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static Map mapKeys(Object func, Map map) {
Map m = similarEmptyMap(map); // TODO: this might break when key type changes through func
for (Object key : keys(map))
m.put(callF(func, key), map.get(key));
return m;
}
static Map mapKeys(Map map, Object func) {
return mapKeys(func, map);
}
static Map mapKeys(Map map, IF1 func) {
return mapKeys(map, (Object) func);
}
static Map mapKeys(IF1 func, Map map) {
return mapKeys(map, func);
}
static HashMap pairsToMap(Collection extends Pair > l) {
HashMap map = new HashMap();
if (l != null) for (Pair p : l)
map.put(p.a, p.b);
return map;
}
static Pair listToPair(List l) {
return l(l) != 2 ? null : pair(first(l), second(l));
}
static List> regexpAllGroups(String pattern, String text) {
List> l = new ArrayList();
Matcher matcher = regexpCompile(pattern).matcher(text);
while (matcher.find())
l.add(regexpGetGroups(matcher));
return l;
}
static int latestInstalledJavaX() {
File[] files = new File(userHome(), ".javax").listFiles();
int v = 0;
if (files != null) for (File f : files) {
Matcher m = regexpMatcher("x(\\d\\d\\d?)\\.jar", f.getName());
if (m.matches())
v = Math.max(v, Integer.parseInt(m.group(1)));
}
return v;
}
static String _userHome;
static String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
static File userHome(String path) {
return new File(userDir(), path);
}
static String x30JarServerURL() {
return "http://botcompany.de:8081/x30.jar";
}
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 RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
/** 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 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 Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
static Object callMCWithVarArgs(String method, Object... args) {
return call_withVarargs(mc(), method, args);
}
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static Object invokeMethod(Method m, Object o, Object... args) { try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) { throw rethrow(__e); } }
static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive()
: isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
// Note: The error reporting only works with Java VM option --illegal-access=deny
vmBus_send("makeAccessible_error",e, f);
}
return f;
}
static Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error",e, m);
}
return m;
}
static Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error",e, c);
}
return c;
}
public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}
// requires Java 7
// assumes the file is yours
static void makeExecutable_java7(File file) { try {
if (isWindows()) return;
Set p = new HashSet(Files.getPosixFilePermissions(file.toPath()));
p.add(PosixFilePermission.OWNER_READ);
p.add(PosixFilePermission.OWNER_EXECUTE);
p.add(PosixFilePermission.GROUP_READ);
p.add(PosixFilePermission.GROUP_EXECUTE);
p.add(PosixFilePermission.OTHERS_READ);
p.add(PosixFilePermission.OTHERS_EXECUTE);
Files.setPosixFilePermissions(file.toPath(), p);
} catch (Exception __e) { throw rethrow(__e); } }
static boolean warn_on = true;
static ThreadLocal> warn_warnings = new ThreadLocal();
static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
addToCollection(warn_warnings.get(), s);
}
static int backtick_exitValue;
static boolean backtick_verbose, backtick_keepScript;
static ThreadLocal backtick_scriptFile = new ThreadLocal();
static ThreadLocal backtick_uninterruptable = new ThreadLocal(); // Great trick, thanks to Tim Bunce @ http://stackoverflow.com/questions/12856620/how-to-handle-signals-in-bash-during-synchronous-execution
static boolean backtick_win_cmd = false; // bugfixing
static String backtick(String cmd) { try {
ping();
File outFile = File.createTempFile("_backtick", "");
backtickToFile(cmd, outFile);
String result = loadTextFile(outFile.getPath(), "");
if (backtick_verbose) {
//print("backtick: script length after=" + backtick_scriptFile->length());
print("[[\n" + result + "]]");
}
outFile.delete();
return result;
} catch (Exception __e) { throw rethrow(__e); } }
static java.lang.Process backtickToFile(String cmd, File outFile) { try {
try {
java.lang.Process process = backtickToFile_noWait(cmd, outFile);
process.waitFor();
backtick_exitValue = process.exitValue();
if (backtick_verbose)
System.out.println("Process return code: " + backtick_exitValue);
return process;
} finally {
if (!backtick_keepScript)
deleteFile(backtick_scriptFile.get());
backtick_scriptFile.set(null);
}
} catch (Exception __e) { throw rethrow(__e); } }
static java.lang.Process backtickToFile_noWait(String cmd, File outFile) { try {
ping();
File scriptFile;
String ext = isWindows() ? ".bat" : "";
if (backtick_keepScript)
scriptFile = makeFileNameUnique_withExtension(javaxCachesDir("Cmd Scripts/backtick"), ".bat");
else
scriptFile = File.createTempFile("_backtick", ext);
backtick_scriptFile.set(scriptFile);
if (backtick_verbose)
print("backtick: scriptFile " + f2s(scriptFile));
cmd = trim(cmd);
if (numLines(cmd) > 1) throw fail("No multi-line commands allowed");
String command = cmd + " >" + bashQuote(outFile.getPath()) + " 2>&1";
if (!isTrue(backtick_uninterruptable.get()) && !isWindows()) command = fixNewLines("\r\ninterruptable() {\r\n\r\n # handle options\r\n local setsid=\"\"\r\n local debug=false\r\n while true; do\r\n case \"${1:-}\" in\r\n --killall) setsid=setsid; shift ;;\r\n --debug) debug=true; shift ;;\r\n --*) echo \"Invalid option: $1\" 1>&2; exit 1;;\r\n *) break;; # no more options\r\n esac\r\n done\r\n\r\n # start the specified command\r\n $setsid \"$@\" &\r\n local child_pid=$!\r\n\r\n # arrange to propagate a signal to the child process\r\n trap '\r\n exec 1>&2\r\n set +e\r\n trap \"\" SIGPIPE # ensure a possible sigpipe from the echo does not prevent the kill\r\n echo \"${BASH_SOURCE[0]} caught SIGTERM while executing $* (pid $child_pid), sending SIGTERM to it\"\r\n # (race) child may have exited in which case kill will report an error\r\n # if setsid is used then prefix the pid with a \"-\" to indicate that the signal\r\n # should be sent to the entire process group\r\n kill ${setsid:+-}$child_pid\r\n exit 143\r\n ' SIGTERM\r\n # ensure that the trap doesn't persist after we return\r\n trap 'trap - SIGTERM' RETURN\r\n\r\n $debug && echo \"interruptable wait (child $child_pid, self $$) for: $*\"\r\n\r\n # An error status from the child process will trigger an exception (via set -e)\r\n # here unless the caller is checking the return status\r\n wait $child_pid # last command, so status of waited for command is returned\r\n}\r\n\r\ninterruptable ") + command;
//Log.info("[Backtick] " + command);
if (backtick_verbose) {
print("backtick: command " + command);
print("backtick: saving to " + scriptFile.getPath());
}
saveTextFile(scriptFile.getPath(), command);
if (backtick_verbose)
print("backtick: command length=" + l(command) + ", file length=" + scriptFile.length());
String[] command2;
if (isWindows())
if (backtick_win_cmd)
command2 = new String[] { "cmd", "/c", scriptFile.getPath() };
else
command2 = new String[] { scriptFile.getPath() };
else
command2 = new String[] { "/bin/bash", scriptFile.getPath() };
if (backtick_verbose)
print("backtick: command2 " + structure(command2));
return Runtime.getRuntime().exec(command2);
} catch (Exception __e) { throw rethrow(__e); } }
/** possibly improvable */
static String bashQuote(String text) {
if (text == null) return null;
return "\"" + text
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r") + "\"";
}
static String bashQuote(File f) {
return bashQuote(f.getAbsolutePath());
}
static JWindow infoBox(String text) {
return infoMessage(text);
}
static JWindow infoBox(String text, double seconds) {
return infoMessage(text, seconds);
}
static JWindow infoBox(Throwable e) {
return infoMessage(e);
}
static String fileInfo(File f) {
return renderFileInfo(f);
}
static String fileInfo(String f) {
return renderFileInfo(newFile(f));
}
static boolean networkAllowanceTest(String url) {
return isAllowed("networkAllowanceTest", url);
}
static final boolean loadPageThroughProxy_enabled = false;
static String loadPageThroughProxy(String url) {
return null;
}
static String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
static void sleepSeconds(double s) {
if (s > 0) sleep(round(s*1000));
}
static A printWithTime(A a) {
return printWithTime("", a);
}
static A printWithTime(String s, A a) {
print(hmsWithColons() + ": " + s, a);
return a;
}
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }
static String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url))) return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=");
}
static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
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 Thread currentThread() {
return Thread.currentThread();
}
static InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
UnknownHostException lastException = null;
for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) {
try {
if (con instanceof HttpURLConnection)
if (((HttpURLConnection) con).getResponseCode() == 500)
throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con))));
return con.getInputStream();
} catch (UnknownHostException e) {
lastException = e;
print("Retrying because of: " + e);
continue;
}
}
throw lastException;
}
static 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(String url) { try {
return openConnection(new URL(url));
} catch (Exception __e) { throw rethrow(__e); } }
static URLConnection openConnection(URL url) { try {
ping();
callOpt(javax(), "recordOpenURLConnection", str(url));
return url.openConnection();
} 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));
if (o instanceof Boolean)
return boolToInt(((Boolean) 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 URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) {
con.setConnectTimeout(toInt(timeout));
con.setReadTimeout(toInt(timeout));
if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
print("Warning: Timeouts not set by JDK.");
return con;
}
static 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 ThreadLocal print_byThread() {
synchronized(print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
// f can return false to suppress regular printing
// call print_raw within f to actually print something
static AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
hideCredentials(str(innerException2(e)))) + "\n");
}
static boolean emptyString(String s) {
return s == null || s.length() == 0;
}
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 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 Class javax() {
return getJavaX();
}
static A second(List l) {
return get(l, 1);
}
static A second(Iterable l) {
if (l == null) return null;
Iterator it = iterator(l);
if (!it.hasNext()) return null;
it.next();
return it.hasNext() ? it.next() : null;
}
static A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static B second(Pair p) {
return p == null ? null : p.b;
}
static A second(Producer p) {
if (p == null) return null;
if (p.next() == null) return null;
return p.next();
}
static char second(String s) {
return charAt(s, 1);
}
static Producer javaTokC_iterator(String s) {
return new Producer() {
final int l = strL(s);
int i = 0;
public String next() {
if (i >= l) return null;
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
i = j;
if (i >= l) return null;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else 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;
String t = quickSubstring(s, i, j);
i = j;
return t;
}
};
}
// TODO: extended multi-line strings
static int javaTok_n, javaTok_elements;
static boolean javaTok_opt = false;
static List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !regionMatches(s, j, "*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
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) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') { // allow multi-line strings, but not for '
++j;
break;
} else if (c2 == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // 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 < l && !regionMatches(s, j, "]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !regionMatches(s, j, "]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static int jfind(String s, String in) {
return jfind(javaTok(s), in);
}
static int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, null);
}
static int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static int jfind(List tok, String in, ITokCondition condition) { return jfind(tok, 1, in, condition); }
static int jfind(List tok, int startIndex, String in, ITokCondition condition) {
return jfind(tok, startIndex, in, toTokCondition(condition));
}
static int jfind(List tok, int startIdx, String in, Object condition) {
//LS tokin = jfind_preprocess(javaTok(in));
return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
}
// assumes you preprocessed tokin
static int jfind(List tok, List tokin) {
return jfind(tok, 1, tokin);
}
static int jfind(List tok, int startIdx, List tokin) {
return jfind(tok, startIdx, tokin, null);
}
static int jfind(List tok, int startIdx, String[] tokinC, Object condition) {
return findCodeTokens(tok, startIdx, false, tokinC, condition);
}
static int jfind(List tok, int startIdx, List tokin, Object condition) {
return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
}
static List jfind_preprocess(List tok) {
for (String type : litlist("quoted", "id", "int"))
replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
return tok;
}
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 JProgressBar jProgressBarWithText() {
return swing(new F0() { public JProgressBar get() { try {
JProgressBar bar = new JProgressBar();
bar.setStringPainted(true);
return bar;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "new JProgressBar bar;\r\n bar.setStringPainted(true);\r\n ret bar;"; }});
}
static JProgressBar jProgressBarWithText(int maxValue) {
JProgressBar bar = jProgressBarWithText();
swingCall(bar, "setMaximum", maxValue);
return bar;
}
static Object swingCall(final Object o, final String method, final Object... args) {
return swing(new F0() { public Object get() { try { return call(o, method, args); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret call(o, method, args);"; }});
}
static A centerFrame(A c) {
Window w = getWindow(c);
if (w != null)
w.setLocationRelativeTo(null); // magic trick
return c;
}
static A centerFrame(int w, int h, A c) {
return centerFrame(setFrameSize(w, h, c));
}
static A packFrameVertically(A c) {
return packWindowVertically(c);
}
static A packFrameVertically(int width, A c) {
return packWindowVertically(setFrameWidth(width, c));
}
static JFrame showFrame() {
return makeFrame();
}
static JFrame showFrame(Object content) {
return makeFrame(content);
}
static JFrame showFrame(String title) {
return makeFrame(title);
}
static JFrame showFrame(String title, Object content) {
return makeFrame(title, content);
}
static JFrame showFrame(final JFrame f) {
if (f != null) { swing(new Runnable() { public void run() { try {
if (frameTooSmall(f)) frameStandardSize(f);
if (!f.isVisible()) f.setVisible(true); // XXX
if (f.getState() == Frame.ICONIFIED) f.setState(Frame.NORMAL);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (frameTooSmall(f)) frameStandardSize(f);\r\n if (!f.isVisible()) f.setVis..."; }}); }
return f;
}
// make or update frame
static JFrame showFrame(String title, Object content, JFrame frame) {
if (frame == null)
return showFrame(title, content);
else {
frame.setTitle(title);
setFrameContents(frame, content);
return frame;
}
}
static double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o instanceof String)
return parseDouble(((String) o));
if (o == null) return 0.0;
throw fail(o);
}
static void disposePossiblyInternalFrame(Component c) {
Container f = (Container) (getPossiblyInternalFrame(c));
if (f instanceof JInternalFrame) disposeInternalFrame((JInternalFrame) f);
else if (f instanceof Window) disposeWindow(f);
}
static A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static A optParam(ThreadLocal tl) {
return optPar(tl);
}
static Object optParam(String name, Map params) {
return mapGet(params, name);
}
// now also takes a map as single array entry
static A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt))) throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2)
if (eq(opt[i], name))
return (A) opt[i+1];
return defaultValue;
}
static Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
static Object optParam(String name, Object[] params) {
return optParam(params, name);
}
static HashSet asHashSet(Collection c) {
synchronized(collectionMutex(c)) {
return new HashSet(c);
}
}
static HashSet asHashSet(A[] a) {
return a == null ? null : new HashSet(Arrays.asList(a));
}
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 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 int[] unnull(int[] l) { return l == null ? emptyIntArray() : l; }
static char[] unnull(char[] l) { return l == null ? emptyCharArray() : l; }
static double[] unnull(double[] l) { return l == null ? emptyDoubleArray() : 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[]) emptyObjectArray() : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
//ifclass Symbol
static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static long unnull(Long l) { return l == null ? 0L : l; }
static Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(Iterable c) { return c == null || !c.iterator().hasNext(); }
static boolean empty(CharSequence s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
if (o instanceof byte[]) return empty((byte[]) o);
if (o == null) return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(Iterator i) { return i == null || !i.hasNext(); }
static boolean empty(double[] a) { return a == null || a.length == 0; }
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static boolean empty(byte[] a) { return a == null || a.length == 0; }
static boolean empty(short[] a) { return a == null || a.length == 0; }
static boolean empty(MultiMap mm) { return mm == null || mm.isEmpty(); }
static boolean empty(File f) { return getFileSize(f) == 0; }
static Object first(Object list) {
return first((Iterable) list);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(IterableIterator i) {
return first((Iterator ) i);
}
static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static Character first(CharSequence s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static void removeFirst(List l) {
if (nempty(l))
l.remove(0);
}
static void removeFirst(int n, List l) {
removeSubList(l, 0, n);
}
static void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null) map.put(key, value);
}
static void mapPut(Map map, Pair p) {
if (map != null && p != null) map.put(p.a, p.b);
}
static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array)
if (o != null)
set.add(o);
return set;
}
static Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array)
if (o != null)
set.add(o);
return set;
}
static Set asSet(Iterable l) {
if (l instanceof Set) return (Set) l;
HashSet set = new HashSet();
for (A o : unnull(l))
if (o != null)
set.add(o);
return set;
}
static Collection similarEmptyCollection(Collection c) {
if (c instanceof List) return similarEmptyList(((List) c));
if (c instanceof Set) return similarEmptySet(((Set) c));
return new ArrayList();
}
static boolean isImageSnippetID(long id) {
return isImageServerSnippet(id);
}
static boolean isImageSnippetID(String id) {
return isImageSnippetID(parseSnippetIDOpt(id));
}
static Set collectSnippetIDsInJavaSource(String s) {
Set set = new HashSet();
for (String t : quotedOnly(javaTokC(s)))
addAll(set, collectSnippetIDsInText(t));
return set;
}
static String dropFirstLine(String text) {
if (text == null) return null;
int i = text.indexOf('\n');
return i >= 0 ? text.substring(i+1) : "";
}
static List regexpAll(String pattern, String text) {
List matches = new ArrayList();
Matcher matcher = regexp(pattern, text);
while (matcher.find())
matches.add(matcher.group());
return matches;
}
static String firstLine(String text) {
if (text == null) return null;
int i = text.indexOf('\n');
return i >= 0 ? text.substring(0, i) : text;
}
static void addAll(Collection c, Iterable b) {
if (c != null && b != null) for (A a : b) c.add(a);
}
static boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static boolean addAll(Collection c, B... b) {
return c != null && b != null && c.addAll(Arrays.asList(b));
}
static Map addAll(Map a, Map extends A,? extends B> b) {
if (a != null) a.putAll(b);
return a;
}
static Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
return null;
}
static Object call_withVarargs(Object o, String method, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
{ if (!(isStaticMethod(m))) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) { throw rethrow(__e); } }
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 int shorten_default = 100;
static String shorten(CharSequence s) { return shorten(s, shorten_default); }
static String shorten(CharSequence s, int max) {
return shorten(s, max, "...");
}
static String shorten(CharSequence s, int max, String shortener) {
if (s == null) return "";
if (max < 0) return str(s);
return s.length() <= max ? str(s) : subCharSequence(s, 0, min(s.length(), max-l(shortener))) + shortener;
}
static String shorten(int max, CharSequence s) { return shorten(s, max); }
static String programID() {
return getProgramID();
}
static String programID(Object o) {
return getProgramID(o);
}
// r may return false to cancel timer
static TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) {
return new SmartTimerTask(r, timer, delay, _threadInfo());
}
static class SmartTimerTask extends TimerTask implements IFieldsToList{
Object r;
java.util.Timer timer;
long delay;
Object threadInfo;
SmartTimerTask() {}
SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) {
this.threadInfo = threadInfo;
this.delay = delay;
this.timer = timer;
this.r = r;}
public String toString() { return shortClassName(this) + "(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")"; }public Object[] _fieldsToList() { return new Object[] {r, timer, delay, threadInfo}; }
long lastRun;
public void run() {
if (!licensed())
timer.cancel();
else {
_threadInheritInfo(threadInfo);
AutoCloseable __1 = tempActivity(r); try {
lastRun = fixTimestamp(lastRun);
long now = now();
if (now >= lastRun + delay*0.9) {
lastRun = now;
if (eq(false, pcallF(r)))
timer.cancel();
}
} finally { _close(__1); }}
}
}
static A vmBus_timerStarted(A timer) {
vmBus_send("timerStarted",timer, costCenter());
return timer;
}
static long toMS(double seconds) {
return (long) (seconds*1000);
}
static Charset utf8charset_cache;
static Charset utf8charset() { if (utf8charset_cache == null) utf8charset_cache = utf8charset_load(); return utf8charset_cache; }
static Charset utf8charset_load() {
return Charset.forName("UTF-8");
}
static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static String substring(String s, int x) {
return substring(s, x, strL(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
int n = s.length();
if (y < x) y = x;
if (y > n) y = n;
if (x >= y) return "";
return s.substring(x, y);
}
// convenience method for quickly dropping a prefix
static String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static int strL(String s) {
return s == null ? 0 : s.length();
}
static int listL(Collection l) {
return l == null ? 0 : l.size();
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
// usually L
static String fromLines(Iterable 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));
}
// unclear semantics as to whether return null on null
static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static ArrayList asList(int[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(long[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static ArrayList asList(float[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static ArrayList asList(double[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static ArrayList asList(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null) while ((a = p.next()) != null)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
static 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) {
int n = s.length();
for (int i = start; i < n; i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1) return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
public static List parseSnippetIDs(Collection snippetIDs) {
List l = new ArrayList();
for (String id : snippetIDs)
l.add(str(parseSnippetID(id)));
return l;
}
static Map trimValues(Map map) {
Map map2 = similarEmptyMap(map);
for (A key : keys(map))
map2.put(key, trim(map.get(key)));
return map2;
}
static Map transformKeys(Map map, Object f) {
HashMap m = new HashMap();
for (Object key : keys(map))
m.put(callF(f, key), map.get(key));
return m;
}
static Map jsonDecodeMap(String s) {
Object o = jsonDecode(s);
if (o instanceof List && empty((List) o))
return new HashMap();
if (o instanceof Map)
return (Map) o;
else
throw fail("Not a JSON map: " + s);
}
static ThreadLocal doPost_silently = new ThreadLocal();
static ThreadLocal doPost_timeout = new ThreadLocal();
static ThreadLocal> doPost_extraHeaders = new ThreadLocal();
static String doPost(Map urlParameters, String url) {
return doPost(makePostData(urlParameters), url);
}
static String doPost(String urlParameters, String url) { try {
URL _url = new URL(url);
ping();
return doPost(urlParameters, _url.openConnection(), _url);
} catch (Exception __e) { throw rethrow(__e); } }
static String doPost(String urlParameters, URLConnection conn, URL url) { try {
boolean silently = isTrue(optParam(doPost_silently));
Long timeout = optParam(doPost_timeout);
Map extraHeaders = optPar(doPost_extraHeaders);
setHeaders(conn);
for (String key : keys(extraHeaders)) {
conn.setRequestProperty(key, extraHeaders.get(key));
}
int l = lUtf8(urlParameters);
if (!silently)
print("Sending POST request: " + hideCredentials(url) + " (" + l + " bytes)");
// connect and do POST
if (timeout != null) setURLConnectionTimeouts(conn, timeout);
((HttpURLConnection) conn).setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", str(l));
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
writer.write(urlParameters);
writer.flush();
String contents = loadPage_utf8(conn, url, false);
writer.close();
return contents;
} catch (Exception __e) { throw rethrow(__e); } }
static Map mapPlus(Map m, Object... data) {
m = cloneMap(m);
litmap_impl(m, data);
return m;
}
static Map standardCredentialsMap() {
String user = standardCredentialsUser();
String pass = standardCredentialsPass();
if (nempty(user) && nempty(pass))
return litmap("_user" , user, "_pass" , pass);
return litmap();
}
static String indentStructureString(String s) {
if (s == null) return null;
List tok = javaTokForStructure(s);
StringBuilder buf = new StringBuilder();
int indent = 0;
for (int i = 0; i < l(tok); i++) {
String t = tok.get(i);
if (isOpeningBracket(t)) {
int j = i+5;
if (containsClosingBracket(subList(tok, i+2, i+5))) {
buf.append(joinSubList(tok, i, j));
i = j-1;
} else
buf.append(t).append("\n").append(spaces(indent += 2));
} else if (isClosingBracket(t))
buf.append("\n").append(spaces(indent -= 2)).append(t);
else if (eq(t, ",")) {
buf.append(t).append("\n").append(spaces(indent));
i++;
} else
buf.append(t);
}
return str(buf);
}
static String struct(Object o) {
return structure(o);
}
static String struct(Object o, structure_Data data) {
return structure(o, data);
}
static A proxy(Class intrface, final Object target) {
if (target == null) return null;
if (isInstance(intrface, target)) return (A) target;
return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(),
new Class[] { intrface },
new proxy_InvocationHandler(target));
}
static A proxy(Object target, Class intrface) {
return proxy(intrface, target);
}
static Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static int parseIntOpt(String s) {
return isInteger(s) ? parseInt(s) : 0;
}
static String getFileInfoField(File f, String field) {
return getOneLineFileInfoField(f, field);
}
static File localSnippetFile(long snippetID) {
return localSnippetsDir(snippetID + ".text");
}
static File localSnippetFile(String snippetID) {
return localSnippetFile(parseSnippetID(snippetID));
}
static String standardCredentialsUser() {
return trim(loadTextFile(
oneOfTheFiles(
javaxSecretDir("tinybrain-username"),
userDir(".tinybrain/username"))));
}
static String standardCredentialsPass() {
return trim(loadTextFile(
oneOfTheFiles(
javaxSecretDir("tinybrain-userpass"),
userDir(".tinybrain/userpass"))));
}
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static File loadImageAsFile(String snippetIDOrURL) { try {
if (isURL(snippetIDOrURL))
throw fail("not implemented");
if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
String snippetID = "" + parseSnippetID(snippetIDOrURL);
File file = imageSnippetCacheFile(snippetID);
if (fileSize(file) > 0) return file;
String imageURL = snippetImageURL_noHttps(snippetID);
System.err.println("Loading image: " + imageURL);
byte[] data = loadBinaryPage(imageURL);
saveBinaryFile(file, data);
return file;
} catch (Exception __e) { throw rethrow(__e); } }
// 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(tb_mainServer() + "/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 File loadDataSnippetToFile(String snippetID) { try {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
return loadDataSnippetToFile_noResourceLoader(snippetID);
} catch (Exception __e) { throw rethrow(__e); } }
static File loadDataSnippetToFile_noResourceLoader(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(tb_mainServer() + "/blobs/" + psI(snippetID)));
print(e);
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 Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
// TODO: test if android complains about this
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isAWTThread_awt();
}
static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static String fileName(File f) {
return f == null ? null : f.getName();
}
static boolean isImageFileName(String s) {
return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif");
}
static boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x)) return true; return false;
}
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 void file2stream(File src, OutputStream out) throws IOException {
FileInputStream inputStream = new FileInputStream(src);
try {
copyStream(inputStream, out);
} finally {
inputStream.close();
}
}
static String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
static 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); } }
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len*2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs+i]);
stringBuilder.append(s.substring(s.length()-2, s.length()));
}
return stringBuilder.toString();
}
static boolean md5OfFile_verbose = false;
static String md5OfFile(String path) {
return md5OfFile(newFile(path));
}
static String md5OfFile(File f) { try {
if (!f.exists()) return "-";
if (md5OfFile_verbose)
print("Getting MD5 of " + f);
MessageDigest md5 = MessageDigest.getInstance("MD5");
FileInputStream in = new FileInputStream(f); try {
byte buf[] = new byte[65536];
int l;
while (true) {
l = in.read(buf);
if (l <= 0) break;
md5.update(buf, 0, l);
}
return bytesToHex(md5.digest());
} finally { _close(in); }} catch (Exception __e) { throw rethrow(__e); } }
static ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal();
static void checkFileNotTooBigToRead(File f) {
callF(checkFileNotTooBigToRead_tl.get(), f);
}
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);
}
}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static File 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();
}
return dest;
} catch (Exception __e) { throw rethrow(__e); } }
static A printStackTrace(A e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
return e;
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
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 int snippetType_javaxSource() {
return 34;
}
static int snippetType_JavaXDesktop() {
return 55;
}
static int snippetType_javaxModule() {
return 54;
}
static int snippetType_javaxDesktopModule() {
return 58;
}
static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static String loadTextFilePossiblyGZipped(String fileName) {
return loadTextFilePossiblyGZipped(fileName, null);
}
static String loadTextFilePossiblyGZipped(String fileName, String defaultContents) {
File gz = new File(fileName + ".gz");
return gz.exists() ? loadGZTextFile(gz) : loadTextFile(fileName, defaultContents);
}
static String loadTextFilePossiblyGZipped(File fileName) {
return loadTextFilePossiblyGZipped(fileName, null);
}
static String loadTextFilePossiblyGZipped(File fileName, String defaultContents) {
return loadTextFilePossiblyGZipped(fileName.getPath(), defaultContents);
}
static File getCachedTranspilationFile(String id) {
return newFile(getCodeProgramDir(id), "Transpilation");
}
static Object vmGeneralMap_get(Object key) {
return vm_generalMap_get(key);
}
static String loadProgramTextFile(String name) {
return loadTextFile(getProgramFile(name));
}
static String loadProgramTextFile(String progID, String name) {
return loadTextFile(getProgramFile(progID, name));
}
static String loadProgramTextFile(String progID, String name, String defaultText) {
return loadTextFile(getProgramFile(progID, name), defaultText);
}
static String loadPage_utf8(URL url) {
return loadPage_utf8(url.toString());
}
static String loadPage_utf8(String url) {
AutoCloseable __1 = tempSetTL(loadPage_charset, "UTF-8"); try {
return loadPage(url);
} finally { _close(__1); }}
static String loadPage_utf8(URLConnection con, URL url, boolean addHeaders) throws IOException {
AutoCloseable __2 = tempSetTL(loadPage_charset, "UTF-8"); try {
return loadPage(con, url, addHeaders);
} finally { _close(__2); }}
static void saveTranspiledCode(String progID, String code) {
File dir = getCodeProgramDir(progID);
new File(dir, "Transpilation").delete();
saveGZTextFile(new File(dir, "Transpilation.gz"), code);
}
static Map vm_threadInterruptionReasonsMap() {
return vm_generalWeakSubMap("Thread interruption reasons");
}
static String strOr(Object o, String ifNull) {
return o == null ? ifNull : str(o);
}
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 ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static List hotwire_libraryIDsFromJar_deleteJarOnFail(File jar) {
try {
return hotwire_libraryIDsFromJar(jar);
} catch (Throwable _e) {
jar.delete();
throw rethrow(_e); }
}
static boolean loadLibraryOrSrcLib_srcLibsEnabled = true;
// to avoid checking src libs too often when booting OS
static ThreadLocal> loadLibraryOrSrcLib_tempCache = new ThreadLocal();
static File loadLibraryOrSrcLib(String snippetID) { try {
vmBus_send("loadLibraryOrSrcLib",snippetID);
long id = parseSnippetID(snippetID);
if (loadLibraryOrSrcLib_tempCache.get() != null)
{ File f = loadLibraryOrSrcLib_tempCache.get().get(id); if (f != null) return f; }
boolean srcLib = loadLibraryOrSrcLib_srcLibsEnabled && isMarkedAsSrcLib(snippetID);
if (srcLib) {
File f = pairA(hotwire_compile(snippetID));
mapPut(loadLibraryOrSrcLib_tempCache.get(), id, f);
return f;
}
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) != 0) return f;
try {
return loadDataSnippetToFile(snippetID);
} catch (Throwable e) {
if (loadLibraryOrSrcLib_srcLibsEnabled && nempty(loadSnippet(snippetID))) {
markAsSrcLib(snippetID);
return pairA(hotwire_compile(snippetID));
}
throw rethrow(e);
}
} catch (Exception __e) { throw rethrow(__e); } }
static Set hotwire_classesToShare = synchroSet();
static Set hotwire_classesToShare() {
return hotwire_classesToShare;
}
static ClassLoader myClassLoader() {
return _getClass(mc()).getClassLoader();
}
static Class __javax;
static Class getJavaX() { try {
return __javax;
} catch (Exception __e) { throw rethrow(__e); } }
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); return; } // possible improvement: skip setAccessible
if (o instanceof DynamicObject)
setDyn(((DynamicObject) o), field, value);
} 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); // TODO: optimize
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) {
makeAccessible(f);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Object callOpt(Object o) {
return callF(o);
}
static A callOpt(Object o, String method, Object... args) {
return (A) callOpt_withVarargs(o, method, args);
}
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 Pair pair(A a, B b) {
return new Pair(a, b);
}
static Pair pair(A a) {
return new Pair(a, a);
}
static byte[] isJAR_magic = bytesFromHex("504B0304");
static boolean isJAR(byte[] data) {
return byteArrayStartsWith(data, isJAR_magic);
}
static boolean isJAR(File f) {
return isJAR(loadBeginningOfBinaryFile(f, l(isJAR_magic)));
}
static byte[] takeFirstOfByteArray(byte[] b, int n) {
return subByteArray(b, 0, n);
}
static byte[] takeFirstOfByteArray(int n, byte[] b) {
return takeFirstOfByteArray(b, n);
}
static String fromUtf8(byte[] bytes) { try {
return bytes == null ? null : new String(bytes, utf8charset());
} catch (Exception __e) { throw rethrow(__e); } }
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt(String field, Object o) {
return getOpt_cached(o, field);
}
static Object getOpt_raw(Object o, String field) { try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
// access of static fields is not yet optimized
static Object getOpt(Class c, String field) { try {
if (c == null) return null;
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
makeAccessible(f);
return f.get(null);
} catch (Exception __e) { throw rethrow(__e); } }
static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
// 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 int indexOf(List l, A a, int startIndex) {
if (l == null) return -1;
int n = l(l);
for (int i = startIndex; i < n; i++)
if (eq(l.get(i), a))
return i;
return -1;
}
static int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
static int indexOf(List l, A a) {
if (l == null) return -1;
return l.indexOf(a);
}
static int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(A[] x, A a) {
int n = l(x);
for (int i = 0; i < n; i++)
if (eq(x[i], a))
return i;
return -1;
}
static void rotateStringBuffer(StringBuffer buf, int max) { try {
if (buf == null) return;
synchronized(buf) {
if (buf.length() <= max) return;
try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) { throw rethrow(__e); } }
static void rotateStringBuilder(StringBuilder buf, int max) { try {
if (buf == null) return;
synchronized(buf) {
if (buf.length() <= max) return;
try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) { throw rethrow(__e); } }
static Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null
: l(args) == 1 ? args[0]
: args;
}
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 Set vm_busListeners_live_cache;
static Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache; }
static Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static Map vm_busListenersByMessage_live_cache;
static Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache; }
static Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
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(List l) {
return l;
}
static Object collectionMutex(Object o) {
if (o instanceof List) return 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 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();
}
static ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
// get correct type at once
static ArrayList emptyList(Class c) {
return new ArrayList();
}
static Map similarEmptyMap(Map m) {
if (m instanceof TreeMap) return new TreeMap(((TreeMap) m).comparator());
if (m instanceof LinkedHashMap) return new LinkedHashMap();
// default to a hash map
return new HashMap();
}
static Map similarEmptyMap(Iterable m) {
if (m instanceof TreeSet) return new TreeMap(((TreeSet) m).comparator());
if (m instanceof LinkedHashSet) return new LinkedHashMap();
return new HashMap();
}
static Pattern regexpCompile(String pat) {
return compileRegexp(pat);
}
static List regexpGetGroups(Matcher matcher) {
int n = matcher.groupCount();
List l = new ArrayList();
for (int i = 1; i <= n; i++)
l.add(matcher.group(i));
return l;
}
// performs find()
static List regexpGetGroups(String pat, String s) {
Matcher m = regexpMatcher(pat, s);
if (m.find())
return regexpGetGroups(m);
return null;
}
static String actualUserHome_value;
static String actualUserHome() {
if (actualUserHome_value == null) {
if (isAndroid())
actualUserHome_value = "/storage/emulated/0/";
else
actualUserHome_value = System.getProperty("user.home");
}
return actualUserHome_value;
}
static File actualUserHome(String sub) {
return newFile(new File(actualUserHome()), sub);
}
static File userDir() {
return new File(userHome());
}
static File userDir(String path) {
return new File(userHome(), path);
}
static A println(A a) {
return print(a);
}
static List _registerDangerousWeakMap_preList;
static A _registerDangerousWeakMap(A map) {
return _registerDangerousWeakMap(map, null);
}
static A _registerDangerousWeakMap(A map, Object init) {
callF(init, map);
if (init instanceof String) {
final String f = (String) init;
init = new VF1() { public void get(Map map) { try { callMC(f, map) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callMC(f, map)"; }};
}
if (javax() == null) {
// We're in class init
if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList();
_registerDangerousWeakMap_preList.add(pair(map, init));
return map;
}
call(javax(), "_registerDangerousWeakMap", map, init);
return map;
}
static void _onLoad_registerDangerousWeakMap() {
assertNotNull(javax());
if (_registerDangerousWeakMap_preList == null) return;
for (Pair p : _registerDangerousWeakMap_preList)
_registerDangerousWeakMap(p.a, p.b);
_registerDangerousWeakMap_preList = null;
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static String joinWithSpace(Iterable c) {
return join(" ", c);
}
static String joinWithSpace(String... c) {
return join(" ", c);
}
static List classNames(Collection l) {
return getClassNames(l);
}
static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class) return arg instanceof Boolean;
if (type == int.class) return arg instanceof Integer;
if (type == long.class) return arg instanceof Long;
if (type == float.class) return arg instanceof Float;
if (type == short.class) return arg instanceof Short;
if (type == char.class) return arg instanceof Character;
if (type == byte.class) return arg instanceof Byte;
if (type == double.class) return arg instanceof Double;
return type.isInstance(arg);
}
static boolean addToCollection(Collection c, A a) {
return c != null && c.add(a);
}
static boolean deleteFile(File file) {
return file != null && file.delete();
}
static File makeFileNameUnique_withExtension(File f, String ext) {
File orig = f;
int n = 0;
ext = addPrefixIfNempty(".", dropPrefix(".", ext));
String name = dropSuffixIC(ext, orig.getName());
f = new File(dirOfFile(orig), name + ext);
while (f.exists())
f = new File(dirOfFile(orig), name + "." + (++n) + ext);
return f;
}
static int numLines(String s) {
return countLines(s);
}
static boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
return structure(o, new structure_Data());
}
static String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack))
popLast(d.stack).run();
}
static void structureToPrintWriter(Object o, PrintWriter out) { structureToPrintWriter(o, out, new structure_Data()); }
static void structureToPrintWriter(Object o, PrintWriter out, structure_Data d) {
d.out = out;
structure_go(o, d);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
// info on how to serialize objects of a certain class
static class structure_ClassInfo {
Class c;
List fields;
Method customSerializer;
IVF1 serializeObject; // can be set by caller of structure function
boolean special, nullInstances;
}
static class structure_Data {
PrintWriter out;
int stringSizeLimit;
int shareStringsLongerThan = 20;
boolean noStringSharing = false;
boolean storeBaseClasses = false;
IdentityHashMap seen = new IdentityHashMap();
//new BitSet refd;
HashMap strings = new HashMap();
HashSet concepts = new HashSet();
HashMap infoByClass = new HashMap();
HashMap persistenceInfo = new HashMap();
int n; // token count
List stack = new ArrayList();
// append single token
structure_Data append(String token) { out.print(token); ++n; return this; }
structure_Data append(int i) { out.print(i); ++n; return this; }
// append multiple tokens
structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; }
// extend last token
structure_Data app(String token) { out.print(token); return this; }
structure_Data app(int i) { out.print(i); return this; }
// called when a new class is detected
// can be overridden by clients
structure_ClassInfo newClass(Class c) {
structure_ClassInfo info = new structure_ClassInfo();
info.c = c;
infoByClass.put(c, info);
if ((info.customSerializer = findMethodNamed(c, "_serialize"))
!= null) info.special = true;
if (storeBaseClasses) {
Class sup = c.getSuperclass();
if (sup != Object.class) {
append("bc ");
append(shortClassName(c));
out.print(" ");
append(shortClassName(sup));
out.print(" ");
}
}
return info;
}
void setFields(structure_ClassInfo info, List fields) {
info.fields = fields;
}
}
static void structure_1(final Object o, final structure_Data d) { try {
if (o == null) { d.append("null"); return; }
Class c = o.getClass();
boolean concept = false;
structure_ClassInfo info = d.infoByClass.get(c);
if (info == null)
info = d.newClass(c);
List lFields = info.fields;
if (lFields == null) {
// these are never back-referenced (for readability)
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; }
if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; }
if (o instanceof Short) { short s = ((Short) o).shortValue(); d.append("sh "); out.print(s); d.n += s < 0 ? 2 : 1; return; }
if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; }
if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; }
if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; }
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f"); return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o)); return;
}
if (o instanceof File) {
d.append("File ").append(quote(((File) o).getPath())); return;
}
// referencable objects follow
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null) ref = d.strings.get((String) o);
if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
if (!(o instanceof String))
d.seen.put(o, d.n); // record token number
else {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out); d.n++; return;
}
if (o instanceof Set) {
/*O set2 = unwrapSynchronizedSet(o);
if (set2 != o) {
d.append("sync");
o = set2;
} TODO */
if (((Set) o) instanceof TreeSet) {
d.append(isCISet_gen(((Set) o)) ? "ciset" : "treeset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
// assume it's a HashSet or LinkedHashSet
d.append(((Set) o) instanceof LinkedHashSet ? "lhs" : "hashset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
String name = c.getName();
if (o instanceof Collection
&& !isJavaXClassName(name)
/* && neq(name, "main$Concept$RefL") */) {
// it's a list
if (name.equals("java.util.Collections$SynchronizedList")
|| name.equals("java.util.Collections$SynchronizedRandomAccessList")) {
d.append("sync ");
{ structure_1(unwrapSynchronizedList(((List) o)), d); return; }
}
else if (name.equals("java.util.LinkedList")) d.append("ll");
d.append("[");
final int l = d.n;
final Iterator it = ((Collection) o).iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.sta..."; }});
return;
}
if (o instanceof Map && !startsWith(name, "main$")) {
if (o instanceof LinkedHashMap) d.append("lhm");
else if (o instanceof HashMap) d.append("hm");
else if (o instanceof TreeMap)
d.append(isCIMap_gen(((TreeMap) o)) ? "cimap" : "tm");
else if (name.equals("java.util.Collections$SynchronizedMap")
|| name.equals("java.util.Collections$SynchronizedSortedMap")
|| name.equals("java.util.Collections$SynchronizedNavigableMap")) {
d.append("sync ");
{ structure_1(unwrapSynchronizedMap(((Map) o)), d); return; }
}
d.append("{");
final int l = d.n;
final Iterator it = ((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
boolean v = false;
Map.Entry e;
public void run() {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(e.getKey(), d);
}
}
}
});
return;
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o))); return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return;
}
String atype = "array"/*, sep = ", "*/; // sep is not used yet
if (o instanceof int[]) {
//ret "intarray " + quote(intArrayToHex((int[]) o));
atype = "intarray";
//sep = " ";
} else if (o instanceof double[]) {
atype = "dblarray";
//sep = " ";
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0) d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
if (d.n != l) d.append(", ");
d.append(i);
}
d.append("}"); return;
}
// Need more cases? This should cover all library classes...
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o))); return; // Hm. this is not unstructure-able
}
/*if (name.equals("main$Lisp")) {
fail("lisp not supported right now");
}*/
if (info.special) {
if (info.customSerializer != null) {
// custom serialization (_serialize method)
Object o2 = invokeMethod(info.customSerializer, o);
d.append("cu ");
String shortName = dropPrefix("main$", name);
d.append(shortName);
d.out.append(' ');
structure_1(o2, d);
return;
} else if (info.nullInstances) { d.append("null"); return; }
else if (info.serializeObject != null)
{ info.serializeObject.get(o); return; }
else throw fail("unknown special type");
}
String dynName = shortDynamicClassName(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
// serialize an object with fields.
// first, collect all fields and values in fv.
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
String fieldName = field.getName();
if (fieldName.equals("_persistenceInfo"))
d.persistenceInfo.put(c, field);
if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
continue;
fields.add(field);
// put special cases here...?
}
cc = cc.getSuperclass();
}
// TODO: S fieldOrder = getOpt(c, "_fieldOrder");
lFields = asList(fields);
// Render this$1 first because unstructure needs it for constructor call.
int n = l(lFields);
for (int i = 0; i < n; i++) {
Field f = lFields.get(i);
if (f.getName().equals("this$1")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
d.setFields(info, lFields);
} // << if (lFields == null)
else { // ref handling for lFields != null
Integer ref = d.seen.get(o);
if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
d.seen.put(o, d.n); // record token number
}
Field persistenceInfoField = (Field) (d.persistenceInfo.get(c));
Map persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o);
LinkedHashMap fv = new LinkedHashMap();
for (Field f : lFields) {
Object value;
try {
value = f.get(o);
} catch (Exception e) {
value = "?";
}
if (value != null && (persistenceInfo == null
|| !Boolean.FALSE.equals(persistenceInfo.get(f.getName()))))
fv.put(f.getName(), value);
}
String name = c.getName();
String shortName = dropPrefix("main$", name); // TODO: drop loadableUtils also
if (startsWithDigit(shortName)) shortName = name; // for anonymous classes
// Now we have fields & values. Process fieldValues if it's a DynamicObject.
// omit field "className" if equal to class's name
if (concept && eq(fv.get("className"), shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
putAll(fv, (Map) fv.get("fieldValues"));
fv.remove("fieldValues");
shortName = shortDynamicClassName(o);
fv.remove("className");
}
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
d.append(shortName);
d.n += countDots(shortName)*2; // correct token count
final int l = d.n;
final Iterator it = fv.entrySet().iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext()) {
if (d.n != l)
d.append(")");
} else {
Map.Entry e = (Map.Entry) it.next();
d.append(d.n == l ? "(" : ", ");
d.append((String) e.getKey()).append("=");
d.stack.add(this);
structure_1(e.getValue(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else..."; }});
} catch (Exception __e) { throw rethrow(__e); } }
static boolean infoMessage_alwaysOnTop = true;
static double infoMessage_defaultTime = 5.0;
// automatically switches to AWT thread for you
static JWindow infoMessage(String text) {
return infoMessage(text, infoMessage_defaultTime);
}
static JWindow infoMessage(final String text, final double seconds) {
printHidingCredentials(text);
return infoMessage_noprint(text, seconds);
}
static JWindow infoMessage_noprint(String text) {
return infoMessage_noprint(text, infoMessage_defaultTime);
}
static JWindow infoMessage_noprint(final String _text, final double seconds) {
final String text = hideCredentials(_text);
if (empty(text)) return null;
logQuotedWithDate(infoBoxesLogFile(), text);
if (isHeadless()) return null;
return (JWindow) swingAndWait(new F0() { public Object get() { try {
final JWindow window = showWindow(infoMessage_makePanel(text));
window.setSize(300, 150);
moveToTopRightCorner(window);
if (infoMessage_alwaysOnTop)
window.setAlwaysOnTop(true);
if (vmBus_noObjections("shouldShowInfoBox",window, text))
window.setVisible(true);
if (seconds != 0)
disposeWindowAfter(iround(seconds*1000), window);
return window;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final JWindow window = showWindow(infoMessage_makePanel(text));\r\n window.s..."; }});
}
static JWindow infoMessage(Throwable e) {
//showConsole();
printStackTrace(e);
return infoMessage(exceptionToStringShort(e));
}
static String renderFileInfo(File f) {
return f == null ? "-" : f2s(f) + " "
+ (f.isFile() ? "(file, " + n2(fileSize(f)) + " bytes)"
: f.isDirectory() ? "(dir)" : "(not found)");
}
static boolean loadBufferedImage_useImageCache = true;
static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try {
ping();
if (snippetIDOrURLOrFile == null) return null;
if (isURL(snippetIDOrURLOrFile))
return imageIO_readURL(snippetIDOrURLOrFile);
if (isAbsolutePath(snippetIDOrURLOrFile))
return loadBufferedImage(new File(snippetIDOrURLOrFile));
if (!isSnippetID(snippetIDOrURLOrFile))
throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile);
String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return loadBufferedImage(rl.loadLibrary(snippetID));
File dir = imageSnippetsCacheDir();
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
try {
return ImageIO.read(file);
} catch (Throwable e) {
e.printStackTrace();
// fall back to loading from sourceforge
}
}
String imageURL = snippetImageURL_http(snippetID);
print("Loading image: " + imageURL);
BufferedImage image = imageIO_readURL(imageURL);
if (loadBufferedImage_useImageCache) {
File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
ImageIO.write(image, "png", tempFile);
tempFile.renameTo(new File(dir, snippetID + ".png"));
//Log.info("Cached image.");
}
//Log.info("Loaded image.");
return image;
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage loadBufferedImage(File file) { try {
return file.isFile() ? ImageIO.read(file) : null;
} catch (Exception __e) { throw rethrow(__e); } }
//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