> 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 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 boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
static public String theAGIBlueDomain() {
return "agi.blue";
}
static public File programDir_mine;
static public File programDir() {
return programDir(getProgramID());
}
static public File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
if (me) {
String c = caseID();
if (nempty(c))
dir = newFile(dir, c);
}
return dir;
}
static public File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
static public AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
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) {
printStackTrace2(e3);
}
}
static public List concatLists(Collection ... lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
static public List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
static public boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static public boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
static public boolean containsNewLines(String s) {
return containsNewLine(s);
}
static public String jlabel_textAsHTML_center(String text) {
return "" + replace(htmlencode(text), "\n", " ") + "
";
}
static public 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 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 regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static public String addPrefixIfNotEmpty(String prefix, String s) {
return empty(s) ? "" : prefix + s;
}
static public IterableIterator toLines(File f) {
return linesFromFile(f);
}
static public List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
static public int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static public List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public String n2(long l) {
return formatWithThousands(l);
}
static public String n2(Collection l) {
return n2(l(l));
}
static public String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
static public String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static public String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
static public String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static public String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static public String n2(Map m, String singular) {
return n2(l(m), singular);
}
static public String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
static public String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static public List collect(Iterable c, String field) {
return collectField(c, field);
}
static public List collect(String field, Iterable c) {
return collectField(c, field);
}
static public void sleepInCleanUp(long ms) {
try {
if (ms < 0)
return;
Thread.sleep(ms);
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 String asString(Object o) {
return o == null ? null : o.toString();
}
static public File javaxSecretDir_dir;
static public File javaxSecretDir() {
return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
}
static public File javaxSecretDir(String sub) {
return newFile(javaxSecretDir(), sub);
}
static public String mL_raw(String name) {
return mechList_raw(name);
}
static public A assertNempty(A a) {
return assertNempty("empty", a);
}
static public A assertNempty(String msg, A a) {
if (empty(a))
throw fail(msg + ": " + a);
return a;
}
static public List jsonTok(String s) {
List tok = new ArrayList();
int l = l(s);
int i = 0;
while (i < l) {
int j = i;
char c;
String cc;
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j + 2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isLetter(c))
do ++j; while (j < l && Character.isLetter(s.charAt(j)));
else if (Character.isDigit(c))
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
return tok;
}
static public String unquote(String s) {
if (s == null)
return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i + 1, s.length() - i - 1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
StringBuilder sb = new StringBuilder(l - 1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\'':
ch = '\'';
break;
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s;
}
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 double parseDouble(String s) {
return Double.parseDouble(s);
}
static public Map classForName_cache = synchroHashMap();
static public Class classForName(String name) {
try {
if (classForName_cache == null)
return Class.forName(name);
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = Class.forName(name));
return c;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static public Object nuObjectWithoutArguments(String className) {
try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObjectWithoutArguments(Class c) {
try {
if (nuObjectWithoutArguments_cache == null)
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
static public Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static public Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static public Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static public List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static public boolean emptyString(String s) {
return s == null || s.length() == 0;
}
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 boolean headless() {
return isHeadless();
}
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 boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b))
return false;
return parseSnippetID(a) == parseSnippetID(b);
}
static volatile public String caseID_caseID;
static public String caseID() {
return caseID_caseID;
}
static public void caseID(String id) {
caseID_caseID = id;
}
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 boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static public boolean containsNewLine(String s) {
return contains(s, '\n');
}
static public List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++) if (eq(l.get(i), a))
l.set(i, b);
return l;
}
static public List replace(A a, A b, List l) {
return replace(l, a, b);
}
static public String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static public String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
static public String htmlencode(Object o) {
return htmlencode(str(o));
}
static public String htmlencode(String s) {
if (s == null)
return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
int cp = s.codePointAt(i);
out.append("");
out.append(intToHex_flexLength(cp));
out.append(';');
i += Character.charCount(cp) - 1;
} else
out.append(c);
}
return out.toString();
}
static public String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
static public String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public CloseableIterableIterator linesFromFile(File f) {
try {
if (!f.exists())
return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
return linesFromReader(utf8bufferedReader(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public CloseableIterableIterator linesFromFile(String path) {
return linesFromFile(newFile(path));
}
static public String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
static public double fraction(double d) {
return d % 1;
}
static public String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
static public String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
static public String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
static public String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
static public String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
static public List collectField(Iterable c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
static public List collectField(String field, Iterable c) {
return collectField(c, field);
}
static public 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 ExpiringMap2 mechList_raw_cache = new ExpiringMap2(10000).setMap(ciMap());
static public Lock mechList_raw_lock = lock();
static public int mechList_raw_timeout = 60000;
static public String mechList_raw(String name) {
try {
Lock __0 = mechList_raw_lock;
lock(__0);
try {
if (empty(name))
return "";
String src = mechList_raw_cache.get(name);
if (src != null)
return src;
src = mechList_raw_fresh(name);
if (src != null)
mechList_raw_cache.put(name, src);
return src;
} finally {
unlock(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public VF2 mechList_raw_listener = new VF2() {
public void get(String msg, Object arg) {
try {
if (eq(msg, "mechChange") && arg instanceof String) {
mechList_raw_cache.remove((String) arg);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(msg, 'mechChange) && arg instanceof S) {\r\n //print(\"Got change noti...";
}
};
static public void _onLoad_mechList_raw() {
add(vm_busListeners_live(), mechList_raw_listener);
}
static public void cleanMeUp_mechList_raw() {
remove(vm_busListeners_live(), mechList_raw_listener);
}
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 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 A popLast(List l) {
return liftLast(l);
}
static public List popLast(int n, List l) {
return liftLast(n, l);
}
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(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 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 String intToHex_flexLength(int i) {
return Integer.toHexString(i);
}
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 CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
public Object next() {
throw fail();
}
public boolean hasNext() {
return false;
}
};
static public CloseableIterableIterator emptyCloseableIterableIterator() {
return emptyCloseableIterableIterator_instance;
}
static public CloseableIterableIterator linesFromReader(Reader r) {
final BufferedReader br = bufferedReader(r);
return iteratorFromFunction_f0_autoCloseable(new F0() {
public String get() {
try {
return readLineFromReaderWithClose(br);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret readLineFromReaderWithClose(br);";
}
}, _wrapIOCloseable(r));
}
static public BufferedReader utf8bufferedReader(InputStream in) {
try {
return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public BufferedReader utf8bufferedReader(File f) {
try {
return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
static public GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
static public String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
static public Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
static public TreeMap ciMap() {
return caseInsensitiveMap();
}
static public String mechList_raw_fresh(String name) {
return mechList_opt_raw_fresh(name);
}
static public void add(BitSet bs, int i) {
bs.set(i);
}
static public boolean add(Collection c, A a) {
return c != null && c.add(a);
}
static public void add(Container c, Component x) {
addToContainer(c, x);
}
static public void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
static public void remove(Collection l, A a) {
if (l != null)
l.remove(a);
}
static public char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s) - 1);
}
static public String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[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 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 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 String className(Object o) {
return getClassName(o);
}
static public boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
static public BufferedReader bufferedReader(Reader r) {
return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
}
static public CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) {
class IFF2 extends CloseableIterableIterator {
public A a;
public boolean done = false;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
return _a;
}
public void getNext() {
if (done || a != null)
return;
a = f.get();
done = a == null;
}
public void close() throws Exception {
if (closeable != null)
closeable.close();
}
}
;
return new IFF2();
}
static public String readLineFromReaderWithClose(BufferedReader r) {
try {
String s = r.readLine();
if (s == null)
r.close();
return s;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
return c == null ? null : new AutoCloseable() {
public String toString() {
return "c.close();\r\n _registerIO(c, null, false);";
}
public void close() throws Exception {
c.close();
_registerIO(c, null, false);
}
};
}
static public A _registerIOWrap(A wrapper, Object wrapped) {
return wrapper;
}
static public int gzInputStream_defaultBufferSize = 65536;
static public GZIPInputStream gzInputStream(File f) {
try {
return gzInputStream(new FileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public GZIPInputStream gzInputStream(File f, int bufferSize) {
try {
return gzInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public GZIPInputStream gzInputStream(InputStream in) {
return gzInputStream(in, gzInputStream_defaultBufferSize);
}
static public GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
try {
return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static public TreeMap caseInsensitiveMap() {
return new TreeMap(caseInsensitiveComparator());
}
static public String mechList_opt_raw_fresh(String name) {
Object readMode = mechMode().readMode;
if (readMode instanceof File) {
String md5Name = uniqueFileNameUsingMD5_80_v2(upper(name));
return loadTextFileFromZipFile((File) readMode, md5Name);
}
boolean useLocal = false, useRemote = true;
if (eq(readMode, "mergeLocalAndRemote"))
useLocal = true;
else if (eq(readMode, "local")) {
useLocal = true;
useRemote = false;
}
String s = "";
if (useRemote) {
if (eq(mechMode().readMode, "localCopies"))
s = unnull(loadTextFile(remoteMechListMirrorFile(name)));
else
s = serverMechList_raw_fresh(name, true);
}
if (useLocal)
s = appendNewLineIfNempty(s) + localMechList_opt_raw_fresh(name);
return s;
}
static public void addToContainer(final Container a, final Component b) {
if (a != null && b != null) {
swing(new Runnable() {
public void run() {
try {
a.add(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.add(b);";
}
});
}
}
static public 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 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 Comparator caseInsensitiveComparator() {
return betterCIComparator();
}
static public MechMode mechMode_value = new MechMode();
static public MechMode mechMode() {
return mechMode_value;
}
static public String uniqueFileNameUsingMD5_80_v2(String fullName) {
return uniqueFileNameUsingMD5_80_v2(fullName, md5(fullName));
}
static public String uniqueFileNameUsingMD5_80_v2(String fullName, String md5) {
return takeFirst(80 - 33, fileNameEncode(fullName)) + " - " + md5;
}
static public String upper(String s) {
return s == null ? null : s.toUpperCase();
}
static public char upper(char c) {
return Character.toUpperCase(c);
}
static public String loadTextFileFromZipFile(File inZip, String fileName) {
try {
if (!fileExists(inZip))
return null;
try {
ZipFile zip = new ZipFile(inZip);
try {
return loadTextFileFromZipFile(zip, fileName);
} finally {
_close(zip);
}
} catch (Throwable e) {
throw fail(f2s(inZip), e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadTextFileFromZipFile(ZipFile zip, String fileName) {
try {
ZipEntry entry = zip.getEntry(fileName);
if (entry == null)
return null;
InputStream fin = zip.getInputStream(entry);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copyStream(fin, baos);
return fromUTF8(baos.toByteArray());
} finally {
_close(fin);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File remoteMechListMirrorFile(String listName) {
return newFile(remoteMechListMirrorsDir(), uniqueFileNameUsingMD5_80_v2(upper(listName)));
}
static public boolean serverMechList_raw_fresh_verbose = false;
static public String serverMechList_raw_fresh(String name) {
return serverMechList_raw_fresh(name, false);
}
static public String serverMechList_raw_fresh(String name, boolean opt) {
Lock __0 = downloadLock();
lock(__0);
try {
String text = null;
try {
text = loadTextFile(remoteMechListMirrorFile(name));
} catch (Throwable __e) {
_handleException(__e);
}
Object[] params = muricaCredentialsPlus("md5", md5OrNull(text), "l", l(text), "opt", opt ? 1 : 0, "withStatus", 1);
String url = "http://butter.botcompany.de:8080/mech/raw/list-text/" + urlencode(name);
String page = postPageSilently(url, params);
Map map = jsonDecodeMap(page);
boolean same = eq(map.get("Same"), true);
boolean appended = eq(map.get("Appended"), true);
saveTextFile(remoteMechListMirrorMetaFile(name), struct(getMultipleKeys(map, "Name", "Status")));
if (!same) {
if (appended)
text += (String) map.get("Text");
else
text = (String) map.get("Text");
saveTextFile(remoteMechListMirrorFile(name), text);
File nameFile = remoteMechListMirrorNameFile(name);
if (!fileExists(nameFile)) {
String actualName = or((String) map.get("Name"), name);
saveTextFile(nameFile, actualName);
}
}
if (serverMechList_raw_fresh_verbose)
print("Mech list " + name + ": " + (appended ? "appended" : same ? "same" : "downloaded") + ": " + n2(countLines(text), "line"));
if (!same)
vmBus_send("remoteMechListMirrorChanged", name);
return text;
} finally {
unlock(__0);
}
}
static public String appendNewLineIfNempty(String s) {
return empty(s) ? "" : s + "\n";
}
static public String localMechList_opt_raw_fresh(String name) {
return unnull(loadTextFile(localMechListFile(name)));
}
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 betterCIComparator_C betterCIComparator_instance;
static public betterCIComparator_C betterCIComparator() {
if (betterCIComparator_instance == null)
betterCIComparator_instance = new betterCIComparator_C();
return betterCIComparator_instance;
}
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 String md5(String text) {
try {
if (text == null)
return "-";
return bytesToHex(md5_impl(toUtf8(text)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String md5(byte[] data) {
if (data == null)
return "-";
return bytesToHex(md5_impl(data));
}
static public byte[] md5_impl(byte[] data) {
try {
return MessageDigest.getInstance("MD5").digest(data);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String md5(File file) {
return md5OfFile(file);
}
static public List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
static public List takeFirst(int n, List l) {
return takeFirst(l, n);
}
static public String takeFirst(int n, String s) {
return substring(s, 0, n);
}
static public String takeFirst(String s, int n) {
return substring(s, 0, n);
}
static public List takeFirst(int n, Iterable i) {
if (i == null)
return null;
List l = new ArrayList();
Iterator it = i.iterator();
for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
static public String fileNameEncode_safeChars = " ()[]#,!";
static public String fileNameEncode(String s) {
StringBuilder buf = new StringBuilder();
int n = l(s);
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (contains(fileNameEncode_safeChars, c))
buf.append(c);
else
buf.append(urlencode(str(c)));
}
return str(buf);
}
static public boolean fileExists(String path) {
return path != null && new File(path).exists();
}
static public boolean fileExists(File f) {
return f != null && f.exists();
}
static public String fromUTF8(byte[] bytes) {
return fromUtf8(bytes);
}
static public File remoteMechListMirrorsDir() {
return javaxDataDir("Remote Mech Lists");
}
static public Lock downloadLock_lock = fairLock();
static public Lock downloadLock() {
return downloadLock_lock;
}
static public Object[] muricaCredentialsPlus(Object... params) {
return concatArrays(muricaCredentials(), params);
}
static public String md5OrNull(String s) {
return s == null ? null : md5(s);
}
static public String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
static public String postPageSilently(String url, Object... params) {
return doPostSilently(litmap(params), url);
}
static public File remoteMechListMirrorMetaFile(String listName) {
return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".meta");
}
static public Map getMultipleKeys(Map map, A... keys) {
Map map2 = similarEmptyMap(map);
if (map != null)
for (A key : keys) map2.put(key, map.get(key));
return map2;
}
static public File remoteMechListMirrorNameFile(String listName) {
return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".name");
}
static public File localMechListFile(String listName) {
return newFile(localMechListsDir(), uniqueFileNameUsingMD5_80_v2(listName) + ".text");
}
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len * 2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs + i]);
stringBuilder.append(s.substring(s.length() - 2, s.length()));
}
return stringBuilder.toString();
}
static public byte[] toUtf8(String s) {
try {
return s.getBytes("UTF-8");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean md5OfFile_verbose = false;
static public String md5OfFile(String path) {
return md5OfFile(newFile(path));
}
static public String md5OfFile(File f) {
try {
if (!f.exists())
return "-";
if (md5OfFile_verbose)
print("Getting MD5 of " + f);
MessageDigest md5 = MessageDigest.getInstance("MD5");
FileInputStream in = new FileInputStream(f);
try {
byte[] buf = new byte[65536];
int l;
while (true) {
l = in.read(buf);
if (l <= 0)
break;
md5.update(buf, 0, l);
}
return bytesToHex(md5.digest());
} finally {
_close(in);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
static public List newSubListOrSame(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = max(0, startIndex);
endIndex = min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return cloneList(l.subList(startIndex, endIndex));
}
static public String fromUtf8(byte[] bytes) {
try {
return bytes == null ? null : new String(bytes, "UTF-8");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object[] concatArrays(Object[]... arrays) {
int l = 0;
for (Object[] a : arrays) l += l(a);
Object[] x = new Object[l];
int i = 0;
for (Object[] a : arrays) if (a != null) {
System.arraycopy(a, 0, x, i, l(a));
i += l(a);
}
return x;
}
static public Object[] muricaCredentials() {
String pass = muricaPassword();
return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0];
}
static public String doPostSilently(Map urlParameters, String url) {
return doPostSilently(makePostData(urlParameters), url);
}
static public String doPostSilently(String urlParameters, String url) {
doPost_silently.set(true);
return doPost(urlParameters, url);
}
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 Map similarEmptyMap(Map m) {
if (m instanceof TreeMap)
return new TreeMap(((TreeMap) m).comparator());
if (m instanceof LinkedHashMap)
return new LinkedHashMap();
return new HashMap();
}
static public File localMechListsDir() {
return javaxDataDir("Mech Lists");
}
static volatile public boolean muricaPassword_pretendNotAuthed = false;
static public String muricaPassword() {
if (muricaPassword_pretendNotAuthed)
return null;
return trim(loadTextFile(muricaPasswordFile()));
}
static public String makePostData(Map map) {
StringBuilder buf = new StringBuilder();
for (Map.Entry e : map.entrySet()) {
String key = (String) (e.getKey());
Object val = e.getValue();
if (val != null) {
String value = str(val);
if (nempty(buf))
buf.append("&");
buf.append(urlencode(key)).append("=").append(urlencode((value)));
}
}
return str(buf);
}
static public String makePostData(Object... params) {
StringBuilder buf = new StringBuilder();
int n = l(params);
for (int i = 0; i + 1 < n; i += 2) {
String key = (String) (params[i]);
Object val = params[i + 1];
if (val != null) {
String value = str(val);
if (nempty(buf))
buf.append("&");
buf.append(urlencode(key)).append("=").append(urlencode((value)));
}
}
return str(buf);
}
static public ThreadLocal doPost_silently = new ThreadLocal();
static public ThreadLocal doPost_timeout = new ThreadLocal();
static public ThreadLocal> doPost_extraHeaders = new ThreadLocal();
static public String doPost(Map urlParameters, String url) {
return doPost(makePostData(urlParameters), url);
}
static public String doPost(String urlParameters, String url) {
try {
URL _url = new URL(url);
ping();
return doPost(urlParameters, _url.openConnection(), _url);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String doPost(String urlParameters, URLConnection conn, URL url) {
try {
boolean silently = isTrue(optParam(doPost_silently));
Long timeout = optParam(doPost_timeout);
Map extraHeaders = optPar(doPost_extraHeaders);
setHeaders(conn);
for (String key : keys(extraHeaders)) {
conn.setRequestProperty(key, extraHeaders.get(key));
}
int l = lUtf8(urlParameters);
if (!silently)
print("Sending POST request: " + hideCredentials(url) + " (" + l + " bytes)");
if (timeout != null)
setURLConnectionTimeouts(conn, timeout);
((HttpURLConnection) conn).setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", str(l));
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
writer.write(urlParameters);
writer.flush();
String contents = loadPage_utf8(conn, url, false);
writer.close();
return contents;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File muricaPasswordFile() {
return new File(javaxSecretDir(), "murica/muricaPasswordFile");
}
static public A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static public A optParam(ThreadLocal tl) {
return optPar(tl);
}
static public Object optParam(String name, Map params) {
return mapGet(params, name);
}
static public A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt)))
throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
return (A) opt[i + 1];
return defaultValue;
}
static public Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
static public Object optParam(String name, Object[] params) {
return optParam(params, name);
}
static public A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
static public A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
static public Object optPar(Object[] params, String name) {
return optParam(params, name);
}
static public Object optPar(String name, Object[] params) {
return optParam(params, name);
}
static public Object optPar(String name, Map params) {
return optParam(name, params);
}
static public A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public void setHeaders(URLConnection con) throws IOException {
String computerID = getComputerID_quick();
if (computerID != null)
try {
con.setRequestProperty("X-ComputerID", computerID);
con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
} catch (Throwable e) {
}
}
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 int lUtf8(String s) {
return l(utf8(s));
}
static public URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) {
con.setConnectTimeout(toInt(timeout));
con.setReadTimeout(toInt(timeout));
if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
print("Warning: Timeouts not set by JDK.");
return con;
}
static public B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
static public B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
static public boolean even(int i) {
return (i & 1) == 0;
}
static public boolean even(long i) {
return (i & 1) == 0;
}
static public String getComputerID_quick() {
return computerID();
}
static public byte[] utf8(String s) {
return toUtf8(s);
}
static public String _computerID;
static public Lock computerID_lock = lock();
public static String computerID() {
if (_computerID == null) {
Lock __0 = computerID_lock;
lock(__0);
try {
if (_computerID != null)
return _computerID;
File file = computerIDFile();
_computerID = loadTextFile(file.getPath());
if (_computerID == null) {
_computerID = loadTextFile(userDir(".tinybrain/computer-id"));
if (_computerID == null)
_computerID = makeRandomID(12, new SecureRandom());
saveTextFile(file, _computerID);
}
} finally {
unlock(__0);
}
}
return _computerID;
}
static public File computerIDFile() {
return javaxDataDir("Basic Info/computer-id.txt");
}
static public String makeRandomID(int length) {
return makeRandomID(length, defaultRandomGenerator());
}
static public String makeRandomID(int length, Random random) {
char[] id = new char[length];
for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
static public String makeRandomID(Random r, int length) {
return makeRandomID(length, r);
}
static public Random defaultRandomGenerator() {
return ThreadLocalRandom.current();
}
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 (!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 IF0 {
public A get();
}
static abstract public class CloseableIterableIterator extends IterableIterator implements AutoCloseable {
public void close() throws Exception {
}
}
static public class ExpiringMap2 extends AbstractMap {
public Map > byKey = new HashMap();
public PriorityBlockingQueue> queue = new PriorityBlockingQueue();
public long standardExpiryTime;
public boolean renewOnOverwrite = true, renewOnGet;
public Object onChange;
public ExpiringMap2() {
}
public ExpiringMap2(long standardExpiryTime) {
this.standardExpiryTime = standardExpiryTime;
}
public ExpiringMap2(long standardExpiryTime, Object onChange) {
this.onChange = onChange;
this.standardExpiryTime = standardExpiryTime;
}
synchronized public boolean clean() {
boolean changes = false;
Pair p;
while ((p = queue.peek()) != null && sysTime() >= p.a) {
p = queue.poll();
Pair v = byKey.get(p.b);
if (v != null) {
byKey.remove(p.b);
changes = true;
change();
}
}
return changes;
}
public void change() {
callF(onChange);
}
synchronized public B put(A a, B b) {
clean();
long timeout = sysTime() + standardExpiryTime;
Pair p = byKey.get(a);
if (p != null && renewOnOverwrite)
queue.remove(new Pair(p.a, a));
byKey.put(a, pair(timeout, b));
change();
if (p == null || renewOnOverwrite)
queue.add(new Pair(timeout, a));
return pairB(p);
}
synchronized public B remove(Object a) {
clean();
Pair p = byKey.get(a);
if (p == null)
return null;
queue.remove(new Pair(p.a, a));
byKey.remove(a);
change();
return p.b;
}
synchronized public B get(Object a) {
clean();
Pair p = byKey.get(a);
if (renewOnGet && p != null) {
queue.remove(new Pair(p.a, a));
long timeout = sysTime() + standardExpiryTime;
byKey.put((A) a, pair(timeout, p.b));
queue.add(new Pair(timeout, a));
}
return pairB(p);
}
synchronized public Set> entrySet() {
clean();
return synchronizedSet(mapValues("pairB", byKey).entrySet());
}
synchronized public Set keySet() {
clean();
return synchronizedSet(byKey.keySet());
}
synchronized public int size() {
clean();
return byKey.size();
}
public void setStandardExpiryTime(long ms) {
standardExpiryTime = ms;
}
synchronized public ExpiringMap2 setMap(Map innerMap) {
byKey = innerMap;
return this;
}
}
static abstract public class VF2 {
abstract public void 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 public class WAVDecoder implements AutoCloseable {
public EndianDataInputStream in;
public int channels;
public float sampleRate;
public boolean ignoreSampleRate = true;
public boolean twentyFourBit = false;
public int specifiedDataLength;
public int remainingDataBytes;
static public int defaultBufferSize = 128 * 1024;
public WAVDecoder(InputStream stream) {
try {
in = new EndianDataInputStream(new BufferedInputStream(stream, defaultBufferSize));
if (!in.read4ByteString().equals("RIFF"))
throw new IllegalArgumentException("not a wav");
in.readIntLittleEndian();
if (!in.read4ByteString().equals("WAVE"))
throw new IllegalArgumentException("expected WAVE tag");
String s = in.read4ByteString();
if (eq(s, "bext")) {
in.skip(in.readIntLittleEndian());
s = in.read4ByteString();
}
if (!s.equals("fmt "))
throw new IllegalArgumentException("expected fmt tag, got: " + s);
if (in.readIntLittleEndian() != 16)
throw new IllegalArgumentException("expected wave chunk size to be 16");
int format;
if ((format = in.readShortLittleEndian()) != 1)
throw new IllegalArgumentException("expected format to be 1, got: " + format);
channels = in.readShortLittleEndian();
sampleRate = in.readIntLittleEndian();
if (sampleRate != 44100)
if (ignoreSampleRate) {
} else
throw fail("Not 44100 sampling rate: " + sampleRate);
in.readIntLittleEndian();
in.readShortLittleEndian();
int fmt = in.readShortLittleEndian();
if (fmt == 24)
twentyFourBit = true;
else if (fmt != 16)
throw fail("Only 16/24-bit samples supported: " + fmt);
String tag;
while (!(tag = in.read4ByteString()).equals("data")) {
int len = in.readIntLittleEndian();
in.skip(len);
}
remainingDataBytes = specifiedDataLength = in.readIntLittleEndian();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public int readMonoSamples(short[] samples) {
int readSamples = 0, n = samples.length;
for (int i = 0; i < n && remainingDataBytes > 0; i++) {
double sample = 0;
try {
for (int j = 0; j < channels; j++) sample += readSample();
sample /= channels;
samples[i] = (short) iround(max(-32768, min(32767, sample)));
readSamples++;
} catch (Exception ex) {
break;
}
}
return readSamples;
}
public int readStereoSamples(short[] samples) {
int readSamples = 0, n = samples.length;
for (int i = 0; i < n && remainingDataBytes > 0; i += 2) {
double sample = 0;
try {
short left = readSample();
short right;
if (channels > 1)
right = readSample();
else
right = left;
samples[i] = left;
samples[i + 1] = right;
readSamples += 2;
} catch (Exception ex) {
break;
}
}
return readSamples;
}
public short readSample() {
try {
if (twentyFourBit) {
--remainingDataBytes;
in.read();
}
remainingDataBytes -= 2;
return in.readShortLittleEndian();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void close() {
try {
in.close();
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static abstract public class IterableIterator implements Iterator , Iterable {
public Iterator iterator() {
return this;
}
public void remove() {
unsupportedOperation();
}
}
abstract static public class DynPrintLogAndEnabled extends DynPrintLog {
volatile public boolean enabled = true;
transient public JPanel buttons;
public JComponent visualize() {
return dm_visualizeWithEnabled(super.visualize());
}
public JComponent visualizeWithoutEnabled() {
return super.visualize();
}
public JComponent dm_visualizeWithEnabled(JComponent main) {
return centerAndSouthWithMargins(main, buttons = jrightalignedline(dm_fieldCheckBox("enabled")));
}
public void setEnabled(boolean b) {
setField("enabled", b);
}
}
static public class MechMode implements IFieldsToList {
public Object readMode;
public Object writeMode;
public MechMode() {
}
public MechMode(Object readMode, Object writeMode) {
this.writeMode = writeMode;
this.readMode = readMode;
}
public String toString() {
return shortClassName(this) + "(" + readMode + ", " + writeMode + ")";
}
public boolean equals(Object o) {
if (!(o instanceof MechMode))
return false;
MechMode x = (MechMode) o;
return eq(readMode, x.readMode) && eq(writeMode, x.writeMode);
}
public int hashCode() {
int h = -866263200;
h = boostHashCombine(h, _hashCode(readMode));
h = boostHashCombine(h, _hashCode(writeMode));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { readMode, writeMode };
}
}
static public interface IFieldsToList {
public Object[] _fieldsToList();
}
static public class EndianDataInputStream extends DataInputStream {
public EndianDataInputStream(InputStream in) {
super(in);
}
public String read4ByteString() {
try {
byte[] bytes = new byte[4];
readFully(bytes);
return new String(bytes, "US-ASCII");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public short readShortLittleEndian() {
try {
int result = readUnsignedByte();
result |= readUnsignedByte() << 8;
return (short) result;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public int readIntLittleEndian() {
try {
int result = readUnsignedByte();
result |= readUnsignedByte() << 8;
result |= readUnsignedByte() << 16;
result |= readUnsignedByte() << 24;
return result;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public int readInt24BitLittleEndian() {
try {
int result = readUnsignedByte();
result |= readUnsignedByte() << 8;
result |= readUnsignedByte() << 16;
if ((result & (1 << 23)) == 8388608)
result |= 0xff000000;
return result;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public int readInt24Bit() {
try {
int result = readUnsignedByte() << 16;
result |= readUnsignedByte() << 8;
result |= readUnsignedByte();
return result;
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static public interface IVar {
public void set(A a);
public A get();
default public boolean has() {
return get() != null;
}
default public void clear() {
set(null);
}
}
static public class Pair implements Comparable> {
public A a;
public B b;
public Pair() {
}
public Pair(A a, B b) {
this.b = b;
this.a = a;
}
public int hashCode() {
return hashCodeFor(a) + 2 * hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Pair))
return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
public String toString() {
return "<" + a + ", " + b + ">";
}
public int compareTo(Pair p) {
if (p == null)
return 1;
int i = ((Comparable ) a).compareTo(p.a);
if (i != 0)
return i;
return ((Comparable) b).compareTo(p.b);
}
}
static public B pairB(Pair p) {
return p == null ? null : p.b;
}
static public boolean reflection_isForbiddenMethod(Method m) {
return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}
static public void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static public Set allInterfacesImplementedBy(Class c) {
if (c == null)
return null;
HashSet set = new HashSet();
allInterfacesImplementedBy_find(c, set);
return set;
}
static public void allInterfacesImplementedBy_find(Class c, Set set) {
if (c.isInterface() && !set.add(c))
return;
do {
for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set);
} while ((c = c.getSuperclass()) != null);
}
static public Method findMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args);
}
static public boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static public boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static public Method findStaticMethod(Class c, String method, Object... args) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (!m.getName().equals(method))
continue;
if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static public boolean findStaticMethod_checkArgs(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length)
return false;
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i])))
return false;
return true;
}
static public long sysTime() {
return sysNow();
}
static public void change() {
callOpt(getOptMC("mainConcepts"), "allChanged");
}
static public void put(Map map, A a, B b) {
if (map != null)
map.put(a, b);
}
static public void put(List l, int i, A a) {
if (l != null && i >= 0 && i < l(l))
l.set(i, a);
}
static public Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
static public Map mapValues(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map)) m.put(key, callF(func, map.get(key)));
return m;
}
static public Map mapValues(Map map, IF1 f) {
return mapValues(f, map);
}
static public Map mapValues(Map map, Object func) {
return mapValues(func, map);
}
static public Set keySet(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keySet(Object map) {
return keys((Map) map);
}
static public Set keySet(MultiSet ms) {
return ms.keySet();
}
static public UnsupportedOperationException unsupportedOperation() {
throw new UnsupportedOperationException();
}
static public String shortClassName(Object o) {
if (o == null)
return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
static public int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
static public int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static public byte[] readFully(InputStream in) {
return streamToBytes(in);
}
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 int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
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 Object getOptMC(String field) {
return getOpt(mc(), field);
}
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 byte[] streamToBytes(InputStream in) {
try {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copyStream(in, baos);
return baos.toByteArray();
} finally {
in.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] streamToBytes(InputStream in, int expectedSize) {
try {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(expectedSize);
copyStream(in, baos);
return baos.toByteArray();
} finally {
in.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 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 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 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 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 __1 = 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(__1);
}
} finally {
unlock(__0);
}
}
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[] 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 boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static public JCheckBox jCheckBox() {
return swingNu(JCheckBox.class);
}
static public JCheckBox jCheckBox(boolean checked) {
return swingNu(JCheckBox.class, "", checked);
}
static public JCheckBox jCheckBox(String text, boolean checked) {
return swingNu(JCheckBox.class, text, checked);
}
static public JCheckBox jCheckBox(String text) {
return swingNu(JCheckBox.class, text);
}
static public JCheckBox jCheckBox(String text, boolean checked, final Object onChange) {
JCheckBox cb = jCheckBox(checked, onChange);
cb.setText(text);
return cb;
}
static public JCheckBox jCheckBox(boolean checked, final Object onChange) {
final JCheckBox cb = jCheckBox(checked);
cb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(onChange, cb.isSelected());
}
});
return cb;
}
static public A bindCheckBoxToLiveValue(final A cb, final SimpleLiveValue lv) {
bindLiveValueListenerToComponent(cb, lv, new Runnable() {
public void run() {
try {
setChecked(cb, isTrue(lv.get()));
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se...";
}
});
onChange(cb, new Runnable() {
public void run() {
try {
lv.set(isChecked(cb));
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se...";
}
});
return cb;
}
static public Class getFieldType(Object o, String field) {
return fieldType(o, field);
}
static public void dm_watchField(String field, Runnable onChange) {
new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange);
}
static public 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(final JCheckBox checkBox, final 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 A onChange(A spinner, Object r) {
{
swing(new Runnable() {
public void run() {
try {
spinner.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "spinner.addChangeListener(changeListener(r));";
}
});
}
return spinner;
}
static public A onChange(A b, Object r) {
{
swing(new Runnable() {
public void run() {
try {
b.addItemListener(itemListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "b.addItemListener(itemListener(r));";
}
});
}
return b;
}
static public void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
static public A onChange(A slider, final Object r) {
{
swing(new Runnable() {
public void run() {
try {
slider.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "slider.addChangeListener(changeListener(r));";
}
});
}
return slider;
}
static public JComboBox onChange(Object r, JComboBox cb) {
return onChange(cb, r);
}
static public JComboBox onChange(JComboBox cb, final Object r) {
if (isEditableComboBox(cb))
onChange(textFieldFromComboBox(cb), r);
else
onSelectedItem(cb, new VF1() {
public void get(String s) {
try {
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r)";
}
});
return cb;
}
static public boolean isChecked(final JCheckBox checkBox) {
return checkBox != null && (boolean) swing(new F0() {
public Boolean get() {
try {
return checkBox.isSelected();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret checkBox.isSelected();";
}
});
}
static public boolean isChecked(final JCheckBoxMenuItem mi) {
return mi != null && (boolean) swing(new F0() {
public Boolean get() {
try {
return mi.isSelected();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret mi.isSelected();";
}
});
}
static public boolean isAllUpperCase(String s) {
return hasLettersAllUpperCase(s);
}
static public boolean isUpperCaseLetter(char c) {
return Character.isUpperCase(c);
}
static public ChangeListener changeListener(final Object r) {
return new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(r);
}
};
}
static public ItemListener itemListener(final Object r) {
return new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pcallF(r);
}
};
}
static public void onUpdate(JComponent c, final Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
call(r);
}
public void removeUpdate(DocumentEvent e) {
call(r);
}
public void changedUpdate(DocumentEvent e) {
call(r);
}
});
else if (c instanceof ItemSelectable)
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
call(r);
}
});
else
print("Warning: onUpdate doesn't know " + getClassName(c));
}
static public void onUpdate(List extends JComponent> l, Object r) {
for (JComponent c : l) onUpdate(c, r);
}
static public boolean isEditableComboBox(final JComboBox cb) {
return cb != null && swing(new F0() {
public Boolean get() {
try {
return cb.isEditable();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret cb.isEditable();";
}
});
}
static public JTextField textFieldFromComboBox(JComboBox cb) {
return (JTextField) cb.getEditor().getEditorComponent();
}
static public JComboBox onSelectedItem(final JComboBox cb, final VF1 f) {
addActionListener(cb, new Runnable() {
public void run() {
try {
pcallF(f, selectedItem(cb));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcallF(f, selectedItem(cb))";
}
});
return cb;
}
static public boolean hasLettersAllUpperCase(String s) {
return hasLetters(s) && !containsLowerCase(s);
}
static public void addActionListener(JTextField tf, final Runnable action) {
onEnter(tf, action);
}
static public void addActionListener(final JComboBox cb, final Runnable action) {
if (cb != null) {
swing(new Runnable() {
public void run() {
try {
cb.addActionListener(actionListener(action));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.addActionListener(actionListener(action));";
}
});
}
}
static public void addActionListener(final AbstractButton b, final Runnable action) {
if (b != null) {
swing(new Runnable() {
public void run() {
try {
b.addActionListener(actionListener(action));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "b.addActionListener(actionListener(action));";
}
});
}
}
static public String selectedItem(JList l) {
return getSelectedItem(l);
}
static public String selectedItem(JComboBox cb) {
return getSelectedItem(cb);
}
static public boolean hasLetters(String s) {
for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i)))
return true;
return false;
}
static public boolean containsLowerCase(String s) {
for (int i = 0; i < l(s); i++) if (isLowerCase(s.charAt(i)))
return true;
return false;
}
static public 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 String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
static public String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
static public boolean isLowerCase(char c) {
return Character.isLowerCase(c);
}
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 String strOrNull(Object o) {
return o == null ? null : str(o);
}
static public class SimpleLiveValue extends LiveValue {
public Class type;
volatile public A value;
transient public List onChange = synchroList();
public SimpleLiveValue(Class type) {
this.type = type;
}
public SimpleLiveValue(Class type, A value) {
this.value = value;
this.type = type;
}
public Class getType() {
return type;
}
public A get() {
return value;
}
public void onChange(Runnable l) {
onChange.add(l);
}
public void onChangeAndNow(Runnable l) {
onChange(l);
callF(l);
}
public void removeOnChangeListener(Runnable l) {
onChange.remove(l);
}
public void fireChanged() {
pcallFAll(onChange);
}
public void set(A a) {
if (neq(value, a)) {
value = a;
fireChanged();
}
}
}
static public interface IF2 {
public C get(A a, B b);
}
static abstract public class LiveValue {
abstract public Class getType();
abstract public A get();
abstract public void onChange(Runnable l);
abstract public void removeOnChangeListener(Runnable l);
public void onChangeAndNow(Runnable l) {
onChange(l);
callF(l);
}
}
static public class Dyn_FieldWatcher {
public DynModule module;
public String field;
public Object value;
public Runnable action;
public Dyn_FieldWatcher(DynModule module, String field, Runnable action) {
this.action = action;
this.field = field;
this.module = module;
value = 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 = get(module, field);
if (eq(value, newValue))
return;
value = newValue;
dm_q(module, action);
}
}
static public class RightAlignedLine extends JPanel {
public RightAlignedLine(Component... components) {
setLayout(LetterLayout.rightAlignedRow());
for (Component component : components) add(component);
}
public void add(String text) {
add(new JLabel(text));
}
}
static public class LetterLayout implements LayoutManager {
public String[] lines;
public Map map = new TreeMap();
public RC[] rows;
public RC[] cols;
public Cell[][] cells;
public int spacingX = 10, spacingY = 10;
public int insetTop, insetBottom, insetLeft, insetRight;
public int template;
public boolean formWideLeftSide, formWideRightSide;
static final public int STALACTITE = 1, LEFT_ALIGNED_ROW = 2, CENTERED_ROW = 3, FORM = 4, RIGHT_ALIGNED_ROW = 5;
public boolean debug = false;
public void setLeftBorder(int border) {
insetLeft = border;
}
public void setRightBorder(int border) {
insetRight = border;
}
public static JComponent withBorder(JComponent component, int border) {
JPanel panel = new JPanel(new LetterLayout("C").setBorder(border));
panel.add("C", component);
return panel;
}
public static JPanel panel(String... lines) {
return new JPanel(new LetterLayout(lines));
}
public static JPanel stalactitePanel() {
return new JPanel(stalactite());
}
static public class DummyComponent extends JComponent {
}
static public class Cell {
public boolean aux = false;
public int minWidth, minHeight;
public Component component;
public int colspan, rowspan;
public double weightX, weightY;
}
static public class RC {
public int min;
public double weightSum;
public int start;
public int minEnd;
}
public LetterLayout(int template) {
this.template = template;
}
public LetterLayout(String... lines) {
this.lines = lines;
}
public void removeLayoutComponent(Component component) {
map.values().remove(component);
}
public void layoutContainer(Container container) {
prepareLayout(container);
if (debug)
System.out.println("Container size: " + container.getSize());
Insets insets = getInsets(container);
for (int r = 0; r < rows.length; r++) {
for (int i = 0; i < cols.length; ) {
Cell cell = cells[i][r];
if (cell.aux)
++i;
else {
if (cell.component != null) {
int x1 = cols[i].start;
int y1 = rows[r].start;
int x2 = i + cell.colspan < cols.length ? cols[i + cell.colspan].start - spacingX : container.getWidth() - insets.right;
int y2 = r + cell.rowspan < rows.length ? rows[r + cell.rowspan].start - spacingY : container.getHeight() - insets.bottom;
if (debug)
System.out.println("Layouting (" + i + ", " + r + ", " + cell.component.getClass().getName() + "): " + x1 + " " + y1 + " " + x2 + " " + y2);
cell.component.setBounds(x1, y1, x2 - x1, y2 - y1);
}
i += cells[i][r].colspan;
}
}
}
}
final public void prepareLayout(Container container) {
applyTemplate(container);
int numRows = lines.length, numCols = lines[0].length();
for (int i = 1; i < numRows; i++) if (lines[i].length() != numCols)
throw new IllegalArgumentException("Lines have varying length");
cells = new Cell[numCols][numRows];
rows = new RC[numRows];
cols = new RC[numCols];
for (int r = 0; r < numRows; r++) rows[r] = new RC();
for (int i = 0; i < numCols; i++) cols[i] = new RC();
for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r] = new Cell();
for (int r = 0; r < numRows; r++) {
String line = lines[r];
for (int i = 0; i < numCols; ) {
Cell cell = cells[i][r];
if (cell.aux) {
++i;
continue;
}
char ch = line.charAt(i);
int iNext = i;
do ++iNext; while (iNext < numCols && ch == line.charAt(iNext));
int rNext = r;
do ++rNext; while (rNext < numRows && ch == lines[rNext].charAt(i));
cell.weightX = numCols == 1 || iNext > i + 1 ? 1.0 : 0.0;
cell.weightY = numRows == 1 || rNext > r + 1 ? 1.0 : 0.0;
Component c = map.get(String.valueOf(ch));
cell.component = c;
if (c != null) {
cell.minWidth = c.getMinimumSize().width + spacingX;
cell.minHeight = getMinimumHeight(c) + spacingY;
}
cell.colspan = iNext - i;
cell.rowspan = rNext - r;
if (cell.colspan == 1)
cols[i].min = Math.max(cols[i].min, cell.minWidth);
if (cell.rowspan == 1)
rows[r].min = Math.max(rows[r].min, cell.minHeight);
for (int r2 = r; r2 < rNext; r2++) for (int i2 = i; i2 < iNext; i2++) if (r2 != r || i2 != i)
cells[i2][r2].aux = true;
i = iNext;
}
}
while (true) {
for (int i = 0; i < numCols; i++) {
int minStart = i == 0 ? 0 : cols[i - 1].minEnd;
double weightStart = i == 0 ? 0.0 : cols[i - 1].weightSum;
for (int r = 0; r < numRows; r++) {
Cell cell = cells[i][r];
if (!cell.aux) {
RC rc = cols[i + cell.colspan - 1];
rc.minEnd = Math.max(rc.minEnd, minStart + cell.minWidth);
rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightX);
}
}
}
for (int r = 0; r < numRows; r++) {
int minStart = r == 0 ? 0 : rows[r - 1].minEnd;
double weightStart = r == 0 ? 0.0 : rows[r - 1].weightSum;
for (int i = 0; i < numCols; i++) {
Cell cell = cells[i][r];
if (!cell.aux) {
RC rc = rows[r + cell.rowspan - 1];
rc.minEnd = Math.max(rc.minEnd, minStart + cell.minHeight);
rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightY);
}
}
}
if (allWeightsZero(cols)) {
for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightX = 1.0;
continue;
}
if (allWeightsZero(rows)) {
for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightY = 1.0;
continue;
}
break;
}
Insets insets = getInsets(container);
determineStarts(cols, insets.left, container.getWidth() - insets.left - insets.right + spacingX, spacingX);
determineStarts(rows, insets.top, container.getHeight() - insets.top - insets.bottom + spacingY, spacingY);
}
final public boolean allWeightsZero(RC[] rcs) {
for (int i = 0; i < rcs.length; i++) if (rcs[i].weightSum != 0.0)
return false;
return true;
}
static public int getMinimumHeight(Component c) {
return c.getMinimumSize().height;
}
final public void applyTemplate(Container container) {
if (template == STALACTITE) {
Component[] components = container.getComponents();
lines = new String[components.length + 2];
map.clear();
for (int i = 0; i < components.length; i++) {
String s = String.valueOf(makeIndexChar(i));
map.put(s, components[i]);
lines[i] = s;
}
lines[components.length] = lines[components.length + 1] = " ";
} else if (template == FORM) {
Component[] components = container.getComponents();
int numRows = components.length / 2;
lines = new String[numRows + 2];
map.clear();
for (int row = 0; row < numRows; row++) {
String lower = String.valueOf(makeIndexChar(row));
String upper = String.valueOf(makeAlternateIndexChar(row));
Component rightComponent = components[row * 2 + 1];
if (rightComponent instanceof DummyComponent)
upper = lower;
lines[row] = (formWideLeftSide ? lower + lower : lower) + (formWideRightSide ? upper + upper : upper);
map.put(lower, components[row * 2]);
if (!(rightComponent instanceof DummyComponent))
map.put(upper, rightComponent);
}
lines[numRows] = lines[numRows + 1] = (formWideLeftSide ? " " : " ") + (formWideRightSide ? " " : " ");
} else if (template == LEFT_ALIGNED_ROW) {
lines = new String[] { makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
} else if (template == CENTERED_ROW) {
lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
} else if (template == RIGHT_ALIGNED_ROW) {
lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) };
}
}
final public String makeSingleRow(Container container) {
Component[] components = container.getComponents();
StringBuffer buf = new StringBuffer();
map.clear();
for (int i = 0; i < components.length; i++) {
String s = String.valueOf(makeAlternateIndexChar(i));
map.put(s, components[i]);
buf.append(s);
}
return buf.toString();
}
static public void determineStarts(RC[] rcs, int start, int totalSize, int spacing) {
int minTotal = rcs[rcs.length - 1].minEnd;
double weightSum = rcs[rcs.length - 1].weightSum;
int spare = (int) ((totalSize - minTotal) / (weightSum == 0.0 ? 1.0 : weightSum));
int x = start, minSum = 0;
double prevWeightSum = 0.0;
for (int i = 0; i < rcs.length; i++) {
int width = rcs[i].minEnd - minSum + (int) ((rcs[i].weightSum - prevWeightSum) * spare) - spacing;
rcs[i].start = x;
x += width + spacing;
prevWeightSum = rcs[i].weightSum;
minSum = rcs[i].minEnd;
}
}
public void addLayoutComponent(String s, Component component) {
map.put(s, component);
}
public Dimension minimumLayoutSize(Container container) {
prepareLayout(container);
Insets insets = getInsets(container);
Dimension result = new Dimension(insets.left + cols[cols.length - 1].minEnd + insets.right - spacingX, insets.top + rows[rows.length - 1].minEnd + insets.bottom - spacingY);
return result;
}
final public Insets getInsets(Container container) {
Insets insets = container.getInsets();
return new Insets(insets.top + insetTop, insets.left + insetLeft, insets.bottom + insetBottom, insets.right + insetRight);
}
public Dimension preferredLayoutSize(Container container) {
return minimumLayoutSize(container);
}
public LetterLayout setSpacing(int x, int y) {
spacingX = x;
spacingY = y;
return this;
}
public LetterLayout setSpacing(int spacing) {
return setSpacing(spacing, spacing);
}
public LetterLayout setBorder(int top, int left, int bottom, int right) {
insetTop = top;
insetLeft = left;
insetBottom = bottom;
insetRight = right;
return this;
}
public LetterLayout setBorder(int inset) {
return setBorder(inset, inset, inset, inset);
}
public LetterLayout setTopBorder(int inset) {
insetTop = inset;
return this;
}
public static LetterLayout stalactite() {
return new LetterLayout(STALACTITE);
}
public static LetterLayout leftAlignedRow() {
return new LetterLayout(LEFT_ALIGNED_ROW);
}
public static LetterLayout leftAlignedRow(int spacing) {
return leftAlignedRow().setSpacing(spacing);
}
public static LetterLayout centeredRow() {
return new LetterLayout(CENTERED_ROW);
}
public static LetterLayout rightAlignedRow() {
return new LetterLayout(RIGHT_ALIGNED_ROW);
}
public static JPanel rightAlignedRowPanel(JComponent... components) {
return makePanel(new LetterLayout(RIGHT_ALIGNED_ROW), components);
}
static public JPanel makePanel(LetterLayout letterLayout, JComponent[] components) {
JPanel panel = new JPanel(letterLayout);
for (JComponent component : components) {
panel.add(component);
}
return panel;
}
public static LetterLayout form() {
LetterLayout letterLayout = new LetterLayout(FORM);
letterLayout.formWideLeftSide = true;
letterLayout.formWideRightSide = true;
return letterLayout;
}
public static LetterLayout formWideRightSide() {
LetterLayout letterLayout = new LetterLayout(FORM);
letterLayout.formWideRightSide = true;
return letterLayout;
}
public static Component getDummyComponent() {
return new DummyComponent();
}
public static JPanel newPanel(String... lines) {
return new JPanel(new LetterLayout(lines));
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public static char makeIndexChar(int idx) {
return (char) ('a' + idx * 2);
}
public static char makeAlternateIndexChar(int idx) {
return (char) ('b' + idx * 2);
}
public static char LEFT_CHAR = ',', RIGHT_CHAR = '.';
public static void main(String[] args) {
System.out.println((int) makeIndexChar(0));
System.out.println((int) makeAlternateIndexChar(0));
System.out.println((int) makeIndexChar(32000));
System.out.println((int) makeAlternateIndexChar(32000));
System.out.println((int) LEFT_CHAR);
System.out.println((int) RIGHT_CHAR);
}
}
static public Q dm_q() {
return dm_current_mandatory().q();
}
static public void dm_q(Runnable r) {
dm_inQ(r);
}
static public void dm_q(DynModule module, Runnable r) {
module.q().add(r);
}
static public void dm_inQ(Runnable r) {
dm_q().add(r);
}
}