Warning : session_start(): open(/var/lib/php/sessions/sess_ej24qg2grt43i8d6nvjqo3p942, 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 x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.fail;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.sendToLocalBotOpt;
import static loadableUtils.utils.sendToLocalBotQuietly;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.tablePopupMenuFirst;
import static loadableUtils.utils.rowSorter_setComparators;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import static loadableUtils.utils.rethrow;
import static loadableUtils.utils.hasBot;
import static loadableUtils.utils.concepts_internStringsLongerThan;
import static loadableUtils.utils.concepts_setUnlistedByDefault;
import static loadableUtils.utils.realMC_tl;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.IVF2;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.structure_ClassInfo;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.RC;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IConceptCounter;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import loadableUtils.utils.GlobalID;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import loadableUtils.utils.SynchronizedArrayList;
import loadableUtils.utils.SecretValue;
import loadableUtils.utils.HCRUD;
import loadableUtils.utils.HCRUD_Data;
import loadableUtils.utils.HCRUD_Concepts;
import loadableUtils.utils.ValueConverterForField;
import loadableUtils.utils.DefaultValueConverterForField;
import loadableUtils.utils.OrError;
import loadableUtils.utils.HTML;
class main {
static public class CleanJavaXCache extends DynPrintLogAndEnabled {
static public boolean _switchableField_retentionHours = true;
public int retentionHours = 48;
static public boolean _switchableField_verbose = true;
public boolean verbose = true;
public void start() {
try {
super.start();
doEvery(dm_osStarting() ? 3600.0 : 10.0, 3600.0, new Runnable() {
public void run() {
try {
doIt();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "doIt();";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void doIt() {
AutoCloseable __10 = enter();
try {
if (!enabled)
return;
cleanJavaXCache(retentionHours, verbose);
} finally {
_close(__10);
}
}
}
static public boolean _moduleClass_CleanJavaXCache = true;
static public String programID;
static public void _onLoad_initUtils() {
utils.__javax = javax();
}
static public void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (name.startsWith("main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
return null;
}
});
}
static public ThreadLocal dynamicObjectIsLoading_threadLocal() {
return DynamicObject_loading;
}
static volatile public Concepts mainConcepts;
static public Concepts db_mainConcepts() {
if (mainConcepts == null)
mainConcepts = newConceptsWithClassFinder(getDBProgramID());
return mainConcepts;
}
static public void cleanMeUp_concepts() {
if (db_mainConcepts() != null)
db_mainConcepts().cleanMeUp();
}
static public FixedRateTimer doEvery(long delay, final Object r) {
return doEvery(delay, delay, r);
}
static public FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
return vmBus_timerStarted(timer);
}
static public FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
}
static public FixedRateTimer doEvery(double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), r);
}
static public boolean dm_osStarting() {
return dm_osLoading();
}
static public int cleanJavaXCache_msgInterval = 5000;
static public boolean cleanJavaXCache_verbose = false;
static public int cleanJavaXCache_emptyDirs_retentionMinutes = 10;
static public void cleanJavaXCache(int retentionHours, boolean verbose) {
try {
retentionHours = max(1, retentionHours);
long now = now(), msgPrinted = now();
if (verbose)
System.out.println("Cleaning JavaX Cache (" + retentionHours + " hours retention time; cutoff time: " + (now - retentionHours * 1000 * 60 * 60) + ")");
int fileDeletions = 0;
for (File javax : ll(new File(userHome(), ".javax"), javaxTempDir())) {
File[] files = javax.listFiles();
int scanned = 0, deleted = 0;
if (files != null)
for (File dir : files) {
++scanned;
if (now() >= msgPrinted + cleanJavaXCache_msgInterval) {
print("Cleaning cache (" + scanned + "/" + n(files, "dir") + " scanned, " + deleted + " deleted)...");
msgPrinted = now();
}
if (dir.isDirectory() && isInteger(dir.getName())) {
try {
long time = Long.parseLong(dir.getName());
long seconds = (now - time) / 1000;
long minutes = seconds / 60;
int retentionMinutes = empty(listFiles(dir)) ? cleanJavaXCache_emptyDirs_retentionMinutes : retentionHours * 60;
if (cleanJavaXCache_verbose)
print("Dir " + dir.getName() + " minutes: " + minutes + ", deleting? " + (minutes >= retentionMinutes));
if (minutes >= retentionMinutes) {
fileDeletions += cleanJavaXCache_removeDir(dir, verbose);
++deleted;
}
} catch (Throwable __e) {
_handleException(__e);
}
}
}
}
if (verbose && fileDeletions != 0)
print("Cleaned cache. File deletions: " + fileDeletions);
} catch (Throwable __e) {
_handleException(__e);
}
}
static public int cleanJavaXCache_removeDir(File dir, boolean verbose) {
int fileDeletions = 0;
if (!containsOneOf(dir.getAbsolutePath(), ".javax", "JavaX-Caches"))
throw fail("WHAT ARE YOU DOING!? >> " + dir.getAbsolutePath());
File[] files = listFiles(dir);
if (cleanJavaXCache_verbose)
print("Have " + n(files, "file") + " in " + dir);
for (File f : files) {
ping();
if (f.isDirectory())
cleanJavaXCache_removeDir(f, verbose);
else {
if (verbose)
print("Deleting " + f.getAbsolutePath());
f.delete();
++fileDeletions;
}
}
dir.delete();
return fileDeletions;
}
static public void _close(AutoCloseable c) {
if (c != null)
try {
c.close();
} catch (Throwable e) {
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else
throw rethrow(e);
}
}
static public Class javax() {
return getJavaX();
}
static public void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
static public HashMap findClass_fullName_cache = new HashMap();
static public Class findClass_fullName(String name) {
synchronized (findClass_fullName_cache) {
if (findClass_fullName_cache.containsKey(name))
return findClass_fullName_cache.get(name);
Class c;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_fullName_cache.put(name, c);
return c;
}
}
static public Object _defaultClassFinder_value = defaultDefaultClassFinder();
static public Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
static public Concepts newConceptsWithClassFinder(String progID) {
Concepts cc = new Concepts(progID);
cc.classFinder = _defaultClassFinder();
return cc;
}
static public String getDBProgramID_id;
static public String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
static public int shorten_default = 100;
static public String shorten(CharSequence s) {
return shorten(s, shorten_default);
}
static public String shorten(CharSequence s, int max) {
return shorten(s, max, "...");
}
static public 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 public String shorten(int max, CharSequence s) {
return shorten(s, max);
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) {
return new SmartTimerTask(r, timer, delay, _threadInfo());
}
static public class SmartTimerTask extends TimerTask implements IFieldsToList {
public Object r;
public java.util.Timer timer;
public long delay;
public Object threadInfo;
public SmartTimerTask() {
}
public SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) {
this.threadInfo = threadInfo;
this.delay = delay;
this.timer = timer;
this.r = r;
}
public String toString() {
return shortClassName(this) + "(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")";
}
public Object[] _fieldsToList() {
return new Object[] { r, timer, delay, threadInfo };
}
public long lastRun;
public void run() {
if (!licensed())
timer.cancel();
else {
_threadInheritInfo(threadInfo);
AutoCloseable __1 = tempActivity(r);
try {
lastRun = fixTimestamp(lastRun);
long now = now();
if (now >= lastRun + delay * 0.9) {
lastRun = now;
if (eq(false, pcallF(r)))
timer.cancel();
}
} finally {
_close(__1);
}
}
}
}
static public 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 public int toInt(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
static public A vmBus_timerStarted(A timer) {
vmBus_send("timerStarted", timer, costCenter());
return timer;
}
static public long toMS(double seconds) {
return (long) (seconds * 1000);
}
static public boolean dm_osLoading() {
return isTrue(dm_callOS("isLoading"));
}
static public int max(int a, int b) {
return Math.max(a, b);
}
static public int max(int a, int b, int c) {
return max(max(a, b), c);
}
static public long max(int a, long b) {
return Math.max((long) a, b);
}
static public long max(long a, long b) {
return Math.max(a, b);
}
static public double max(int a, double b) {
return Math.max((double) a, b);
}
static public float max(float a, float b) {
return Math.max(a, b);
}
static public double max(double a, double b) {
return Math.max(a, b);
}
static public int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static public 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 public 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 public byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
static public short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
static public int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
static public long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static public String _userHome;
static public String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
static public File userHome(String path) {
return new File(userDir(), path);
}
static public File javaxTempDir() {
return javaxCachesDir("Temp");
}
static public File javaxTempDir(String sub) {
return newFile(javaxTempDir(), sub);
}
static volatile public StringBuffer local_log = new StringBuffer();
static volatile public Appendable print_log = local_log;
static volatile public int print_log_max = 1024 * 1024;
static volatile public int local_log_max = 100 * 1024;
static public boolean print_silent = false;
static public Object print_byThread_lock = new Object();
static volatile public ThreadLocal print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = o + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
try {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
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 public 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 public void print_autoRotate() {
}
static public String n(long l, String name) {
return l + " " + trim(l == 1 ? singular(name) : getPlural(name));
}
static public String n(Collection l, String name) {
return n(l(l), name);
}
static public String n(Map m, String name) {
return n(l(m), name);
}
static public String n(Object[] a, String name) {
return n(l(a), name);
}
static public String n(MultiSet ms, String name) {
return n(l(ms), name);
}
static public boolean isInteger(String s) {
int n = l(s);
if (n == 0)
return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n)
return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9')
return false;
++i;
}
return true;
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean empty(Iterable c) {
return c == null || !c.iterator().hasNext();
}
static public boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean empty(Map map) {
return map == null || map.isEmpty();
}
static public boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static public 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 public boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
static public boolean empty(double[] a) {
return a == null || a.length == 0;
}
static public boolean empty(float[] a) {
return a == null || a.length == 0;
}
static public boolean empty(int[] a) {
return a == null || a.length == 0;
}
static public boolean empty(long[] a) {
return a == null || a.length == 0;
}
static public boolean empty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean empty(short[] a) {
return a == null || a.length == 0;
}
static public boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public File[] listFiles(File dir) {
File[] files = dir.listFiles();
return files == null ? new File[0] : files;
}
static public File[] listFiles(String dir) {
return listFiles(new File(dir));
}
static volatile public PersistableThrowable _handleException_lastException;
static public List _handleException_onException = synchroList(ll("printStackTrace2"));
static public 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)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
try {
printStackTrace2(e3);
} catch (Throwable e4) {
System.out.println(getStackTrace(e3));
System.out.println(getStackTrace(e4));
}
}
}
static public boolean containsOneOf(Collection l, A... x) {
for (A a : unnull(l)) if (eqOneOf(a, x))
return true;
return false;
}
static public boolean containsOneOf(Collection l, Set set) {
if (set == null)
return false;
for (A a : unnull(l)) if (set.contains(a))
return true;
return false;
}
static public boolean containsOneOf(String s, String... x) {
for (String o : x) if (contains(s, o))
return true;
return false;
}
static volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal ping_isCleanUpThread = new ThreadLocal();
static public boolean ping() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
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 public Class __javax;
static public Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
static public void printStackTrace2() {
printStackTrace2(new Throwable());
}
static public void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static public Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (name.startsWith("loadableUtils.utils$"))
return findClass_fullName("main" + name.substring(19));
return null;
}
};
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(Object o) {
return !empty(o);
}
static public String programIDWithCase() {
return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID();
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public CharSequence subCharSequence(CharSequence s, int x) {
return subCharSequence(s, x, s == null ? 0 : s.length());
}
static public CharSequence subCharSequence(CharSequence s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.subSequence(x, y);
}
static public int min(int a, int b) {
return Math.min(a, b);
}
static public long min(long a, long b) {
return Math.min(a, b);
}
static public float min(float a, float b) {
return Math.min(a, b);
}
static public float min(float a, float b, float c) {
return min(min(a, b), c);
}
static public double min(double a, double b) {
return Math.min(a, b);
}
static public double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static public float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static public byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
static public short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
static public int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
static public String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
static public String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static public String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static public String shortClassName(Object o) {
if (o == null)
return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
static volatile public boolean licensed_yes = true;
static public boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
static public void licensed_off() {
licensed_yes = false;
}
static public AutoCloseable tempActivity(Object r) {
return null;
}
static public long fixTimestamp(long timestamp) {
return timestamp > now() ? 0 : timestamp;
}
static public boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public void pcallF(VF1 f, A a) {
try {
if (f != null)
f.get(a);
} catch (Throwable __e) {
_handleException(__e);
}
}
static public B pcallF(IF1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static public int parseInt(char c) {
return Integer.parseInt(str(c));
}
static public int boolToInt(boolean b) {
return b ? 1 : 0;
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public 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 public void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static public Object costCenter() {
return mc();
}
static public Object dm_callOS(String functionName, Object... args) {
return call(dm_os(), functionName, args);
}
static public String actualUserHome_value;
static public String actualUserHome() {
if (actualUserHome_value == null) {
if (isAndroid())
actualUserHome_value = "/storage/emulated/0/";
else
actualUserHome_value = System.getProperty("user.home");
}
return actualUserHome_value;
}
static public File actualUserHome(String sub) {
return newFile(new File(actualUserHome()), sub);
}
static public File userDir() {
return new File(userHome());
}
static public File userDir(String path) {
return new File(userHome(), path);
}
static public File javaxCachesDir_dir;
static public File javaxCachesDir() {
return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
static public File javaxCachesDir(String sub) {
return newFile(javaxCachesDir(), sub);
}
static public File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static public File newFile(String name) {
return name == null ? null : new File(name);
}
static public File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static public boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static public Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static public A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static public A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
static public Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
return x30_util.callF(f, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static public String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static public String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static public String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static public 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 public 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 public Class mc() {
return main.class;
}
static public String trim(String s) {
return s == null ? null : s.trim();
}
static public String trim(StringBuilder buf) {
return buf.toString().trim();
}
static public String trim(StringBuffer buf) {
return buf.toString().trim();
}
static public Map singular_specials = litmap("children", "child", "images", "image", "chess", "chess");
static public Set singular_specials2 = litciset("time", "machine", "line", "rule");
static public String singular(String s) {
if (s == null)
return null;
{
String __1 = singular_specials.get(s);
if (!empty(__1))
return __1;
}
if (singular_specials2.contains(dropSuffix("s", afterLastSpace(s))))
return dropSuffix("s", s);
if (s.endsWith("ness"))
return s;
if (s.endsWith("ges"))
return dropSuffix("s", s);
if (endsWith(s, "bases"))
return dropLast(s);
s = dropSuffix("es", s);
s = dropSuffix("s", s);
return s;
}
static public List getPlural_specials = ll("sheep", "fish");
static public String getPlural(String s) {
if (containsIgnoreCase(getPlural_specials, s))
return s;
if (ewic(s, "y"))
return dropSuffixIgnoreCase("y", s) + "ies";
if (ewicOneOf(s, "ss", "ch"))
return s + "es";
if (ewic(s, "s"))
return s;
return s + "s";
}
static public String getType(Object o) {
return getClassName(o);
}
static public long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static public long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static public List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static public Throwable innerException(Throwable e) {
return getInnerException(e);
}
static public ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static public ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public int[] unnull(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnull(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnull(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public long unnull(Long l) {
return l == null ? 0L : l;
}
static public boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
static public boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
static public boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static public boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static public boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static public boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
static public boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static public void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static public Thread currentThread() {
return Thread.currentThread();
}
static public ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
static public AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static public String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
static volatile public String caseID_caseID;
static public String caseID() {
return caseID_caseID;
}
static public void caseID(String id) {
caseID_caseID = id;
}
static public String quoteUnlessIdentifierOrInteger(String s) {
return quoteIfNotIdentifierOrInteger(s);
}
static public String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static public String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static public String formatSnippetID(long id) {
return "#" + id;
}
static public Class getMainClass() {
return mc();
}
static public Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
ClassLoader cl = (o instanceof Class ? (Class) o : o.getClass()).getClassLoader();
return cl == null ? null : cl.loadClass("main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String shortenClassName(String name) {
if (name == null)
return null;
int i = lastIndexOf(name, "$");
if (i < 0)
i = lastIndexOf(name, ".");
return i < 0 ? name : substring(name, i + 1);
}
static public Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
static public boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static public Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public void pcallFAll(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) pcallF(f, args);
}
static public void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static public Set vm_busListeners_live_cache;
static public Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
static public Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static public Map vm_busListenersByMessage_live_cache;
static public Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
static public Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public Object dm_os() {
{
Object __1 = vm_generalMap_get("stefansOS");
if (__1 != null)
return __1;
}
return creator();
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static public 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);
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);
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 volatile public PersistableThrowable lastException_lastException;
static public PersistableThrowable lastException() {
return lastException_lastException;
}
static public void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static public String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
static public 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 public String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static public 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 public 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 public HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static public void litmap_impl(Map map, Object... x) {
if (x != null)
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
static public TreeSet litciset(String... items) {
TreeSet set = caseInsensitiveSet();
for (String a : items) set.add(a);
return set;
}
static public String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public String afterLastSpace(String s) {
return s == null ? null : substring(s, s.lastIndexOf(' ') + 1);
}
static public boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static public boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
static public boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b))
return false;
m.m = new String[] { dropLast(l(b), a) };
return true;
}
static public A[] dropLast(A[] a) {
return dropLast(a, 1);
}
static public A[] dropLast(A[] a, int n) {
if (a == null)
return null;
n = Math.min(n, a.length);
A[] b = arrayOfSameType(a, a.length - n);
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static public List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
static public List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
static public List dropLast(Iterable l) {
return dropLast(asList(l));
}
static public String dropLast(String s) {
return substring(s, 0, l(s) - 1);
}
static public String dropLast(String s, int n) {
return substring(s, 0, l(s) - n);
}
static public String dropLast(int n, String s) {
return dropLast(s, n);
}
static public boolean containsIgnoreCase(Collection l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
static public boolean containsIgnoreCase(String[] l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
static public boolean containsIgnoreCase(String s, char c) {
return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}
static public boolean containsIgnoreCase(String a, String b) {
return indexOfIgnoreCase(a, b) >= 0;
}
static public boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static public boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static public String dropSuffixIgnoreCase(String suffix, String s) {
return ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public boolean ewicOneOf(String s, String... l) {
if (s != null)
for (String x : l) if (ewic(s, x))
return true;
return false;
}
static public Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
static public Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(long[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(double[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static public 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 public ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public Object collectionMutex(List l) {
return l;
}
static public 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 public ArrayList emptyList() {
return new ArrayList();
}
static public ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
static public ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static public ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
static public ArrayList emptyList(Class c) {
return new ArrayList();
}
static public int[] emptyIntArray_a = new int[0];
static public int[] emptyIntArray() {
return emptyIntArray_a;
}
static public char[] emptyCharArray = new char[0];
static public char[] emptyCharArray() {
return emptyCharArray;
}
static public double[] emptyDoubleArray = new double[0];
static public double[] emptyDoubleArray() {
return emptyDoubleArray;
}
static public Map emptyMap() {
return new HashMap();
}
static public Object[] emptyObjectArray_a = new Object[0];
static public Object[] emptyObjectArray() {
return emptyObjectArray_a;
}
static public AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null)
return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
static public Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null)
return e;
while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause();
return e;
}
static public String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix))
return s;
return replacement + substring(s, l(prefix));
}
static public Throwable innerException2(Throwable e) {
if (e == null)
return null;
while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
return e;
}
static public String quoteIfNotIdentifierOrInteger(String s) {
if (s == null)
return null;
return isJavaIdentifier(s) || isInteger(s) ? s : quote(s);
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
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 public int lastIndexOf(String a, String b) {
return a == null || b == null ? -1 : a.lastIndexOf(b);
}
static public int lastIndexOf(String a, char b) {
return a == null ? -1 : a.lastIndexOf(b);
}
static public int lastIndexOf(List l, int i, A a) {
if (l == null)
return -1;
for (i = min(l(l), i) - 1; i >= 0; i--) if (eq(l.get(i), a))
return i;
return -1;
}
static public int lastIndexOf(List l, A a) {
if (l == null)
return -1;
for (int i = l(l) - 1; i >= 0; i--) if (eq(l.get(i), a))
return i;
return -1;
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public 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);
}
static public String substring(String s, CharSequence l) {
return substring(s, l(l));
}
static public Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static public Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static public WeakReference creator_class;
static public Object creator() {
return creator_class == null ? null : creator_class.get();
}
static final public Map callOpt_cache = newDangerousWeakHashMap();
static public Object callOpt_cached(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null)
return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public _MethodCache callOpt_getCache(Class c) {
synchronized (callOpt_cache) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
}
static public 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 public boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static public Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = args.length;
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs - n);
arraycopy(args, n, varArgs, 0, nArgs - n);
newArgs[n] = varArgs;
return newArgs;
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public List classNames(Collection l) {
return getClassNames(l);
}
static public List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static public boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x))
return true;
return false;
}
static public boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m))
return true;
return false;
}
static public boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static public String hostNameFromURL(String url) {
try {
return new URL(url).getHost();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public TreeSet caseInsensitiveSet() {
return caseInsensitiveSet_treeSet();
}
static public TreeSet caseInsensitiveSet(Collection c) {
return caseInsensitiveSet_treeSet(c);
}
static public TreeSet treeSet() {
return new TreeSet();
}
static public char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s) - 1);
}
static public A[] arrayOfSameType(A[] a, int n) {
return newObjectArrayOfSameType(a, n);
}
static public List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static public List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static public List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return l.subList(startIndex, endIndex);
}
static public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public int indexOfIgnoreCase(List a, String b) {
return indexOfIgnoreCase(a, b, 0);
}
static public int indexOfIgnoreCase(List a, String b, int i) {
int n = a == null ? 0 : a.size();
for (; i < n; i++) if (eqic(a.get(i), b))
return i;
return -1;
}
static public int indexOfIgnoreCase(String a, String b) {
return indexOfIgnoreCase_manual(a, b);
}
static public int indexOfIgnoreCase(String a, String b, int i) {
return indexOfIgnoreCase_manual(a, b, i);
}
static public boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
}
static public boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b))
return false;
if (m != null)
m.m = new String[] { substring(a, 0, l(a) - l(b)) };
return true;
}
static public Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static public String className(Object o) {
return getClassName(o);
}
static public A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public 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 public 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 public boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static public String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
static public 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 public 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 public 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 public int strL(String s) {
return s == null ? 0 : s.length();
}
static public Map vm_generalMap_map;
static public Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static public Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static public String joinWithSpace(Iterable c) {
return join(" ", c);
}
static public String joinWithSpace(String... c) {
return join(" ", c);
}
static public boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static public boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
static public void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, Math.min(a.length, b.length));
}
static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
static public A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
static public A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
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 public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
static public boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
static public String theAGIBlueDomain() {
return "agi.blue";
}
static public TreeSet caseInsensitiveSet_treeSet() {
return new TreeSet(caseInsensitiveComparator());
}
static public TreeSet caseInsensitiveSet_treeSet(Collection c) {
return toCaseInsensitiveSet_treeSet(c);
}
static public A[] newObjectArrayOfSameType(A[] a, int n) {
return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
static public int indexOfIgnoreCase_manual(String a, String b) {
return indexOfIgnoreCase_manual(a, b, 0);
}
static public int indexOfIgnoreCase_manual(String a, String b, int i) {
int la = strL(a), lb = strL(b);
if (la < lb)
return -1;
int n = la - lb;
loop: for (; i <= n; i++) {
for (int j = 0; j < lb; j++) {
char c1 = a.charAt(i + j), c2 = b.charAt(j);
if (!eqic(c1, c2))
continue loop;
}
return i;
}
return -1;
}
static public boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static public boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static public int listL(Collection l) {
return l == null ? 0 : l.size();
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public long parseLong(String s) {
if (empty(s))
return 0;
return Long.parseLong(dropSuffix("L", s));
}
static public long parseLong(Object s) {
return Long.parseLong((String) s);
}
static public 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 public A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public Character first(CharSequence s) {
return empty(s) ? null : s.charAt(0);
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public Comparator caseInsensitiveComparator() {
return betterCIComparator();
}
static public TreeSet toCaseInsensitiveSet_treeSet(Iterable c) {
if (isCISet(c))
return (TreeSet) c;
TreeSet set = caseInsensitiveSet_treeSet();
addAll(set, c);
return set;
}
static public TreeSet toCaseInsensitiveSet_treeSet(String... x) {
TreeSet set = caseInsensitiveSet_treeSet();
addAll(set, x);
return set;
}
static public betterCIComparator_C betterCIComparator_instance;
static public betterCIComparator_C betterCIComparator() {
if (betterCIComparator_instance == null)
betterCIComparator_instance = new betterCIComparator_C();
return betterCIComparator_instance;
}
final static public class betterCIComparator_C implements Comparator {
public int compare(String s1, String s2) {
if (s1 == null)
return s2 == null ? 0 : -1;
if (s2 == null)
return 1;
int n1 = s1.length();
int n2 = s2.length();
int min = Math.min(n1, n2);
for (int i = 0; i < min; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
if (c1 != c2) {
return c1 - c2;
}
}
}
}
return n1 - n2;
}
}
static public boolean isCISet(Iterable l) {
return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator();
}
static public void addAll(Collection c, Iterable b) {
if (c != null && b != null)
for (A a : b) c.add(a);
}
static public boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static public boolean addAll(Collection c, B... b) {
return c != null && b != null && c.addAll(Arrays.asList(b));
}
static public Map addAll(Map a, Map extends A, ? extends B> b) {
if (a != null)
a.putAll(b);
return a;
}
final static public class _MethodCache {
final public Class c;
final public HashMap> cache = new HashMap();
public _MethodCache(Class c) {
this.c = c;
_init();
}
public void _init() {
Class _c = c;
while (_c != null) {
for (Method m : _c.getDeclaredMethods()) if (!isAbstract(m) && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
_c = _c.getSuperclass();
}
for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
}
public Method findMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Method findStaticMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (isStaticMethod(me) && call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static public interface IFieldsToList {
public Object[] _fieldsToList();
}
static public class FixedRateTimer extends java.util.Timer {
public FixedRateTimer() {
this(false);
}
public FixedRateTimer(boolean daemon) {
this(defaultTimerName(), daemon);
}
public FixedRateTimer(String name) {
this(name, false);
}
public FixedRateTimer(String name, boolean daemon) {
super(name, daemon);
_registerTimer(this);
}
public List entries = synchroList();
static public class Entry implements IFieldsToList {
public TimerTask task;
public long firstTime;
public long period;
public Entry() {
}
public Entry(TimerTask task, long firstTime, long period) {
this.period = period;
this.firstTime = firstTime;
this.task = task;
}
public String toString() {
return shortClassName(this) + "(" + task + ", " + firstTime + ", " + period + ")";
}
public Object[] _fieldsToList() {
return new Object[] { task, firstTime, period };
}
}
public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
entries.add(new Entry(task, now() + delay, period));
super.scheduleAtFixedRate(task, delay, period);
}
public void cancel() {
entries.clear();
super.cancel();
}
public int purge() {
entries.clear();
return super.purge();
}
public FixedRateTimer changeRate(int newPeriod) {
Object r = ((SmartTimerTask) first(entries).task).r;
cancel();
return doEvery(newPeriod, r);
}
}
abstract static public class DynPrintLogAndEnabled extends DynPrintLog {
public JComponent visualize() {
return dm_visualizeWithEnabled(super.visualize());
}
volatile public boolean enabled = true;
transient public JPanel buttons;
public JComponent visualizeWithoutEnabled() {
return super.visualize();
}
public JComponent dm_visualizeWithEnabled(JComponent main) {
return centerAndSouthWithMargins(main, makeControlArea());
}
public JPanel makeControlArea() {
return buttons = jrightalignedline(makeEnabledCheckBox());
}
static public JCheckBox makeEnabledCheckBox() {
return dm_fieldCheckBox("enabled");
}
public void setEnabled(boolean b) {
setField("enabled", b);
}
public void addToControlArea(Component... components) {
addComponentsFirst(buttons, components);
}
}
static public boolean isAbstract(Class c) {
return (c.getModifiers() & Modifier.ABSTRACT) != 0;
}
static public boolean isAbstract(Method m) {
return (m.getModifiers() & Modifier.ABSTRACT) != 0;
}
static public boolean reflection_isForbiddenMethod(Method m) {
return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}
static public void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static public Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static public Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static public Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static public Set allInterfacesImplementedBy(Class c) {
if (c == null)
return null;
HashSet set = new HashSet();
allInterfacesImplementedBy_find(c, set);
return set;
}
static public void allInterfacesImplementedBy_find(Class c, Set set) {
if (c.isInterface() && !set.add(c))
return;
do {
for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set);
} while ((c = c.getSuperclass()) != null);
}
static public Method findMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args);
}
static public boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static public boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static public Method findStaticMethod(Class c, String method, Object... args) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (!m.getName().equals(method))
continue;
if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static public boolean findStaticMethod_checkArgs(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length)
return false;
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i])))
return false;
return true;
}
static public String defaultTimerName_name;
static public String defaultTimerName() {
if (defaultTimerName_name == null)
defaultTimerName_name = "A timer by " + programID();
return defaultTimerName_name;
}
static public Set _registerTimer_list = newWeakHashSet();
static public void _registerTimer(java.util.Timer timer) {
_registerTimer_list.add(timer);
}
static public void cleanMeUp__registerTimer() {
cancelTimers(getAndClearList(_registerTimer_list));
}
static public Method findMethod_cached(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
_MethodCache cache = callOpt_getCache(((Class) o));
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
return m;
return null;
} else {
_MethodCache cache = callOpt_getCache(o.getClass());
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (findMethod_checkArgs(m, args, false))
return m;
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Set newWeakHashSet() {
return synchroWeakHashSet();
}
static public void cancelTimers(Collection timers) {
for (Object timer : timers) cancelTimer(timer);
}
static public List getAndClearList(Collection l) {
if (l == null)
return emptyList();
synchronized (collectionMutex(l)) {
List out = cloneList(l);
l.clear();
return out;
}
}
static public Set synchroWeakHashSet() {
return Collections.newSetFromMap((Map) newWeakHashMap());
}
static public void cancelTimer(javax.swing.Timer timer) {
if (timer != null)
timer.stop();
}
static public void cancelTimer(java.util.Timer timer) {
if (timer != null)
timer.cancel();
}
static public void cancelTimer(Object o) {
if (o instanceof java.util.Timer)
cancelTimer((java.util.Timer) o);
else if (o instanceof javax.swing.Timer)
cancelTimer((javax.swing.Timer) o);
else if (o instanceof AutoCloseable) {
try {
((AutoCloseable) o).close();
} catch (Throwable __e) {
_handleException(__e);
}
}
}
static public JPanel centerAndSouthWithMargins(Component c, Component s) {
return applyDefaultMargin(centerAndSouth(c, withTopMargin(s)));
}
static public JPanel jrightalignedline(Component... components) {
return jrightAlignedLine(components);
}
static public JPanel jrightalignedline(List components) {
return jrightAlignedLine(components);
}
static public JCheckBox dm_fieldCheckBox(String field) {
return dm_fieldCheckBox(humanizeFormLabel(field), field);
}
static public JCheckBox dm_fieldCheckBox(String text, String field) {
if (isIdentifier(text) && !isIdentifier(field)) {
String temp = field;
field = text;
text = temp;
}
return jLiveValueCheckBox(text, dm_fieldLiveValue(field));
}
static public void addComponentsFirst(Container c, Component... l) {
containerAddFirst(c, l);
}
static public A applyDefaultMargin(final A c) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMarg...";
}
});
}
return c;
}
static public JPanel centerAndSouth(final Component c, final Component s) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
if (s != null)
panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT...";
}
});
}
static public int withTopMargin_defaultWidth = 6;
static public JPanel withTopMargin(Component c) {
return withTopMargin(withTopMargin_defaultWidth, c);
}
static public JPanel withTopMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
static public JPanel jrightAlignedLine(final Component... components) {
return swing(new F0() {
public RightAlignedLine get() {
try {
return new RightAlignedLine(components);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret RightAlignedLine(components);";
}
});
}
static public JPanel jrightAlignedLine(List extends Component> components) {
return jrightAlignedLine(asArray(Component.class, components));
}
static public Map humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5");
static public String humanizeFormLabel(String s) {
if (containsSpace(s))
return s;
return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID"));
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public JCheckBox jLiveValueCheckBox(String text, final SimpleLiveValue lv) {
final JCheckBox cb = jCheckBox(text);
bindCheckBoxToLiveValue(cb, lv);
return cb;
}
static public SimpleLiveValue dm_fieldLiveValue(String fieldName) {
return dm_fieldLiveValue(dm_current_mandatory(), fieldName);
}
static public SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
Lock __0 = module.lock;
lock(__0);
try {
AutoCloseable __2 = module.enter();
try {
Class type = getFieldType(module, fieldName);
final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName));
dm_watchField(fieldName, new Runnable() {
public void run() {
try {
Object o = get(module, fieldName);
value.set(o);
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting \" + fi...";
}
});
value.onChange(new Runnable() {
public void run() {
try {
module.setField(fieldName, value.get());
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting 2 \" + ...";
}
});
return value;
} finally {
_close(__2);
}
} finally {
unlock(__0);
}
}
static public void containerAddFirst(final Container c, final Component... l) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
for (int i = 0; i < l(l); i++) c.add(l[i], i);
revalidate(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "for (int i = 0; i < l(l); i++)\r\n c.add(l[i], i);\r\n revalidate(c);";
}
});
}
}
static public int withMargin_defaultWidth = 6;
static public JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
static public JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
static public JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
static public JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
static public Object swing(Object f) {
return swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public JComponent wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
static public JComponent wrap_2(Object swingable) {
if (swingable == null)
return null;
JComponent c;
if (swingable instanceof Component)
c = componentToJComponent(((Component) swingable));
else
c = componentToJComponent((Component) callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
static public Object[] asArray(List l) {
return toObjectArray(l);
}
static public A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static public boolean containsSpace(String s) {
return containsSpaces(s);
}
static public String firstToUpper(String s) {
if (empty(s))
return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
static public List replaceElementsUsingMap(Iterable l, final Map map) {
return map(l, new F1 () {
public A get(A a) {
try {
return getOrKeep(map, a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "getOrKeep(map, a)";
}
});
}
static public List splitCamelCase(String s) {
return ai_splitCamelCase(s);
}
static public JCheckBox jCheckBox() {
return swingNu(JCheckBox.class);
}
static public JCheckBox jCheckBox(boolean checked) {
return swingNu(JCheckBox.class, "", checked);
}
static public JCheckBox jCheckBox(String text, boolean checked) {
return swingNu(JCheckBox.class, text, checked);
}
static public JCheckBox jCheckBox(String text) {
return swingNu(JCheckBox.class, text);
}
static public JCheckBox jCheckBox(String text, boolean checked, final Object onChange) {
JCheckBox cb = jCheckBox(checked, onChange);
cb.setText(text);
return cb;
}
static public JCheckBox jCheckBox(boolean checked, final Object onChange) {
final JCheckBox cb = jCheckBox(checked);
cb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(onChange, cb.isSelected());
}
});
return cb;
}
static public A bindCheckBoxToLiveValue(final A cb, final SimpleLiveValue lv) {
bindLiveValueListenerToComponent(cb, lv, new Runnable() {
public void run() {
try {
setChecked(cb, isTrue(lv.get()));
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se...";
}
});
onChange(cb, new Runnable() {
public void run() {
try {
lv.set(isChecked(cb));
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se...";
}
});
return cb;
}
static public 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);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static public void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static public ReentrantLock lock() {
return fairLock();
}
static public Class getFieldType(Object o, String field) {
return fieldType(o, field);
}
static public void dm_watchField(String field, Runnable onChange) {
new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange);
}
static public void unlock(Lock lock, String msg) {
if (lock == null)
return;
lock.unlock();
print("Unlocked: " + msg);
}
static public void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
}
static public A revalidate(final A c) {
if (c == null || !c.isShowing())
return c;
{
swing(new Runnable() {
public void run() {
try {
c.revalidate();
c.repaint();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "// magic combo to actually relayout and repaint\r\n c.revalidate();\r\n c.r...";
}
});
}
return c;
}
static public void revalidate(JFrame f) {
revalidate((Component) f);
}
static public void revalidate(JInternalFrame f) {
revalidate((Component) f);
}
static public void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
static public A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
return c;
}
static public JComponent componentToJComponent(Component c) {
if (c instanceof JComponent)
return (JComponent) c;
if (c instanceof JFrame)
return ((JFrame) c).getRootPane();
if (c == null)
return null;
throw fail("boohoo " + getClassName(c));
}
static public JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JScrollPane(c);";
}
});
}
static public JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
static public JLabel jlabel() {
return jlabel(" ");
}
static public Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static public boolean containsSpaces(String s) {
return indexOf(s, ' ') >= 0;
}
static public List map(Iterable l, Object f) {
return map(f, l);
}
static public List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
static public List map(Iterable l, F1 f) {
return map(f, l);
}
static public List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(callF(f, o));
return x;
}
static public List map(IF1 f, Iterable l) {
return map(l, f);
}
static public List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(IF1 f, A[] l) {
return map(l, f);
}
static public List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static public A getOrKeep(Map map, A a) {
if (map == null)
return a;
A v = map.get(a);
return v != null ? v : a;
}
static public List ai_splitCamelCase(String s) {
int j = 0;
List l = new ArrayList();
if (isAllUpperCase(s)) {
l.add(s);
return l;
}
for (int i = 0; i < l(s); i++) if (i > j && isUpperCaseLetter(s.charAt(i))) {
l.add(substring(s, j, i));
j = i;
}
if (j < l(s))
l.add(substring(s, j));
return l;
}
static public A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static public A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) {
if (lv != null)
bindToComponent(component, new Runnable() {
public void run() {
try {
lv.onChangeAndNow(listener);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindLiveValueListenerToComponent_debug\r\n print(\"bindLiveValueL...";
}
}, new Runnable() {
public void run() {
try {
lv.removeOnChangeListener(listener);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "lv.removeOnChangeListener(listener)";
}
});
return component;
}
static public void setChecked(JCheckBox checkBox, boolean b) {
if (checkBox != null) {
swing(new Runnable() {
public void run() {
try {
if (isChecked(checkBox) != b)
checkBox.setSelected(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (isChecked(checkBox) != b)\r\n checkBox.setSelected(b);";
}
});
}
}
static public void setChecked(JCheckBoxMenuItem mi, boolean b) {
if (mi != null) {
swing(new Runnable() {
public void run() {
try {
mi.setSelected(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "mi.setSelected(b);";
}
});
}
}
static public A onChange(A spinner, Object r) {
{
swing(new Runnable() {
public void run() {
try {
spinner.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "spinner.addChangeListener(changeListener(r));";
}
});
}
return spinner;
}
static public A onChange(A b, Object r) {
{
swing(new Runnable() {
public void run() {
try {
b.addItemListener(itemListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "b.addItemListener(itemListener(r));";
}
});
}
return b;
}
static public void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
static public A onChange(A slider, final Object r) {
{
swing(new Runnable() {
public void run() {
try {
slider.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "slider.addChangeListener(changeListener(r));";
}
});
}
return slider;
}
static public JComboBox onChange(Object r, JComboBox cb) {
return onChange(cb, r);
}
static public JComboBox onChange(JComboBox cb, final Object r) {
if (isEditableComboBox(cb))
onChange(textFieldFromComboBox(cb), r);
else
onSelectedItem(cb, new VF1() {
public void get(String s) {
try {
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r)";
}
});
return cb;
}
static public boolean isChecked(final JCheckBox checkBox) {
return checkBox != null && (boolean) swing(new F0() {
public Boolean get() {
try {
return checkBox.isSelected();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret checkBox.isSelected();";
}
});
}
static public boolean isChecked(final JCheckBoxMenuItem mi) {
return mi != null && (boolean) swing(new F0() {
public Boolean get() {
try {
return mi.isSelected();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret mi.isSelected();";
}
});
}
static public Map vm_threadInterruptionReasonsMap() {
return vm_generalWeakSubMap("Thread interruption reasons");
}
static public String strOr(Object o, String ifNull) {
return o == null ? ifNull : str(o);
}
static public A printStackTrace(A e) {
print(getStackTrace(e));
return e;
}
static public void printStackTrace() {
printStackTrace(new Throwable());
}
static public void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static public void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static public void lockOrFail(Lock lock, long timeout) {
try {
ping();
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static public Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() {
public void run() {
try {
_inheritThreadInfo(info);
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_inheritThreadInfo(info); callF(r);";
}
};
}
static public A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () {
public A get() {
try {
return nuObject(c, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret nuObject(c, args);";
}
});
}
static public boolean isAllUpperCase(String s) {
return hasLettersAllUpperCase(s);
}
static public boolean isUpperCaseLetter(char c) {
return Character.isUpperCase(c);
}
static public ChangeListener changeListener(final Object r) {
return new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(r);
}
};
}
static public ItemListener itemListener(final Object r) {
return new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pcallF(r);
}
};
}
static public void onUpdate(JComponent c, final Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
call(r);
}
public void removeUpdate(DocumentEvent e) {
call(r);
}
public void changedUpdate(DocumentEvent e) {
call(r);
}
});
else if (c instanceof ItemSelectable)
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
call(r);
}
});
else
print("Warning: onUpdate doesn't know " + getClassName(c));
}
static public void onUpdate(List extends JComponent> l, Object r) {
for (JComponent c : l) onUpdate(c, r);
}
static public boolean isEditableComboBox(final JComboBox cb) {
return cb != null && swing(new F0() {
public Boolean get() {
try {
return cb.isEditable();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret cb.isEditable();";
}
});
}
static public JTextField textFieldFromComboBox(JComboBox cb) {
return (JTextField) cb.getEditor().getEditorComponent();
}
static public JComboBox onSelectedItem(final JComboBox cb, final VF1 f) {
addActionListener(cb, new Runnable() {
public void run() {
try {
pcallF(f, selectedItem(cb));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcallF(f, selectedItem(cb))";
}
});
return cb;
}
static public Runnable asRunnable(Object o) {
return toRunnable(o);
}
static public void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static public Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static public boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static public boolean hasLettersAllUpperCase(String s) {
return hasLetters(s) && !containsLowerCase(s);
}
static public void addActionListener(JTextField tf, final Runnable action) {
onEnter(tf, action);
}
static public void addActionListener(final JComboBox cb, final Runnable action) {
if (cb != null) {
swing(new Runnable() {
public void run() {
try {
cb.addActionListener(actionListener(action));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.addActionListener(actionListener(action));";
}
});
}
}
static public void addActionListener(final AbstractButton b, final Runnable action) {
if (b != null) {
swing(new Runnable() {
public void run() {
try {
b.addActionListener(actionListener(action));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "b.addActionListener(actionListener(action));";
}
});
}
}
static public String selectedItem(JList l) {
return getSelectedItem(l);
}
static public String selectedItem(JComboBox cb) {
return getSelectedItem(cb);
}
static public Runnable toRunnable(final Object o) {
if (o instanceof Runnable)
return (Runnable) o;
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
static public Map classForName_cache = synchroHashMap();
static public Class classForName(String name) {
try {
if (classForName_cache == null)
return Class.forName(name);
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = Class.forName(name));
return c;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static public Object nuObjectWithoutArguments(String className) {
try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObjectWithoutArguments(Class c) {
try {
if (nuObjectWithoutArguments_cache == null)
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
static public List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static public boolean hasLetters(String s) {
for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i)))
return true;
return false;
}
static public boolean containsLowerCase(String s) {
for (int i = 0; i < l(s); i++) if (isLowerCase(s.charAt(i)))
return true;
return false;
}
static public JTextField onEnter(final JTextField tf, final Object action) {
if (action == null || tf == null)
return tf;
tf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
tf.selectAll();
callF(action);
} catch (Throwable __e) {
messageBox(__e);
}
}
});
return tf;
}
static public JButton onEnter(JButton btn, final Object action) {
if (action == null || btn == null)
return btn;
btn.addActionListener(actionListener(action));
return btn;
}
static public JList onEnter(JList list, Object action) {
list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
return list;
}
static public JComboBox onEnter(final JComboBox cb, final Object action) {
{
swing(new Runnable() {
public void run() {
try {
if (cb.isEditable()) {
JTextField text = (JTextField) cb.getEditor().getEditorComponent();
onEnter(text, action);
} else {
cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
cb.getActionMap().put("enter", abstractAction("", new Runnable() {
public void run() {
try {
cb.hidePopup();
callF(action);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.hidePopup(); callF(action);";
}
}));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (cb.isEditable()) {\r\n JTextField text = (JTextField) cb.getEditor().g...";
}
});
}
return cb;
}
static public JTable onEnter(final JTable table, final Object action) {
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
table.getActionMap().put("Enter", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
callF(action, table.getSelectedRow());
}
});
return table;
}
static public JTextField onEnter(Object action, JTextField tf) {
return onEnter(tf, action);
}
static public ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
static public ActionListener actionListener(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
final Object info = _threadInfo();
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
_threadInheritInfo(info);
AutoCloseable __1 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__1);
}
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
static public String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
static public String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
static public Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static public Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
static public Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
static public boolean isLowerCase(char c) {
return Character.isLowerCase(c);
}
static public void messageBox(final String msg) {
if (headless())
print(msg);
else {
swing(new Runnable() {
public void run() {
try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES...";
}
});
}
}
static public void messageBox(Throwable e) {
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
static public KeyListener enterKeyListener(final Object action) {
return new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER)
pcallF(action);
}
};
}
static public Runnable rCallOnSelectedListItem(final JList list, final Object action) {
return new Runnable() {
public void run() {
try {
pcallF(action, getSelectedItem(list));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcallF(action, getSelectedItem(list))";
}
};
}
static public AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
static public ThreadLocal> holdInstance_l = new ThreadLocal();
static public AutoCloseable holdInstance(Object o) {
if (o == null)
return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
static public String strOrNull(Object o) {
return o == null ? null : str(o);
}
static public Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static public Class getClass(Object realm, String name) {
try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String classNameToVM(String name) {
return name.replace(".", "$");
}
static public boolean headless() {
return isHeadless();
}
static public void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null)
tl.set(l = new ArrayList());
l.add(a);
}
static public A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null)
return null;
A a = popLast(l);
if (empty(l))
tl.set(null);
return a;
}
static public A popLast(List l) {
return liftLast(l);
}
static public List popLast(int n, List l) {
return liftLast(n, l);
}
static public A liftLast(List l) {
if (empty(l))
return null;
int i = l(l) - 1;
A a = l.get(i);
l.remove(i);
return a;
}
static public List liftLast(int n, List l) {
int i = l(l) - n;
List part = cloneSubList(l, i);
removeSubList(l, i);
return part;
}
static public List cloneSubList(List l, int startIndex, int endIndex) {
return newSubList(l, startIndex, endIndex);
}
static public List cloneSubList(List l, int startIndex) {
return newSubList(l, startIndex);
}
static public void removeSubList(List l, int from, int to) {
if (l != null)
subList(l, from, to).clear();
}
static public void removeSubList(List l, int from) {
if (l != null)
subList(l, from).clear();
}
static public List newSubList(List l, int startIndex, int endIndex) {
return cloneList(subList(l, startIndex, endIndex));
}
static public List newSubList(List l, int startIndex) {
return cloneList(subList(l, startIndex));
}
static public class SimpleLiveValue extends LiveValue {
public Class type;
volatile public A value;
transient public List onChange = synchroList();
public SimpleLiveValue(Class type) {
this.type = type;
}
public SimpleLiveValue(Class type, A value) {
this.value = value;
this.type = type;
}
public Class getType() {
return type;
}
public A get() {
return value;
}
public void onChange(Runnable l) {
onChange.add(l);
}
public void onChangeAndNow(Runnable l) {
onChange(l);
callF(l);
}
public void removeOnChangeListener(Runnable l) {
onChange.remove(l);
}
public void fireChanged() {
pcallFAll(onChange);
}
public void set(A a) {
if (neq(value, a)) {
value = a;
fireChanged();
}
}
}
static public interface IF2 {
public C get(A a, B b);
}
static public class Var implements IVar {
public Var() {
}
public Var(A v) {
this.v = v;
}
public A v;
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() {
return v;
}
public synchronized boolean has() {
return v != null;
}
public synchronized void clear() {
v = null;
}
public String toString() {
return str(get());
}
}
static abstract public class LiveValue {
abstract public Class getType();
abstract public A get();
abstract public void onChange(Runnable l);
abstract public void removeOnChangeListener(Runnable l);
public void onChangeAndNow(Runnable l) {
onChange(l);
callF(l);
}
}
static public class Dyn_FieldWatcher {
public DynModule module;
public String field;
public Object value;
public Runnable action;
transient public IF1 cloneValue;
public Object cloneValue(Object o) {
return cloneValue != null ? cloneValue.get(o) : cloneValue_base(o);
}
final public Object cloneValue_fallback(IF1 _f, Object o) {
return _f != null ? _f.get(o) : cloneValue_base(o);
}
public Object cloneValue_base(Object o) {
return o;
}
public Dyn_FieldWatcher(DynModule module, String field, Runnable action) {
this(module, field, action, null);
}
public Dyn_FieldWatcher(DynModule module, String field, Runnable action, IF1 cloneValue) {
this.cloneValue = cloneValue;
this.action = action;
this.field = field;
this.module = module;
value = cloneValue(get(module, field));
module.onChange(new Runnable() {
public void run() {
try {
check();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "check();";
}
});
module.onFieldChange(new VF1() {
public void get(String f) {
try {
if (eq(f, field))
check();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(f, field))\r\n check();";
}
});
}
public void check() {
Object newValue = cloneValue(get(module, field));
if (eq(value, newValue))
return;
value = newValue;
dm_q(module, action);
}
}
static public class RightAlignedLine extends JPanel {
public RightAlignedLine(Component... components) {
setLayout(LetterLayout.rightAlignedRow());
for (Component component : components) add(component);
}
public void add(String text) {
add(new JLabel(text));
}
}
static public interface IVar extends IF0 {
public void set(A a);
public A get();
default public boolean has() {
return get() != null;
}
default public void clear() {
set(null);
}
}
static public class LetterLayout implements LayoutManager {
public String[] lines;
public Map map = new TreeMap();
public RC[] rows;
public RC[] cols;
public Cell[][] cells;
public int spacingX = 10, spacingY = 10;
public int insetTop, insetBottom, insetLeft, insetRight;
public int template;
public boolean formWideLeftSide, formWideRightSide;
static final public int STALACTITE = 1, LEFT_ALIGNED_ROW = 2, CENTERED_ROW = 3, FORM = 4, RIGHT_ALIGNED_ROW = 5;
public boolean debug = false;
public void setLeftBorder(int border) {
insetLeft = border;
}
public void setRightBorder(int border) {
insetRight = border;
}
public static JComponent withBorder(JComponent component, int border) {
JPanel panel = new JPanel(new LetterLayout("C").setBorder(border));
panel.add("C", component);
return panel;
}
public static JPanel panel(String... lines) {
return new JPanel(new LetterLayout(lines));
}
public static JPanel stalactitePanel() {
return new JPanel(stalactite());
}
static public class DummyComponent extends JComponent {
}
static public class Cell {
public boolean aux = false;
public int minWidth, minHeight;
public Component component;
public int colspan, rowspan;
public double weightX, weightY;
}
static public class RC {
public int min;
public double weightSum;
public int start;
public int minEnd;
}
public LetterLayout(int template) {
this.template = template;
}
public LetterLayout(String... lines) {
this.lines = lines;
}
public void removeLayoutComponent(Component component) {
map.values().remove(component);
}
public void layoutContainer(Container container) {
prepareLayout(container);
if (debug)
System.out.println("Container size: " + container.getSize());
Insets insets = getInsets(container);
for (int r = 0; r < rows.length; r++) {
for (int i = 0; i < cols.length; ) {
Cell cell = cells[i][r];
if (cell.aux)
++i;
else {
if (cell.component != null) {
int x1 = cols[i].start;
int y1 = rows[r].start;
int x2 = i + cell.colspan < cols.length ? cols[i + cell.colspan].start - spacingX : container.getWidth() - insets.right;
int y2 = r + cell.rowspan < rows.length ? rows[r + cell.rowspan].start - spacingY : container.getHeight() - insets.bottom;
if (debug)
System.out.println("Layouting (" + i + ", " + r + ", " + cell.component.getClass().getName() + "): " + x1 + " " + y1 + " " + x2 + " " + y2);
cell.component.setBounds(x1, y1, x2 - x1, y2 - y1);
}
i += cells[i][r].colspan;
}
}
}
}
final public void prepareLayout(Container container) {
applyTemplate(container);
int numRows = lines.length, numCols = lines[0].length();
for (int i = 1; i < numRows; i++) if (lines[i].length() != numCols)
throw new IllegalArgumentException("Lines have varying length");
cells = new Cell[numCols][numRows];
rows = new RC[numRows];
cols = new RC[numCols];
for (int r = 0; r < numRows; r++) rows[r] = new RC();
for (int i = 0; i < numCols; i++) cols[i] = new RC();
for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r] = new Cell();
for (int r = 0; r < numRows; r++) {
String line = lines[r];
for (int i = 0; i < numCols; ) {
Cell cell = cells[i][r];
if (cell.aux) {
++i;
continue;
}
char ch = line.charAt(i);
int iNext = i;
do ++iNext; while (iNext < numCols && ch == line.charAt(iNext));
int rNext = r;
do ++rNext; while (rNext < numRows && ch == lines[rNext].charAt(i));
cell.weightX = numCols == 1 || iNext > i + 1 ? 1.0 : 0.0;
cell.weightY = numRows == 1 || rNext > r + 1 ? 1.0 : 0.0;
Component c = map.get(String.valueOf(ch));
cell.component = c;
if (c != null) {
cell.minWidth = c.getMinimumSize().width + spacingX;
cell.minHeight = getMinimumHeight(c) + spacingY;
}
cell.colspan = iNext - i;
cell.rowspan = rNext - r;
if (cell.colspan == 1)
cols[i].min = Math.max(cols[i].min, cell.minWidth);
if (cell.rowspan == 1)
rows[r].min = Math.max(rows[r].min, cell.minHeight);
for (int r2 = r; r2 < rNext; r2++) for (int i2 = i; i2 < iNext; i2++) if (r2 != r || i2 != i)
cells[i2][r2].aux = true;
i = iNext;
}
}
while (true) {
for (int i = 0; i < numCols; i++) {
int minStart = i == 0 ? 0 : cols[i - 1].minEnd;
double weightStart = i == 0 ? 0.0 : cols[i - 1].weightSum;
for (int r = 0; r < numRows; r++) {
Cell cell = cells[i][r];
if (!cell.aux) {
RC rc = cols[i + cell.colspan - 1];
rc.minEnd = Math.max(rc.minEnd, minStart + cell.minWidth);
rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightX);
}
}
}
for (int r = 0; r < numRows; r++) {
int minStart = r == 0 ? 0 : rows[r - 1].minEnd;
double weightStart = r == 0 ? 0.0 : rows[r - 1].weightSum;
for (int i = 0; i < numCols; i++) {
Cell cell = cells[i][r];
if (!cell.aux) {
RC rc = rows[r + cell.rowspan - 1];
rc.minEnd = Math.max(rc.minEnd, minStart + cell.minHeight);
rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightY);
}
}
}
if (allWeightsZero(cols)) {
for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightX = 1.0;
continue;
}
if (allWeightsZero(rows)) {
for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightY = 1.0;
continue;
}
break;
}
Insets insets = getInsets(container);
determineStarts(cols, insets.left, container.getWidth() - insets.left - insets.right + spacingX, spacingX);
determineStarts(rows, insets.top, container.getHeight() - insets.top - insets.bottom + spacingY, spacingY);
}
final public boolean allWeightsZero(RC[] rcs) {
for (int i = 0; i < rcs.length; i++) if (rcs[i].weightSum != 0.0)
return false;
return true;
}
static public int getMinimumHeight(Component c) {
return c.getMinimumSize().height;
}
final public void applyTemplate(Container container) {
if (template == STALACTITE) {
Component[] components = container.getComponents();
lines = new String[components.length + 2];
map.clear();
for (int i = 0; i < components.length; i++) {
String s = String.valueOf(makeIndexChar(i));
map.put(s, components[i]);
lines[i] = s;
}
lines[components.length] = lines[components.length + 1] = " ";
} else if (template == FORM) {
Component[] components = container.getComponents();
int numRows = components.length / 2;
lines = new String[numRows + 2];
map.clear();
for (int row = 0; row < numRows; row++) {
String lower = String.valueOf(makeIndexChar(row));
String upper = String.valueOf(makeAlternateIndexChar(row));
Component rightComponent = components[row * 2 + 1];
if (rightComponent instanceof DummyComponent)
upper = lower;
lines[row] = (formWideLeftSide ? lower + lower : lower) + (formWideRightSide ? upper + upper : upper);
map.put(lower, components[row * 2]);
if (!(rightComponent instanceof DummyComponent))
map.put(upper, rightComponent);
}
lines[numRows] = lines[numRows + 1] = (formWideLeftSide ? " " : " ") + (formWideRightSide ? " " : " ");
} else if (template == LEFT_ALIGNED_ROW) {
lines = new String[] { makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
} else if (template == CENTERED_ROW) {
lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
} else if (template == RIGHT_ALIGNED_ROW) {
lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) };
}
}
final public String makeSingleRow(Container container) {
Component[] components = container.getComponents();
StringBuffer buf = new StringBuffer();
map.clear();
for (int i = 0; i < components.length; i++) {
String s = String.valueOf(makeAlternateIndexChar(i));
map.put(s, components[i]);
buf.append(s);
}
return buf.toString();
}
static public void determineStarts(RC[] rcs, int start, int totalSize, int spacing) {
int minTotal = rcs[rcs.length - 1].minEnd;
double weightSum = rcs[rcs.length - 1].weightSum;
int spare = (int) ((totalSize - minTotal) / (weightSum == 0.0 ? 1.0 : weightSum));
int x = start, minSum = 0;
double prevWeightSum = 0.0;
for (int i = 0; i < rcs.length; i++) {
int width = rcs[i].minEnd - minSum + (int) ((rcs[i].weightSum - prevWeightSum) * spare) - spacing;
rcs[i].start = x;
x += width + spacing;
prevWeightSum = rcs[i].weightSum;
minSum = rcs[i].minEnd;
}
}
public void addLayoutComponent(String s, Component component) {
map.put(s, component);
}
public Dimension minimumLayoutSize(Container container) {
prepareLayout(container);
Insets insets = getInsets(container);
Dimension result = new Dimension(insets.left + cols[cols.length - 1].minEnd + insets.right - spacingX, insets.top + rows[rows.length - 1].minEnd + insets.bottom - spacingY);
return result;
}
final public Insets getInsets(Container container) {
Insets insets = container.getInsets();
return new Insets(insets.top + insetTop, insets.left + insetLeft, insets.bottom + insetBottom, insets.right + insetRight);
}
public Dimension preferredLayoutSize(Container container) {
return minimumLayoutSize(container);
}
public LetterLayout setSpacing(int x, int y) {
spacingX = x;
spacingY = y;
return this;
}
public LetterLayout setSpacing(int spacing) {
return setSpacing(spacing, spacing);
}
public LetterLayout setBorder(int top, int left, int bottom, int right) {
insetTop = top;
insetLeft = left;
insetBottom = bottom;
insetRight = right;
return this;
}
public LetterLayout setBorder(int inset) {
return setBorder(inset, inset, inset, inset);
}
public LetterLayout setTopBorder(int inset) {
insetTop = inset;
return this;
}
public static LetterLayout stalactite() {
return new LetterLayout(STALACTITE);
}
public static LetterLayout leftAlignedRow() {
return new LetterLayout(LEFT_ALIGNED_ROW);
}
public static LetterLayout leftAlignedRow(int spacing) {
return leftAlignedRow().setSpacing(spacing);
}
public static LetterLayout centeredRow() {
return new LetterLayout(CENTERED_ROW);
}
public static LetterLayout rightAlignedRow() {
return new LetterLayout(RIGHT_ALIGNED_ROW);
}
public static JPanel rightAlignedRowPanel(JComponent... components) {
return makePanel(new LetterLayout(RIGHT_ALIGNED_ROW), components);
}
static public JPanel makePanel(LetterLayout letterLayout, JComponent[] components) {
JPanel panel = new JPanel(letterLayout);
for (JComponent component : components) {
panel.add(component);
}
return panel;
}
public static LetterLayout form() {
LetterLayout letterLayout = new LetterLayout(FORM);
letterLayout.formWideLeftSide = true;
letterLayout.formWideRightSide = true;
return letterLayout;
}
public static LetterLayout formWideRightSide() {
LetterLayout letterLayout = new LetterLayout(FORM);
letterLayout.formWideRightSide = true;
return letterLayout;
}
public static Component getDummyComponent() {
return new DummyComponent();
}
public static JPanel newPanel(String... lines) {
return new JPanel(new LetterLayout(lines));
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public static char makeIndexChar(int idx) {
return (char) ('a' + idx * 2);
}
public static char makeAlternateIndexChar(int idx) {
return (char) ('b' + idx * 2);
}
public static char LEFT_CHAR = ',', RIGHT_CHAR = '.';
public static void main(String[] args) {
System.out.println((int) makeIndexChar(0));
System.out.println((int) makeAlternateIndexChar(0));
System.out.println((int) makeIndexChar(32000));
System.out.println((int) makeAlternateIndexChar(32000));
System.out.println((int) LEFT_CHAR);
System.out.println((int) RIGHT_CHAR);
}
}
static public Q dm_q() {
return dm_current_mandatory().q();
}
static public void dm_q(Runnable r) {
dm_inQ(r);
}
static public void dm_q(DynModule module, Runnable r) {
module.q().add(r);
}
static public A dm_q(IF0 f) {
return dm_evalInQ(if0ToF0(f));
}
static public void add(BitSet bs, int i) {
bs.set(i);
}
static public boolean add(Collection c, A a) {
return c != null && c.add(a);
}
static public void add(Container c, Component x) {
addToContainer(c, x);
}
static public A set(A o, String field, Object value) {
if (o == null)
return null;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
static public void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static public Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static public void dm_inQ(Runnable r) {
dm_q().add(r);
}
static public A dm_evalInQ(F0 f) {
return dm_evalInQ(dm_current_mandatory(), f);
}
static public A dm_evalInQ(IF0 f) {
return dm_evalInQ(dm_current_mandatory(), if0ToF0(f));
}
static public A dm_evalInQ(DynModule module, F0 f) {
return evalInQ(module.q(), f);
}
static public F0 if0ToF0(IF0 f) {
return f == null ? null : new F0 () {
public A get() {
try {
return f.get();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret f.get();";
}
};
}
static public void addToContainer(Container a, Component... b) {
if (a == null)
return;
{
swing(new Runnable() {
public void run() {
try {
for (Component c : unnull(b)) if (c != null)
a.add(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "for (Component c : unnull(b))\r\n if (c != null) \r\n a.add(c);";
}
});
}
}
static public void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
if (type == int.class && value instanceof Long)
value = ((Long) value).intValue();
if (type == LinkedHashMap.class && value instanceof Map) {
f.set(o, asLinkedHashMap((Map) value));
return;
}
try {
if (f.getType() == Concept.Ref.class) {
f.set(o, ((Concept) o).new Ref((Concept) value));
return;
}
if (o instanceof Concept.Ref) {
f.set(o, ((Concept.Ref) o).get());
return;
}
} catch (Throwable _e) {
}
throw e;
}
}
static public A evalInQ(Q q, final F0 f) {
if (isInQ(q))
return callF(f);
final Var> var = new Var();
q.add(new Runnable() {
public void run() {
try {
try {
var.set(eitherA(callF(f)));
} catch (Throwable e) {
var.set(eitherB(e));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "try {\r\n var.set(eitherA(callF(f)));\r\n } catch (Throwable e) {\r\n ...";
}
});
return returnOrThrow_either(waitForVarToBeNotNull(var));
}
static public LinkedHashMap asLinkedHashMap(Map map) {
if (map instanceof LinkedHashMap)
return (LinkedHashMap) map;
LinkedHashMap m = new LinkedHashMap();
if (map != null)
synchronized (collectionMutex(map)) {
m.putAll(map);
}
return m;
}
static public boolean isInQ(Q q) {
return q != null && isCurrentThread(q.rst.thread);
}
static public Either eitherA(A a) {
return new Either(1, a);
}
static public Either eitherB(B b) {
return new Either(2, b);
}
static public A returnOrThrow_either(Either e) {
if (isEitherB(e))
throw rethrow(e.b());
return eitherAOpt(e);
}
static public A waitForVarToBeNotNull(Var v) {
try {
synchronized (v) {
while (!v.has()) v.wait();
return v.get();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isCurrentThread(Thread t) {
return t != null && t == currentThread();
}
static public boolean isEitherB(Either e) {
return eitherIsB(e);
}
static public A eitherAOpt(Either e) {
return e != null && e.isA() ? e.a() : null;
}
static public boolean eitherIsB(Either e) {
return e != null && e.isB();
}
static public class Either {
public byte which;
public Object value;
public Either() {
}
public Either(int which, Object value) {
this.which = (byte) which;
this.value = value;
}
public boolean isA() {
return which == 1;
}
public boolean isB() {
return which == 2;
}
public A a() {
if (which != 1)
_failMe();
return (A) value;
}
public B b() {
if (which != 2)
_failMe();
return (B) value;
}
public A aOpt() {
return which != 1 ? null : (A) value;
}
public B bOpt() {
return which != 2 ? null : (B) value;
}
public void _failMe() {
throw fail("Either object is of wrong type: " + shortClassName(value));
}
public String toString() {
return "Either" + (isA() ? "A" : "B") + "(" + value + ")";
}
}
static public String b(Object contents, Object... params) {
return tag("b", contents, params);
}
static public boolean isA(Either e) {
return eitherIsA(e);
}
static public String tag(String tag) {
return htag(tag);
}
static public String tag(String tag, Object contents, Object... params) {
return htag(tag, str(contents), params);
}
static public String tag(String tag, StringBuilder contents, Object... params) {
return htag(tag, contents, params);
}
static public String tag(String tag, StringBuffer contents, Object... params) {
return htag(tag, contents, params);
}
static public boolean eitherIsA(Either e) {
return e != null && e.isA();
}
static public String htag(String tag) {
return htag(tag, "");
}
static public String htag(String tag, Object contents, Object... params) {
String openingTag = hopeningTag(tag, params);
String s = str(contents);
if (empty(s) && neqic(tag, "script"))
return dropLast(openingTag) + "/>";
return openingTag + s + "" + tag + ">";
}
static public String hopeningTag(String tag, Map params) {
return hopeningTag(tag, mapToParams(params));
}
static public String hopeningTag(String tag, Object... params) {
StringBuilder buf = new StringBuilder();
buf.append("<" + tag);
params = unrollParams(params);
for (int i = 0; i < l(params); i += 2) {
String name = (String) get(params, i);
Object val = get(params, i + 1);
if (nempty(name) && val != null) {
if (val == html_valueLessParam())
buf.append(" " + name);
else {
String s = str(val);
if (!empty(s))
buf.append(" " + name + "=" + htmlQuote(s));
}
}
}
buf.append(">");
return str(buf);
}
static public boolean neqic(String a, String b) {
return !eqic(a, b);
}
static public boolean neqic(char a, char b) {
return !eqic(a, b);
}
static public Object[] mapToParams(Map map) {
return mapToObjectArray(map);
}
static public Object[] unrollParams(Object[] params) {
if (l(params) == 1 && params[0] instanceof Map)
return mapToParams((Map) params[0]);
return params;
}
static public Object html_valueLessParam_cache;
static public Object html_valueLessParam() {
if (html_valueLessParam_cache == null)
html_valueLessParam_cache = html_valueLessParam_load();
return html_valueLessParam_cache;
}
static public Object html_valueLessParam_load() {
return new Object();
}
static public String htmlQuote(String s) {
return "\"" + htmlencode_forParams(s) + "\"";
}
static public Object[] mapToObjectArray(Map map) {
List l = new ArrayList();
for (Object o : keys(map)) {
l.add(o);
l.add(map.get(o));
}
return toObjectArray(l);
}
static public Object[] mapToObjectArray(Object f, Collection l) {
int n = l(l);
Object[] array = new Object[n];
if (n != 0) {
Iterator it = iterator(l);
for (int i = 0; i < n; i++) array[i] = callF(f, it.next());
}
return array;
}
static public Object[] mapToObjectArray(Object f, Object[] l) {
int n = l(l);
Object[] array = new Object[n];
for (int i = 0; i < n; i++) array[i] = callF(f, l[i]);
return array;
}
static public Object[] mapToObjectArray(Collection l, IF1 f) {
return mapToObjectArray(f, l);
}
static public Object[] mapToObjectArray(A[] l, IF1 f) {
return mapToObjectArray(f, l);
}
static public ThreadLocal htmlencode_forParams_useV2 = new ThreadLocal();
static public String htmlencode_forParams(String s) {
if (s == null)
return "";
if (isTrue(htmlencode_forParams_useV2.get()))
return htmlencode_forParams_v2(s);
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>') {
out.append("");
out.append((int) c);
out.append(';');
} else
out.append(c);
}
return out.toString();
}
static public Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keys(Object map) {
return keys((Map) map);
}
static public Set keys(MultiSet ms) {
return ms.keySet();
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public String htmlencode_forParams_v2(String s) {
if (s == null)
return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
out.append("");
out.append((int) c);
out.append(';');
} else
out.append(c);
}
return out.toString();
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
}