vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
static public Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public 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 ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static public boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static public boolean containsNewLines(String s) {
return containsNewLine(s);
}
static public String jlabel_textAsHTML_center(String text) {
return "" + replace(htmlencode2(text), "\n", " ") + "
";
}
static public Object call_withVarargs(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(methodName, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(methodName);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + methodName + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(methodName);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + methodName + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 int iteratorCount_int_close(Iterator i) {
try {
int n = 0;
if (i != null)
while (i.hasNext()) {
i.next();
++n;
}
if (i instanceof AutoCloseable)
((AutoCloseable) i).close();
return n;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public CharSequence subCharSequence(CharSequence s, int x) {
return subCharSequence(s, x, s == null ? 0 : s.length());
}
static public CharSequence subCharSequence(CharSequence s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.subSequence(x, y);
}
static public int min(int a, int b) {
return Math.min(a, b);
}
static public long min(long a, long b) {
return Math.min(a, b);
}
static public float min(float a, float b) {
return Math.min(a, b);
}
static public float min(float a, float b, float c) {
return min(min(a, b), c);
}
static public double min(double a, double b) {
return Math.min(a, b);
}
static public double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static public float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static public byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
static public short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
static public int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
static public JTextArea showWrappedText(final String title, final String text) {
return (JTextArea) swingAndWait(new F0() {
public Object get() {
try {
JTextArea textArea = wrappedTextArea(text);
caretToHome(textArea);
textArea.setFont(typeWriterFont());
makeFrame(title, new JScrollPane(textArea));
return textArea;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JTextArea textArea = wrappedTextArea(text);\r\n caretToHome(textArea);\r\n ...";
}
});
}
static public JTextArea showWrappedText(Object text) {
return showWrappedText(autoFrameTitle(), str(text));
}
static public String stackTraceToString(StackTraceElement[] st) {
return lines(st);
}
static public String stackTraceToString(Throwable e) {
return getStackTrace_noRecord(e);
}
static public ThreadLocal> holdInstance_l = new ThreadLocal();
static public AutoCloseable holdInstance(Object o) {
if (o == null)
return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
static public AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null)
return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
static public Map classForName_cache = synchroHashMap();
static public Class classForName(String name) {
return classForName(name, null);
}
static public Class classForName(String name, Object classFinder) {
if (classForName_cache == null || classFinder != null)
return classForName_uncached(name, classFinder);
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = classForName_uncached(name, null));
return c;
}
static public Class classForName_uncached(String name, Object classFinder) {
try {
if (classFinder != null)
return (Class) callF(classFinder, name);
return Class.forName(name);
} 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 : getDeclaredConstructors_cached(c)) if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
static public Map getDeclaredConstructors_cached_cache = newDangerousWeakHashMap();
static public Constructor[] getDeclaredConstructors_cached(Class c) {
Constructor[] ctors;
synchronized (getDeclaredConstructors_cached_cache) {
ctors = getDeclaredConstructors_cached_cache.get(c);
if (ctors == null) {
getDeclaredConstructors_cached_cache.put(c, ctors = c.getDeclaredConstructors());
for (var ctor : ctors) makeAccessible(ctor);
}
}
return ctors;
}
static public List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static public boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class)
return arg instanceof Boolean;
if (type == int.class)
return arg instanceof Integer;
if (type == long.class)
return arg instanceof Long;
if (type == float.class)
return arg instanceof Float;
if (type == short.class)
return arg instanceof Short;
if (type == char.class)
return arg instanceof Character;
if (type == byte.class)
return arg instanceof Byte;
if (type == double.class)
return arg instanceof Double;
return type.isInstance(arg);
}
static public void setMeta(IMeta o, Object key, Object value) {
metaMapPut(o, key, value);
}
static public void setMeta(Object o, Object key, Object value) {
metaMapPut(o, key, value);
}
static public void assertSame(Object a, Object b) {
assertSame("", a, b);
}
static public void assertSame(String msg, Object a, Object b) {
if (a != b)
throw fail(joinNemptiesWithColon(msg, a + " != " + b + " (" + identityHash(a) + "/" + identityHash(b) + ")"));
}
static public void assertSame(IF0 msg, Object a, Object b) {
if (a != b)
throw fail(joinNemptiesWithColon(msg.get(), a + " != " + b + " (" + identityHash(a) + "/" + identityHash(b) + ")"));
}
static public String className(Object o) {
return getClassName(o);
}
static public Object metaGet(IMeta o, Object key) {
return metaMapGet(o, key);
}
static public Object metaGet(Object o, Object key) {
return metaMapGet(o, key);
}
static public Object metaGet(String key, IMeta o) {
return metaMapGet(o, key);
}
static public Object metaGet(String key, Object o) {
return metaMapGet(o, key);
}
static public boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
static public boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static public Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() {
public void run() {
try {
_inheritThreadInfo(info);
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_inheritThreadInfo(info); callF(r);";
}
};
}
static public JPanel jpanel(LayoutManager layout, Object... components) {
return jpanel(layout, asList(components));
}
static public JPanel jpanel(LayoutManager layout, List components) {
return smartAdd(jpanel(layout), components);
}
static public JPanel jpanel(LayoutManager layout) {
return swing(() -> new JPanel(layout));
}
static public JPanel jpanel() {
return swing(() -> new JPanel());
}
static public boolean newButton_autoToolTip = true;
static public JButton newButton(final String text, final Object action) {
return swing(new F0() {
public JButton get() {
try {
String text2 = dropPrefix("[disabled] ", text);
JButton btn = basicJButton(text2);
if (l(text2) < l(text))
btn.setEnabled(false);
if (newButton_autoToolTip) {
btn.setToolTipText(btn.getText());
}
if (action != null)
btn.addActionListener(actionListener(action, btn));
return btn;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S text2 = dropPrefix(\"[disabled] \", text);\r\n JButton btn = basicJButton(te...";
}
});
}
static public A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static public String getType(Object o) {
return getClassName(o);
}
static public long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static public long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static public String charToString(char c) {
return String.valueOf(c);
}
static public String charToString(int c) {
return String.valueOf((char) c);
}
static public boolean isMenuSeparatorIndicator(Object o) {
return eqOneOf(o, "***", "---", "===", "");
}
static public boolean isRunnableX(Object o) {
if (o == null)
return false;
if (o instanceof String)
return hasMethod(mc(), (String) o);
return o instanceof Runnable || hasMethod(o, "get");
}
static public A bindLiveValueListenerToComponent(A component, IHasChangeListeners lv, Runnable listener) {
return bindHasChangeListenersToComponent(component, lv, listener);
}
static public boolean isCurlyBracketed(String s) {
return isCurlyBraced(s);
}
static public A setEnabled(A c, boolean enable) {
if (c != null) {
swing(() -> {
c.setEnabled(enable);
});
}
return c;
}
static public A setEnabled(boolean enable, A c) {
return setEnabled(c, enable);
}
static public void setEnabled(boolean enable, JComponent... l) {
for (var c : unnullForIteration(l)) setEnabled(c, enable);
}
static public String unCurlyBracket(String s) {
return tok_unCurlyBracket(s);
}
static public Map mapMinus(Map map, Object... keys) {
if (empty(keys))
return map;
Map m2 = cloneMap(map);
for (Object key : keys) m2.remove(key);
return m2;
}
static public HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
static public boolean isInstanceOf(Object o, Class type) {
return type.isInstance(o);
}
static public int preferredWidth(Component c) {
return c == null ? 0 : getPreferredSize(c).width;
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public Object dm_current_generic() {
return getWeakRef(dm_current_generic_tl().get());
}
static public Object rcall(String method, Object o, Object... args) {
return call_withVarargs(o, method, args);
}
static public Runnable _topLevelErrorHandling(Runnable r) {
if (r == null)
return null;
Object info = _threadInfo();
Object mod = dm_current_generic();
Runnable r2 = r;
if (info != null || mod == null)
r2 = new Runnable() {
public void run() {
try {
AutoCloseable __1 = (AutoCloseable) (rcall("enter", mod));
try {
_threadInheritInfo(info);
r.run();
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp (AutoCloseable) rcall enter(mod);\r\n _threadInheritInfo(info);\r\n ...";
}
};
r2 = rPcall(r2);
return r2;
}
static public Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static public Map vm_generalWeakSubMap(Object name) {
synchronized (vm_generalMap()) {
Map map = (Map) (vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = newWeakMap());
return map;
}
}
static public WeakReference weakRef(A a) {
return newWeakReference(a);
}
static public String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static public Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
static public List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
static public Map vm_generalMap_map;
static public Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static public B mapPutOrRemove(Map map, A key, B value) {
if (map != null && key != null)
if (value != null)
return map.put(key, value);
else
return map.remove(key);
return null;
}
static public A firstWithClassShortNamed(String shortName, Iterable l) {
if (l != null)
for (A o : l) if (eq(shortClassName(o), shortName))
return o;
return null;
}
static public A firstWithClassShortNamed(String shortName, A[] l) {
if (l != null)
for (A o : l) if (eq(shortClassName(o), shortName))
return o;
return null;
}
static public JInternalFrame getInternalFrame(final Object _o) {
return _o == null ? null : swing(new F0() {
public JInternalFrame get() {
try {
Object o = _o;
if (o instanceof ButtonGroup)
o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component))
return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JInternalFrame)
return (JInternalFrame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button...";
}
});
}
static public AutoCloseable tempSetThreadLocalIfNecessary(ThreadLocal tl, A a) {
if (tl == null)
return null;
A prev = tl.get();
if (eq(prev, a))
return null;
tl.set(a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
static public AutoCloseable tempSetThreadLocalIfNecessary(BetterThreadLocal tl, A a) {
if (tl == null)
return null;
A prev = tl.get();
if (eq(prev, a))
return null;
tl.set(a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
static public JMenuItem jMenuItem(final String text) {
return jmenuItem(text);
}
static public JMenuItem jMenuItem(String text, Object r) {
return jmenuItem(text, r);
}
static public Pair jmenu_autoMnemonic(String s) {
int i = indexOf(s, '&');
if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i + 1)))
return pair(substring(s, 0, i) + substring(s, i + 1), (int) s.charAt(i + 1));
return pair(s, 0);
}
static public String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
if (m != null)
m.m = new String[] { substring(a, strL(b)) };
return true;
}
static public boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static public JMenuItem disableMenuItem(final JMenuItem mi) {
if (mi != null) {
swing(() -> {
mi.setEnabled(false);
});
}
return mi;
}
static public ActionListener actionListenerInNewThread(final Object runnable) {
return actionListenerInNewThread(runnable, null);
}
static public ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
startThread("Action Listener", new Runnable() {
public void run() {
try {
AutoCloseable __1 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __1 = holdInstance(instanceToHold); try {\r\n callF(runnable...";
}
});
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
static public ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
static public ActionListener actionListener(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
final Object info = _threadInfo();
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
_threadInheritInfo(info);
AutoCloseable __1 = holdInstance(instanceToHold);
try {
pcallF(runnable);
} finally {
_close(__1);
}
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
static public JMenuItem directJMenuItem(Action a) {
return new JMenuItem(a) {
public Dimension getMaximumSize() {
return new Dimension(super.getPreferredSize().width, super.getMaximumSize().height);
}
};
}
static public JMenuItem directJMenuItem(String text, Object action) {
return directJMenuItem(abstractAction(text, action));
}
static public JMenuBar addMenuBar(final Component c) {
return swing(new F0() {
public JMenuBar get() {
try {
RootPaneContainer f = getPossiblyInternalFrame(c);
if (f == null)
return null;
JMenuBar bar = (JMenuBar) (call(f, "getJMenuBar"));
if (bar == null) {
setMenuBar(f, bar = new JMenuBar());
revalidate((Component) f);
}
return bar;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "RootPaneContainer f = getPossiblyInternalFrame(c);\r\n if (f == null) null;\r...";
}
});
}
static public A revalidate(final A c) {
if (c == null || !c.isShowing())
return c;
{
swing(() -> {
c.revalidate();
c.repaint();
});
}
return c;
}
static public void revalidate(JFrame f) {
revalidate((Component) f);
}
static public void revalidate(JInternalFrame f) {
revalidate((Component) f);
}
static public A bindToComponent(A component, Runnable onShow, Runnable onUnShow) {
{
swing(() -> {
final Var flag = new Var<>(false);
component.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
if (flag.get())
print("Warning: bindToComponent logic failure");
flag.set(true);
pcallF(onShow);
}
public void ancestorRemoved(AncestorEvent event) {
if (!flag.get())
print("Warning: bindToComponent logic failure");
flag.set(false);
pcallF(onUnShow);
}
public void ancestorMoved(AncestorEvent event) {
}
});
if (component.isShowing()) {
flag.set(true);
pcallF(onShow);
}
});
}
return component;
}
static public A bindToComponent(A component, Runnable onShow) {
return bindToComponent(component, onShow, null);
}
static public A bindToComponent(A component, IF0 onShow, IVF1 onUnShow) {
Var b = new Var();
return bindToComponent(component, () -> b.set(onShow.get()), () -> {
try {
onUnShow.get(b.get());
} finally {
b.set(null);
}
});
}
static public void setCaretPosition(final JTextComponent c, final int pos) {
if (c != null) {
swing(() -> {
try {
int _pos = max(0, min(l(c.getText()), pos));
c.setCaretPosition(_pos);
} catch (Throwable __e) {
printStackTrace(__e);
}
});
}
}
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, Runnable r) {
onUpdate(c, (Object) r);
}
static public void onUpdate(JTextComponent c, IVF1 r) {
if (c == null || r == null)
return;
c.getDocument().addDocumentListener(runnableToDocumentListener(() -> r.get(c.getText())));
}
static public void onUpdate(JComponent c, Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(runnableToDocumentListener(toRunnable(r)));
else if (c instanceof ItemSelectable)
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pcallF(r);
}
});
else if (c instanceof JSpinner)
onChange(((JSpinner) c), 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 void addActionListener(JTextField tf, final Runnable action) {
onEnter(tf, action);
}
static public void addActionListener(final JComboBox cb, final Runnable action) {
if (cb != null) {
swing(() -> {
cb.addActionListener(actionListener(action));
});
}
}
static public void addActionListener(final AbstractButton b, final Runnable action) {
if (b != null) {
swing(() -> {
b.addActionListener(actionListener(action));
});
}
}
static public A getSelectedItem_typed(JList l) {
return swing(() -> l.getSelectedValue());
}
static public A getSelectedItem_typed(JComboBox cb) {
return swing(() -> (A) cb.getSelectedItem());
}
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 "return 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 JComboBox onSelectedItem(final JComboBox cb, IVF1 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 ArrayList emptyList() {
return new ArrayList();
}
static public ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
static public ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static public ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
static public ArrayList emptyList(Class c) {
return new ArrayList();
}
static public int[] emptyIntArray_a = new int[0];
static public int[] emptyIntArray() {
return emptyIntArray_a;
}
static public char[] emptyCharArray = new char[0];
static public char[] emptyCharArray() {
return emptyCharArray;
}
static public double[] emptyDoubleArray = new double[0];
static public double[] emptyDoubleArray() {
return emptyDoubleArray;
}
static public Map emptyMap() {
return new HashMap();
}
static public Object[] emptyObjectArray_a = new Object[0];
static public Object[] emptyObjectArray() {
return emptyObjectArray_a;
}
static public Symbol emptySymbol_value;
static public Symbol emptySymbol() {
if (emptySymbol_value == null)
emptySymbol_value = symbol("");
return emptySymbol_value;
}
static public Set vm_generalWeakSet(Object name) {
synchronized (vm_generalMap()) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = newWeakHashSet());
return set;
}
}
static public AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(long[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(double[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static public ArrayList asList(short[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (short i : a) l.add(i);
return l;
}
static public ArrayList asList(Iterator it) {
ArrayList l = new ArrayList();
if (it != null)
while (it.hasNext()) l.add(it.next());
return l;
}
static public ArrayList asList(IterableIterator s) {
return asList((Iterator) s);
}
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(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null)
while ((a = p.next()) != null) 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 ArrayList asList(ReverseChain c) {
return c == null ? emptyList() : c.toList();
}
static public List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static public int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(int a, int b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(long a, long b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(Object a, Object b) {
if (a == null)
return b == null ? 0 : -1;
if (b == null)
return 1;
return ((Comparable) a).compareTo(b);
}
static public Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static public double parseDouble(String s) {
return empty(s) ? 0.0 : Double.parseDouble(s);
}
static public boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x))
return true;
return false;
}
static public boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m))
return true;
return false;
}
static public boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static public String hostNameFromURL(String url) {
try {
return empty(url) ? null : new URL(url).getHost();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void logQuotedWithTime(String s) {
logQuotedWithTime(standardLogFile(), s);
}
static public void logQuotedWithTime(File logFile, String s) {
logQuoted(logFile, logQuotedWithTime_format(s));
}
static public void logQuotedWithTime(String logFile, String s) {
logQuoted(logFile, logQuotedWithTime_format(s));
}
static public String logQuotedWithTime_format(String s) {
return (now()) + " " + s;
}
static public File javaxDataDir_dir;
static public File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static public File javaxDataDir(String... subs) {
return newFile(javaxDataDir(), subs);
}
static public int isAndroid_flag;
static public boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static public JTextArea wrappedTextArea(final JTextArea ta) {
enableWordWrapForTextArea(ta);
return ta;
}
static public JTextArea wrappedTextArea() {
return wrappedTextArea(jtextarea());
}
static public JTextArea wrappedTextArea(String text) {
JTextArea ta = wrappedTextArea();
setText(ta, text);
return ta;
}
static public A onClick(A c, IVF1 runnable) {
return onClick(c, (Object) runnable);
}
static public A onClick(A c, Object runnable) {
if (c != null) {
swing(() -> {
c.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
callF(runnable, e);
}
});
});
}
return c;
}
static public void onClick(JButton btn, Object runnable) {
onEnter(btn, runnable);
}
static public void disposeWindow(final Window window) {
if (window != null) {
swing(() -> {
window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING));
myFrames_list.remove(window);
window.dispose();
});
}
}
static public void disposeWindow(final Component c) {
disposeWindow(getWindow(c));
}
static public void disposeWindow(Object o) {
if (o != null)
disposeWindow(((Component) o));
}
static public void disposeWindow() {
disposeWindow(heldInstance(Component.class));
}
static public Font typeWriterFont() {
return typeWriterFont(iround(14 * getSwingFontScale()));
}
static public Font typeWriterFont(int size) {
return new Font("Courier", Font.PLAIN, size);
}
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 = marginPanel();
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 = marginPanel();\r\n p.setBorder(BorderFactory.createEmptyBorder(to...";
}
});
}
static public Window getWindow(Object o) {
if (!(o instanceof Component))
return null;
return swing(() -> {
Component c = (Component) o;
while (c != null) {
if (c instanceof Window)
return ((Window) c);
c = c.getParent();
}
return null;
});
}
static public Rect preferredScreenBounds() {
return screenBounds_safe(preferredScreen());
}
static public boolean vmBus_anyFalse(String msg, Object... args) {
return contains(vmBus_queryAll(msg, args), false);
}
static public void swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
timer.setRepeats(false);
timer.start();
}
static public void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
static public int toMS_int(double seconds) {
return toInt_checked((long) (seconds * 1000));
}
static public Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
static public Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
static public String baseClassName(String className) {
return substring(className, className.lastIndexOf('.') + 1);
}
static public String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
static public String prependIfNempty(String prefix, String s) {
return empty(s) ? unnull(s) : prefix + s;
}
static final public Map callOpt_cache = newDangerousWeakHashMap();
static public Object callOpt_cached(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null)
return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public _MethodCache callOpt_getCache(Class c) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
static public Object[] massageArgsForVarArgsCall(Executable m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = l(args);
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
int nVarArgs = nArgs - n;
Object varArgs = Array.newInstance(varArgType, nVarArgs);
for (int i = 0; i < nVarArgs; i++) Array.set(varArgs, i, args[n + i]);
newArgs[n] = varArgs;
return newArgs;
}
static public JButton jimageButton(String imageID, Object action) {
JButton btn = jbutton("", action);
btn.setIcon(imageIcon(imageID));
return btn;
}
static public JButton jimageButton(String imageID) {
return jimageButton(imageID, null);
}
static public JButton jimageButton(Image img) {
return jimageButton(img, null, null);
}
static public JButton jimageButton(String imageID, String toolTip, Runnable action) {
return jimageButton(imageIcon(imageID), toolTip, action);
}
static public JButton jimageButton(Image img, String toolTip, Runnable action) {
var btn = jbutton("", action);
setButtonImage(btn, img);
return setToolTip(toolTip, btn);
}
static public JButton jimageButton(ImageIcon img, String toolTip, Runnable action) {
var btn = jbutton("", action);
setButtonImage(btn, img);
return setToolTip(toolTip, btn);
}
static public BufferedImage scaleImageToWidth(BufferedImage img, int newW) {
return resizeImage(img, newW);
}
static public BufferedImage scaleImageToWidth(int newW, BufferedImage img) {
return scaleImageToWidth(img, newW);
}
static public BufferedImage scaleImageToWidth(int newW, String imageID) {
return scaleImageToWidth(newW, loadImage2(imageID));
}
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 void newPing() {
var tl = newPing_actionTL();
Runnable action = tl == null ? null : tl.get();
{
if (action != null)
action.run();
}
}
static public boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null)
return false;
if (o instanceof ThreadLocal)
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static public boolean isTrue(Boolean b) {
return b != null && b.booleanValue();
}
static public void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static public Thread currentThread() {
return Thread.currentThread();
}
static public class getOpt_Map extends WeakHashMap {
public getOpt_Map() {
if (getOpt_special == null)
getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final public Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
static public HashMap getOpt_special;
static public Map getOpt_getFieldMap(Object o) {
Class c = _getClass(o);
HashMap map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
return map;
}
static public Object getOpt_cached(Object o, String field) {
try {
if (o == null)
return null;
Map map = getOpt_getFieldMap(o);
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null)
return f.get(o);
if (o instanceof DynamicObject)
return syncMapGet2(((DynamicObject) o).fieldValues, field);
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
if (!reflection_classesNotToScan().contains(c.getName())) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
makeAccessible(f);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
}
if (getOpt_cache != null)
getOpt_cache.put(c, map);
return map;
}
static public List _registerDangerousWeakMap_preList;
static public A _registerDangerousWeakMap(A map) {
return _registerDangerousWeakMap(map, null);
}
static public A _registerDangerousWeakMap(A map, Object init) {
callF(init, map);
if (init instanceof String) {
final String f = (String) init;
init = new VF1() {
public void get(Map map) {
try {
callMC(f, map);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callMC(f, map)";
}
};
}
if (javax() == null) {
if (_registerDangerousWeakMap_preList == null)
_registerDangerousWeakMap_preList = synchroList();
_registerDangerousWeakMap_preList.add(pair(map, init));
return map;
}
call(javax(), "_registerDangerousWeakMap", map, init);
return map;
}
static public void _onLoad_registerDangerousWeakMap() {
assertNotNull(javax());
if (_registerDangerousWeakMap_preList == null)
return;
for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b);
_registerDangerousWeakMap_preList = null;
}
static public Map synchroMap() {
return synchroHashMap();
}
static public Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static public Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static public String joinWithSpace(Iterable c) {
return join(" ", c);
}
static public String joinWithSpace(Object... c) {
return join(" ", c);
}
static public List classNames(Collection l) {
return getClassNames(l);
}
static public List classNames(Object[] l) {
return getClassNames(asList(l));
}
static public PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(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 Object pcallF_minimalExceptionHandling(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable e) {
System.out.println(getStackTrace(e));
_storeException(e);
}
return null;
}
static public Set vm_generalIdentityHashSet(Object name) {
synchronized (vm_generalMap()) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = syncIdentityHashSet());
return set;
}
}
static public Map vm_generalHashMap(Object name) {
synchronized (vm_generalMap()) {
Map m = (Map) (vm_generalMap_get(name));
if (m == null)
vm_generalMap_put(name, m = syncHashMap());
return m;
}
}
static public boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
int n = s.length();
if (y < x)
y = x;
if (y > n)
y = n;
if (x >= y)
return "";
return s.substring(x, y);
}
static public String substring(String s, IntRange r) {
return r == null ? null : substring(s, r.start, r.end);
}
static public String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static public boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
}
static public boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b))
return false;
if (m != null)
m.m = new String[] { substring(a, 0, l(a) - l(b)) };
return true;
}
static public 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 htmlencode2(String s) {
return htmlencode_noQuotes(s);
}
static public boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(Object... c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
static public String trim(String s) {
return s == null ? null : s.trim();
}
static public String trim(StringBuilder buf) {
return buf.toString().trim();
}
static public String trim(StringBuffer buf) {
return buf.toString().trim();
}
static public void caretToHome(JTextComponent c) {
setCaret(c, 0);
}
static public String makeFrame_defaultIcon;
static public boolean makeFrame_hideConsole = false;
static public ThreadLocal> makeFrame_post = new ThreadLocal();
static public JFrame makeFrame() {
return makeFrame((Component) null);
}
static public JFrame makeFrame(Object content) {
return makeFrame(programTitle(), content);
}
static public JFrame makeFrame(String title) {
return makeFrame(title, null);
}
static public JFrame makeFrame(String title, Object content) {
return makeFrame(title, content, true);
}
static public JFrame makeFrame(final String title, final Object content, final boolean showIt) {
final VF1 post = optParam(makeFrame_post);
return swing(new F0() {
public JFrame get() {
try {
if (getFrame(content) != null)
return getFrame(setFrameTitle((Component) content, title));
final JFrame frame = new JFrame(title);
if (makeFrame_defaultIcon != null)
setFrameIconLater(frame, makeFrame_defaultIcon);
_initFrame(frame);
Component wrapped = wrap(content);
if (wrapped != null)
frame.getContentPane().add(wrapped);
frame.setBounds(defaultNewFrameBounds());
callF(post, frame);
if (showIt)
frame.setVisible(true);
if (showIt && makeFrame_hideConsole) {
hideConsole();
makeFrame_hideConsole = false;
}
return frame;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (getFrame(content) != null)\r\n ret getFrame(setFrameTitle((Component) ...";
}
});
}
static public String autoFrameTitle_value;
static public String autoFrameTitle() {
return autoFrameTitle_value != null ? autoFrameTitle_value : getProgramTitle();
}
static public void autoFrameTitle(Component c) {
setFrameTitle(getFrame(c), autoFrameTitle());
}
static public String lines(Iterable lines) {
return fromLines(lines);
}
static public String lines(Object[] lines) {
return fromLines(asList(lines));
}
static public List lines(String s) {
return toLines(s);
}
static public String lines(Iterable l, IF1 f) {
return mapToLines(l, f);
}
static public Map myFrames_list = weakHashMap();
static public List myFrames() {
return swing(new F0>() {
public List get() {
try {
return keysList(myFrames_list);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return keysList(myFrames_list);";
}
});
}
static public void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null)
tl.set(l = new ArrayList());
l.add(a);
}
static public A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null)
return null;
A a = popLast(l);
if (empty(l))
tl.set(null);
return a;
}
static public A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
static public Map synchroHashMap() {
return 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 classLoaderForObject(realm).loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
static public void metaMapPut(IMeta o, Object key, Object value) {
{
if (o != null)
o.metaPut(key, value);
}
}
static public void metaMapPut(Object o, Object key, Object value) {
var meta = initIMeta(o);
{
if (meta != null)
meta.metaPut(key, value);
}
}
static public String joinNemptiesWithColon(String... strings) {
return joinNempties(": ", strings);
}
static public String joinNemptiesWithColon(Collection strings) {
return joinNempties(": ", strings);
}
static public int identityHash(Object o) {
return identityHashCode(o);
}
static public Object metaMapGet(IMeta o, Object key) {
return o == null ? null : o.metaGet(key);
}
static public Object metaMapGet(Object o, Object key) {
return metaMapGet(toIMeta(o), key);
}
static public List> _threadInfo_makers = synchroList();
static public Object _threadInfo() {
if (empty(_threadInfo_makers))
return null;
HashMap map = new HashMap();
pcallFAll(_threadInfo_makers, map);
return map;
}
static public Runnable asRunnable(Object o) {
return toRunnable(o);
}
static public void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static public JPanel smartAdd(JPanel panel, List parts) {
for (Object o : parts) addToContainer(panel, wrapForSmartAdd(o));
return panel;
}
static public JPanel smartAdd(JPanel panel, Object... parts) {
return smartAdd(panel, asList(parts));
}
static public JButton basicJButton(String text) {
return swing(() -> new JButton(text));
}
static public boolean eqOneOf(Object o, Object... l) {
if (l != null)
for (Object x : l) if (eq(o, x))
return true;
return false;
}
static public boolean hasMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args) != null;
}
static public boolean isCurlyBraced(String s) {
List tok = tok_combineCurlyBrackets_keep(javaTok(s));
return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}");
}
static public String unnullForIteration(String s) {
return s == null ? "" : s;
}
static public Collection unnullForIteration(Collection l) {
return l == null ? immutableEmptyList() : l;
}
static public List unnullForIteration(List l) {
return l == null ? immutableEmptyList() : l;
}
static public int[] unnullForIteration(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnullForIteration(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnullForIteration(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public short[] unnullForIteration(short[] l) {
return l == null ? emptyShortArray() : l;
}
static public Map unnullForIteration(Map l) {
return l == null ? immutableEmptyMap() : l;
}
static public Iterable unnullForIteration(Iterable i) {
return i == null ? immutableEmptyList() : i;
}
static public A[] unnullForIteration(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnullForIteration(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnullForIteration(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnullForIteration(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnullForIteration(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public long unnullForIteration(Long l) {
return l == null ? 0L : l;
}
static public String tok_unCurlyBracket(String s) {
return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
}
static public Map cloneMap(Map map) {
if (map == null)
return new HashMap();
synchronized (map) {
return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
}
}
static public List cloneMap(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : cloneList(l)) x.add(f.get(o));
return x;
}
static public Dimension getPreferredSize(final Component c) {
return c == null ? null : swing(new F0() {
public Dimension get() {
try {
return c.getPreferredSize();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return c.getPreferredSize();";
}
});
}
static public String programID;
static public String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
static public String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static public String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static public A getWeakRef(Reference ref) {
return ref == null ? null : ref.get();
}
static public x30_pkg.x30_util.BetterThreadLocal dm_current_generic_tl;
static public x30_pkg.x30_util.BetterThreadLocal dm_current_generic_tl() {
if (dm_current_generic_tl == null)
dm_current_generic_tl = vm_generalMap_getOrCreate("currentModule", () -> new x30_pkg.x30_util.BetterThreadLocal());
return dm_current_generic_tl;
}
static public List> _threadInheritInfo_retrievers = synchroList();
static public void _threadInheritInfo(Object info) {
if (info == null)
return;
pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
static public Runnable rPcall(Runnable r) {
return r == null ? null : () -> {
try {
r.run();
} catch (Throwable __e) {
printStackTrace(__e);
}
};
}
static public List _registerWeakMap_preList;
static public A _registerWeakMap(A map) {
if (javax() == null) {
if (_registerWeakMap_preList == null)
_registerWeakMap_preList = synchroList();
_registerWeakMap_preList.add(map);
return map;
}
try {
call(javax(), "_registerWeakMap", map);
} catch (Throwable e) {
printException(e);
print("Upgrade JavaX!!");
}
return map;
}
static public void _onLoad_registerWeakMap() {
assertNotNull(javax());
if (_registerWeakMap_preList == null)
return;
for (Object o : _registerWeakMap_preList) _registerWeakMap(o);
_registerWeakMap_preList = null;
}
static public Map newWeakMap() {
return newWeakHashMap();
}
static public WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
static public boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean isEmpty(Object[] a) {
return a == null || a.length == 0;
}
static public boolean isEmpty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static public boolean isEmpty(DoubleRange r) {
return r == null || r.isEmpty();
}
static public boolean isEmpty(AppendableChain c) {
return c == null;
}
static public Class javax() {
return getJavaX();
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public Pair first(Map map) {
return mapEntryToPair(first(entrySet(map)));
}
static public Pair first(MultiMap mm) {
if (mm == null)
return null;
var e = first(mm.data.entrySet());
if (e == null)
return null;
return pair(e.getKey(), first(e.getValue()));
}
static public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public Character first(CharSequence s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public A first(T3 t) {
return t == null ? null : t.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static public A first(AppendableChain a) {
return a == null ? null : a.element;
}
static public List buttonsInGroup(ButtonGroup g) {
if (g == null)
return ll();
return asList(g.getElements());
}
static public boolean isLetterOrDigit(char c) {
return Character.isLetterOrDigit(c);
}
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 boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static public int strL(String s) {
return s == null ? 0 : s.length();
}
static public int listL(Collection l) {
return l == null ? 0 : l.size();
}
static public void messageBox(final String msg) {
print(msg);
{
swing(() -> {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
});
}
}
static public void messageBox(Throwable e) {
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
static public RootPaneContainer getPossiblyInternalFrame(Component c) {
JInternalFrame f = getInternalFrame(c);
if (f != null)
return f;
return optCast(RootPaneContainer.class, getWindow(c));
}
static public void setMenuBar(final JMenuBar mb, final RootPaneContainer f) {
{
swing(() -> {
call(f, "setJMenuBar", mb);
revalidate((Component) f);
});
}
}
static public void setMenuBar(RootPaneContainer f, JMenuBar mb) {
setMenuBar(mb, f);
}
static public DocumentListener runnableToDocumentListener(Runnable r) {
return new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
pcallF(r);
}
public void removeUpdate(DocumentEvent e) {
pcallF(r);
}
public void changedUpdate(DocumentEvent e) {
pcallF(r);
}
};
}
static public JTextField onEnter(JTextField tf, JButton btn) {
if (btn != null)
onEnter(tf, new Runnable() {
public void run() {
try {
clickButton(btn);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "clickButton(btn)";
}
});
return tf;
}
static public JTextField onEnter(JTextField tf, 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, Runnable action) {
{
swing(() -> {
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);";
}
}));
}
});
}
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(Runnable action, JTextField tf) {
return onEnter(tf, action);
}
static public String selectedItem(JList l) {
return getSelectedItem(l);
}
static public String selectedItem(JComboBox cb) {
return getSelectedItem(cb);
}
static public WeakHasherMap symbol_map = new WeakHasherMap(new Hasher() {
public int hashCode(Symbol symbol) {
return symbol.text.hashCode();
}
public boolean equals(Symbol a, Symbol b) {
if (a == null)
return b == null;
return b != null && eq(a.text, b.text);
}
});
static public Symbol symbol(String s) {
if (s == null)
return null;
synchronized (symbol_map) {
Symbol symbol = new Symbol(s, true);
Symbol existingSymbol = symbol_map.findKey(symbol);
if (existingSymbol == null)
symbol_map.put(existingSymbol = symbol, true);
return existingSymbol;
}
}
static public Symbol symbol(CharSequence s) {
if (s == null)
return null;
if (s instanceof Symbol)
return (Symbol) s;
if (s instanceof String)
return symbol((String) s);
return symbol(str(s));
}
static public Symbol symbol(Object o) {
return symbol((CharSequence) o);
}
static public Set newWeakHashSet() {
return synchroWeakHashSet();
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
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 standardLogFile() {
return getProgramFile("log");
}
static public void logQuoted(String logFile, String line) {
logQuoted(getProgramFile(logFile), line);
}
static public void logQuoted(File logFile, String line) {
appendToFile(logFile, quote(line) + "\n");
}
static public long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static public String _userHome;
static public String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
static public File userHome(String path) {
return new File(userDir(), path);
}
static public File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static public File newFile(String name) {
return name == null ? null : new File(name);
}
static public File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static public JTextArea enableWordWrapForTextArea(JTextArea ta) {
return enableWordWrapForTextArea(ta, true);
}
static public JTextArea enableWordWrapForTextArea(JTextArea ta, boolean enabled) {
if (ta != null) {
swing(() -> {
ta.setLineWrap(enabled);
ta.setWrapStyleWord(true);
});
}
return ta;
}
static public JTextArea jtextarea() {
return jTextArea();
}
static public JTextArea jtextarea(String text) {
return jTextArea(text);
}
static public float getSwingFontScale() {
return or((Float) vm_generalMap_get("swingFontScale_value"), 1f);
}
static public Rect screenBounds_safe(int iScreen) {
return screenBounds(min(iScreen, screenCount() - 1));
}
static public IF0 preferredScreen;
static public int preferredScreen() {
return preferredScreen != null ? preferredScreen.get() : preferredScreen_base();
}
final static public int preferredScreen_fallback(IF0 _f) {
return _f != null ? _f.get() : preferredScreen_base();
}
static public int preferredScreen_base() {
return 0;
}
static public boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Iterable it, Object a) {
if (it != null)
for (Object o : it) if (eq(a, o))
return true;
return false;
}
static public boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
static public boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static public boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static public boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static public boolean contains(Producer p, A a) {
if (p != null && a != null)
while (true) {
A x = p.next();
if (x == null)
break;
if (eq(x, a))
return true;
}
return false;
}
static public boolean contains(Rect r, Pt p) {
return rectContains(r, p);
}
static public List vmBus_queryAll(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
List out = new ArrayList();
for (Object o : unnullForIteration(vm_busListeners_live())) addIfNotNull(out, pcallF(o, msg, arg));
for (Object o : unnullForIteration(vm_busListenersByMessage_live().get(msg))) addIfNotNull(out, pcallF(o, msg, arg));
return out;
}
static public int toInt(Object o) {
if (o == null)
return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt((String) o);
if (o instanceof Boolean)
return boolToInt((Boolean) o);
throw fail("woot not int: " + getClassName(o));
}
static public int toInt(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
static public int toInt_checked(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
static public Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static public boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
static public void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, Math.min(a.length, b.length));
}
static public void arraycopy(Object src, int srcPos, int destPos, int n) {
arraycopy(src, srcPos, src, destPos, n);
}
static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
static public int imageIcon_cacheSize = 10;
static public boolean imageIcon_verbose = false;
static public Map imageIcon_cache;
static public Lock imageIcon_lock = lock();
static public ThreadLocal imageIcon_fixGIF = new ThreadLocal();
static public ImageIcon imageIcon(String imageID) {
try {
if (imageID == null)
return null;
Lock __0 = imageIcon_lock;
lock(__0);
try {
if (imageIcon_cache == null)
imageIcon_cache = new MRUCache(imageIcon_cacheSize);
imageID = fsI(imageID);
ImageIcon ii = imageIcon_cache.get(imageID);
if (ii == null) {
if (imageIcon_verbose)
print("Loading image icon: " + imageID);
File f = loadBinarySnippet(imageID);
Boolean b = imageIcon_fixGIF.get();
if (!isFalse(b))
ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
else
ii = new ImageIcon(f.toURI().toURL());
} else
imageIcon_cache.remove(imageID);
imageIcon_cache.put(imageID, ii);
return ii;
} finally {
unlock(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ImageIcon imageIcon(File f) {
try {
return new ImageIcon(f.toURI().toURL());
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ImageIcon imageIcon(Image img) {
return img == null ? null : new ImageIcon(img);
}
static public ImageIcon imageIcon(RGBImage img) {
return imageIcon(img.getBufferedImage());
}
static public JButton setButtonImage(Icon img, JButton btn) {
btn.setIcon(img);
return btn;
}
static public JButton setButtonImage(Image img, JButton btn) {
btn.setIcon(imageIcon(img));
return btn;
}
static public A setButtonImage(Image img, A btn) {
btn.setIcon(imageIcon(img));
return btn;
}
static public A setButtonImage(A btn, Image img) {
return setButtonImage(img, btn);
}
static public A setButtonImage(A btn, String imageID) {
btn.setIcon(imageIcon(imageID));
return btn;
}
static public JButton setButtonImage(JButton btn, Image img) {
return setButtonImage(img, btn);
}
static public JButton setButtonImage(JButton btn, Icon img) {
return setButtonImage(img, btn);
}
static public A setToolTip(A c, Object toolTip) {
return setToolTipText(c, toolTip);
}
static public A setToolTip(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
static public void setToolTip(TrayIcon trayIcon, String toolTip) {
setTrayIconToolTip(trayIcon, toolTip);
}
static public BufferedImage resizeImage(BufferedImage img, int newW, int newH) {
return resizeImage(img, newW, newH, Image.SCALE_SMOOTH);
}
static public BufferedImage resizeImage(BufferedImage img, int newW, int newH, int scaleType) {
if (newW == img.getWidth() && newH == img.getHeight())
return img;
Image tmp = img.getScaledInstance(newW, newH, scaleType);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
static public BufferedImage resizeImage(BufferedImage img, int newW) {
int newH = iround(img.getHeight() * (double) newW / img.getWidth());
return resizeImage(img, newW, newH);
}
static public BufferedImage resizeImage(int newW, BufferedImage img) {
return resizeImage(img, newW);
}
static public BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static public BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
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 x30_pkg.x30_util.BetterThreadLocal newPing_actionTL;
static public x30_pkg.x30_util.BetterThreadLocal newPing_actionTL() {
if (newPing_actionTL == null)
newPing_actionTL = vm_generalMap_getOrCreate("newPing_actionTL", () -> {
Runnable value = (Runnable) (callF_gen(vm_generalMap_get("newPing_valueForNewThread")));
var tl = new x30_pkg.x30_util.BetterThreadLocal();
tl.set(value);
return tl;
});
return newPing_actionTL;
}
static public void assertTrue(Object o) {
if (!(eq(o, true)))
throw fail(str(o));
}
static public boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static public boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static volatile public boolean licensed_yes = true;
static public boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
static public void licensed_off() {
licensed_yes = false;
}
static public void clear(Collection c) {
if (c != null)
c.clear();
}
static public void clear(Map map) {
if (map != null)
map.clear();
}
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 B syncMapGet2(Map map, A a) {
if (map == null)
return null;
synchronized (collectionMutex(map)) {
return map.get(a);
}
}
static public B syncMapGet2(A a, Map map) {
return syncMapGet2(map, a);
}
static public boolean isSubtypeOf(Class a, Class b) {
return a != null && b != null && b.isAssignableFrom(a);
}
static public Set reflection_classesNotToScan_value = litset("jdk.internal.loader.URLClassPath");
static public Set reflection_classesNotToScan() {
return reflection_classesNotToScan_value;
}
static public HashMap> callMC_cache = new HashMap();
static public String callMC_key;
static public Method callMC_value;
static public Object callMC(String method, String[] arg) {
return callMC(method, new Object[] { arg });
}
static public Object callMC(String method, Object... args) {
try {
Method me;
if (callMC_cache == null)
callMC_cache = new HashMap();
synchronized (callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null)
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
List m;
synchronized (callMC_cache) {
m = callMC_cache.get(method);
}
if (m == null) {
if (callMC_cache.isEmpty()) {
callMC_makeCache();
m = callMC_cache.get(method);
}
if (m == null)
throw fail("Method named " + method + " not found in main");
}
int n = m.size();
if (n == 1) {
me = m.get(0);
synchronized (callMC_cache) {
callMC_key = method;
callMC_value = me;
}
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return invokeMethod(me, null, args);
}
throw fail("No method called " + method + " with arguments (" + joinWithComma(getClasses(args)) + ") found in main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void callMC_makeCache() {
synchronized (callMC_cache) {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
makeAccessible(m);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
static public List synchroList() {
return synchroList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static public A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first((Collection) strings));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(String glue, Object... strings) {
return join(glue, Arrays.asList(strings));
}
static public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static public List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
static public Object collectionMutex(List l) {
return l;
}
static public Object collectionMutex(Object o) {
if (o instanceof List)
return o;
String c = className(o);
return o;
}
static public Throwable _storeException_value;
static public void _storeException(Throwable e) {
_storeException_value = e;
}
static public Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static public Map syncHashMap() {
return synchroHashMap();
}
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 int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
static public String htmlencode_noQuotes(String s) {
if (s == null)
return "";
int n = s.length();
StringBuilder out = null;
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c == '<') {
if (out == null)
out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s));
out.append("<");
} else if (c == '>') {
if (out == null)
out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s));
out.append(">");
} else if (c > 127 || c == '&') {
int cp = s.codePointAt(i);
if (out == null)
out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s));
out.append("");
out.append(intToHex_flexLength(cp));
out.append(';');
i += Character.charCount(cp) - 1;
} else {
if (out != null)
out.append(c);
}
}
return out == null ? s : out.toString();
}
static public boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static public void setCaret(final JTextComponent c, final int pos) {
if (c != null) {
swing(() -> {
c.setCaretPosition(pos);
});
}
}
static public String programTitle() {
return getProgramName();
}
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 JFrame getFrame(final Object _o) {
return swing(new F0() {
public JFrame get() {
try {
Object o = _o;
if (o instanceof ButtonGroup)
o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component))
return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JFrame)
return (JFrame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button...";
}
});
}
static public A setFrameTitle(A c, final String title) {
final Frame f = getAWTFrame(c);
if (f != null) {
swing(() -> {
f.setTitle(title);
});
}
return c;
}
static public A setFrameTitle(String title, A c) {
return setFrameTitle(c, title);
}
static public JFrame setFrameTitle(String title) {
Object f = getOpt(mc(), "frame");
if (f instanceof JFrame)
return setFrameTitle((JFrame) f, title);
return null;
}
static public JFrame setFrameIconLater(Component c, final String imageID) {
final JFrame frame = getFrame(c);
if (frame != null)
startThread("Loading Icon", new Runnable() {
public void run() {
try {
final Image i = imageIcon(or2(imageID, "#1005557")).getImage();
swingLater(new Runnable() {
public void run() {
try {
frame.setIconImage(i);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "frame.setIconImage(i);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n swingL...";
}
});
return frame;
}
static public void _initFrame(JFrame f) {
myFrames_list.put(f, Boolean.TRUE);
standardTitlePopupMenu(f);
}
static public Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400);
static public Rectangle defaultNewFrameBounds() {
return swing(new F0() {
public Rectangle get() {
try {
defaultNewFrameBounds_r.translate(60, 20);
var bounds = preferredScreenBounds();
if (!bounds.contains(defaultNewFrameBounds_r))
defaultNewFrameBounds_r.setLocation(centerX(bounds) + random_incl(-30, 30), centerY(bounds) + random_incl(-20, 20));
return new Rectangle(defaultNewFrameBounds_r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "defaultNewFrameBounds_r.translate(60, 20);\r\n var bounds = preferredScreenB...";
}
});
}
static public void hideConsole() {
final JFrame frame = consoleFrame();
if (frame != null) {
autoVMExit();
swingLater(new Runnable() {
public void run() {
try {
frame.setVisible(false);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "frame.setVisible(false);";
}
});
}
}
static public String getProgramTitle() {
return getProgramName();
}
static public String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
static public String fromLines(String... lines) {
return fromLines(asList(lines));
}
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) {
int n = s.length();
for (int i = start; i < n; i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static public List mapToLines(Map map) {
List l = new ArrayList();
for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
return l;
}
static public String mapToLines(Map map, Object f) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Map map) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Iterable l) {
return lines(map(f, l));
}
static public String mapToLines(Iterable l, IF1 f) {
return mapToLines((Object) f, l);
}
static public String mapToLines(IF1 f, Iterable l) {
return mapToLines((Object) f, l);
}
static public String mapToLines(Map map, IF2 f) {
return lines(map(map, f));
}
static public String mapToLines(IF1 f, A data1, A... moreData) {
return lines(map(f, data1, moreData));
}
static public Map weakHashMap() {
return newWeakHashMap();
}
static public List keysList(Map map) {
return cloneListSynchronizingOn(keys(map), map);
}
static public List keysList(MultiSet ms) {
return ms == null ? null : keysList(ms.map);
}
static public A popLast(List l) {
return liftLast(l);
}
static public List popLast(int n, List l) {
return liftLast(n, l);
}
static public Map synchronizedMap() {
return synchroMap();
}
static public Map synchronizedMap(Map map) {
return synchroMap(map);
}
static public ClassLoader classLoaderForObject(Object o) {
if (o instanceof ClassLoader)
return ((ClassLoader) o);
if (o == null)
return null;
return _getClass(o).getClassLoader();
}
static public String classNameToVM(String name) {
return name.replace(".", "$");
}
static public IMeta initIMeta(Object o) {
if (o == null)
return null;
if (o instanceof IMeta)
return ((IMeta) o);
if (o instanceof JComponent)
return initMetaOfJComponent((JComponent) o);
if (o instanceof BufferedImage)
return optCast(IMeta.class, ((BufferedImage) o).getProperty("meta"));
return null;
}
static public String joinNempties(String sep, Object... strings) {
return joinStrings(sep, strings);
}
static public String joinNempties(String sep, Iterable strings) {
return joinStrings(sep, strings);
}
static public int identityHashCode(Object o) {
return System.identityHashCode(o);
}
static public IMeta toIMeta(Object o) {
return initIMeta(o);
}
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 void addToContainer(Container a, Component... b) {
if (a == null)
return;
{
swing(() -> {
for (Component c : unnullForIteration(b)) if (c != null)
a.add(c);
});
}
}
static public Component wrapForSmartAdd(Object o) {
if (o == null)
return jpanel();
if (o instanceof String)
return jlabel((String) o);
return wrap(o);
}
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 List tok_combineCurlyBrackets_keep(List tok) {
List l = new ArrayList();
for (int i = 0; i < l(tok); i++) {
String t = tok.get(i);
if (odd(i) && eq(t, "{")) {
int j = findEndOfCurlyBracketPart(tok, i);
l.add(joinSubList(tok, i, j));
i = j - 1;
} else
l.add(t);
}
return l;
}
static public int javaTok_n, javaTok_elements;
static public boolean javaTok_opt = false;
static public List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !regionMatches(s, j, "*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j < l && !regionMatches(s, j, "]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !regionMatches(s, j, "]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static public boolean startsWithAndEndsWith(String s, String prefix, String suffix) {
return startsWith(s, prefix) && endsWith(s, suffix);
}
static public List immutableEmptyList() {
return Collections.emptyList();
}
static public short[] emptyShortArray = new short[0];
static public short[] emptyShortArray() {
return emptyShortArray;
}
static public Map immutableEmptyMap() {
return Collections.emptyMap();
}
static public List dropFirstThreeAndLastThree(List l) {
return dropFirstAndLast(3, l);
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(BitSet bs) {
return !empty(bs);
}
static public boolean nempty(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(IMultiMap mm) {
return mm != null && mm.size() != 0;
}
static public boolean nempty(Object o) {
return !empty(o);
}
static public boolean nempty(IntRange r) {
return !empty(r);
}
static public boolean nempty(Rect r) {
return r != null && r.w != 0 && r.h != 0;
}
static public boolean nempty(MultiSet ms) {
return ms != null && !ms.isEmpty();
}
static public String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static public String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static public String formatSnippetID(long id) {
return "#" + id;
}
static public Class getMainClass() {
return mc();
}
static public Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
ClassLoader cl = (o instanceof Class ? (Class) o : o.getClass()).getClassLoader();
if (cl == null)
return null;
String name = mainClassNameForClassLoader(cl);
return loadClassFromClassLoader_orNull(cl, name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A vm_generalMap_getOrCreate(Object key, F0 create) {
return vm_generalMap_getOrCreate(key, f0ToIF0(create));
}
static public A vm_generalMap_getOrCreate(Object key, IF0 create) {
Map generalMap = vm_generalMap();
if (generalMap == null)
return null;
synchronized (generalMap) {
A a = (A) (vm_generalMap_get(key));
if (a == null)
vm_generalMap_put(key, a = create == null ? null : create.get());
return a;
}
}
static public A printException(A e) {
printStackTrace(e);
return e;
}
static public Class __javax;
static public Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void __setJavaX(Class j) {
__javax = j;
_onJavaXSet();
}
static public Pair mapEntryToPair(Map.Entry e) {
return e == null ? null : pair(e.getKey(), e.getValue());
}
static public Set> entrySet(Map map) {
return _entrySet(map);
}
static public A firstThat(Iterable l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(A[] l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public A firstThat(IF1 pred, A[] l) {
return firstThat(l, pred);
}
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 A optCast(Class c, Object o) {
return isInstance(c, o) ? (A) o : null;
}
static public void clickButton(final JButton b) {
if (b != null) {
swing(() -> {
if (b.isEnabled())
b.doClick();
});
}
}
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 String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
static public String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
static public Set synchroWeakHashSet() {
return Collections.newSetFromMap((Map) newWeakHashMap());
}
static public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(Symbol a, Symbol b) {
return eq(a, b);
}
static public boolean eqic(Symbol a, String b) {
return eqic(asString(a), b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
static public File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
static public Lock appendToFile_lock = lock();
static public boolean appendToFile_keepOpen = false;
static public HashMap appendToFile_writers = new HashMap();
static public void appendToFile(String path, String s) {
try {
Lock __0 = appendToFile_lock;
lock(__0);
try {
mkdirsForFile(new File(path));
path = getCanonicalPath(path);
Writer writer = appendToFile_writers.get(path);
if (writer == null) {
writer = new BufferedWriter(new OutputStreamWriter(newFileOutputStream(path, true), "UTF-8"));
if (appendToFile_keepOpen)
appendToFile_writers.put(path, writer);
}
writer.write(s);
if (!appendToFile_keepOpen)
writer.close();
} finally {
unlock(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void appendToFile(File path, String s) {
if (path != null)
appendToFile(path.getPath(), s);
}
static public void cleanMeUp_appendToFile() {
AutoCloseable __3 = tempCleaningUp();
try {
Lock __1 = appendToFile_lock;
lock(__1);
try {
closeAllWriters(values(appendToFile_writers));
appendToFile_writers.clear();
} finally {
unlock(__1);
}
} finally {
_close(__3);
}
}
static public String actualUserHome_value;
static public String actualUserHome() {
if (actualUserHome_value == null) {
if (isAndroid())
actualUserHome_value = "/storage/emulated/0/";
else
actualUserHome_value = System.getProperty("user.home");
}
return actualUserHome_value;
}
static public File actualUserHome(String sub) {
return newFile(new File(actualUserHome()), sub);
}
static public File userDir() {
return new File(userHome());
}
static public File userDir(String path) {
return new File(userHome(), path);
}
static public JTextArea jTextArea() {
return jTextArea("");
}
static public JTextArea jTextArea(final String text) {
return jTextAreaWithUndo(text);
}
static public Rect screenBounds(GraphicsDevice screen) {
return screen == null ? null : toRect(screen.getDefaultConfiguration().getBounds());
}
static public Rect screenBounds(int iScreen) {
return screenBounds(get(screenDevices(), iScreen));
}
static public int screenCount() {
return l(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices());
}
static public boolean rectContains(int x1, int y1, int w, int h, Pt p) {
return p.x >= x1 && p.y >= y1 && p.x < x1 + w && p.y < y1 + h;
}
static public boolean rectContains(Rect a, Rect b) {
return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2();
}
static public boolean rectContains(Rect a, Rectangle b) {
return rectContains(a, toRect(b));
}
static public boolean rectContains(Rect a, int x, int y) {
return a != null && a.contains(x, y);
}
static public boolean rectContains(Rect a, Pt p) {
return a != null && p != null && a.contains(p);
}
static public boolean addIfNotNull(Collection l, A a) {
return a != null && l != null & l.add(a);
}
static public void addIfNotNull(MultiSet ms, A a) {
if (a != null && ms != null)
ms.add(a);
}
static public int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static public int parseInt(char c) {
return Integer.parseInt(str(c));
}
static public int boolToInt(boolean b) {
return b ? 1 : 0;
}
static public void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
vmBus_send("locking", lock, "thread", currentThread());
lock.lockInterruptibly();
vmBus_send("locked", lock, "thread", currentThread());
} catch (InterruptedException e) {
Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
printStackTrace(e);
rethrow(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static public void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static public ReentrantLock lock() {
return fairLock();
}
static public String fsI(String id) {
return formatSnippetID(id);
}
static public String fsI(long id) {
return formatSnippetID(id);
}
static public File loadBinarySnippet(String snippetID) {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
return loadBinarySnippet_noResourceLoader(snippetID);
}
static public File loadBinarySnippet_noResourceLoader(String snippetID) {
try {
long id = parseSnippetID(snippetID);
if (isImageServerSnippet(id))
return loadImageAsFile(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile_noResourceLoader(snippetID);
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean loadBufferedImageFixingGIFs_debug = false;
static public ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal();
static public Image loadBufferedImageFixingGIFs(File file) {
try {
if (!file.exists())
return null;
if (!isGIF(file))
return ImageIO.read(file);
if (loadBufferedImageFixingGIFs_debug)
print("loadBufferedImageFixingGIFs" + ": checking gif");
ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
reader.setInput(ImageIO.createImageInputStream(file));
int numImages = reader.getNumImages(true);
IIOMetadata imageMetaData = reader.getImageMetadata(0);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
boolean foundBug = false;
for (int i = 0; i < numImages && !foundBug; i++) {
IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
if (Integer.parseInt(delay) == 0) {
foundBug = true;
}
break;
}
}
}
if (loadBufferedImageFixingGIFs_debug)
print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
Image image;
if (!foundBug) {
image = Toolkit.getDefaultToolkit().createImage(f2s(file));
} else {
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
{
ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
try {
ImageWriter writer = ImageIO.getImageWriter(reader);
writer.setOutput(ios);
writer.prepareWriteSequence(null);
for (int i = 0; i < numImages; i++) {
BufferedImage frameIn = reader.read(i);
IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
if (Integer.parseInt(delay) == 0) {
((IIOMetadataNode) node).setAttribute("delayTime", "10");
}
break;
}
}
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
IIOImage frameOut = new IIOImage(frameIn, null, metadata);
writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
}
writer.endWriteSequence();
} finally {
_close(ios);
}
}
byte[] data = baoStream.toByteArray();
setVar(loadBufferedImageFixingGIFs_output.get(), data);
if (loadBufferedImageFixingGIFs_debug)
print("Data size: " + l(data));
image = Toolkit.getDefaultToolkit().createImage(data);
}
return image;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void unlock(Lock lock, String msg) {
if (lock == null)
return;
lock.unlock();
vmBus_send("unlocked", lock, "thread", currentThread());
print("Unlocked: " + msg);
}
static public void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
vmBus_send("unlocked", lock, "thread", currentThread());
}
static public void setTrayIconToolTip(TrayIcon trayIcon, String toolTip) {
if (trayIcon != null)
trayIcon.setToolTip(toolTip);
}
static public boolean loadBufferedImage_useImageCache = true;
static public BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) {
try {
ping();
if (snippetIDOrURLOrFile == null)
return null;
if (isURL(snippetIDOrURLOrFile))
return imageIO_readURL(snippetIDOrURLOrFile);
if (isSnippetID(snippetIDOrURLOrFile)) {
String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return loadBufferedImage(rl.loadLibrary(snippetID));
File dir = imageSnippetsCacheDir();
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
try {
return ImageIO.read(file);
} catch (Throwable e) {
e.printStackTrace();
}
}
String imageURL = snippetImageURL_http(snippetID);
print("Loading image: " + imageURL);
BufferedImage image = imageIO_readURL(imageURL);
if (loadBufferedImage_useImageCache) {
File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
ImageIO.write(image, "png", tempFile);
tempFile.renameTo(new File(dir, snippetID + ".png"));
}
return image;
} else
return loadBufferedImage(new File(snippetIDOrURLOrFile));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public BufferedImage loadBufferedImage(File file) {
return loadBufferedImageFile(file);
}
static public int lastIndexOf(String a, String b) {
return a == null || b == null ? -1 : a.lastIndexOf(b);
}
static public int lastIndexOf(String a, char b) {
return a == null ? -1 : a.lastIndexOf(b);
}
static public int lastIndexOf(List l, int i, A a) {
if (l == null)
return -1;
for (i = min(l(l), i) - 1; i >= 0; i--) if (eq(l.get(i), a))
return i;
return -1;
}
static public int lastIndexOf(List l, A a) {
if (l == null)
return -1;
for (int i = l(l) - 1; i >= 0; i--) if (eq(l.get(i), a))
return i;
return -1;
}
static public A callF_gen(F0 f) {
return f == null ? null : f.get();
}
static public B callF_gen(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public A callF_gen(IF0 f) {
return f == null ? null : f.get();
}
static public B callF_gen(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF_gen(A a, IF1 f) {
return f == null ? null : f.get(a);
}
static public C callF_gen(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public void callF_gen(VF1 f, A a) {
{
if (f != null)
f.get(a);
}
}
static public void callF_gen(A a, IVF1 f) {
{
if (f != null)
f.get(a);
}
}
static public void callF_gen(IVF1 f, A a) {
{
if (f != null)
f.get(a);
}
}
static public Object callF_gen(Runnable r) {
{
if (r != null)
r.run();
}
return null;
}
static public Object callF_gen(Object f, Object... args) {
return callF(f, args);
}
static public HashSet litset(A... items) {
return lithashset(items);
}
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 void multiMapPut(MultiMap mm, A key, B value) {
if (mm != null && key != null && value != null)
mm.put(key, value);
}
static public Set synchronizedSet() {
return synchroHashSet();
}
static public Set synchronizedSet(Set set) {
return Collections.synchronizedSet(set);
}
static public Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
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 CharSequence takeFirst(int n, CharSequence s) {
return subCharSequence(s, 0, n);
}
static public List takeFirst(int n, Iterator it) {
if (it == null)
return null;
List l = new ArrayList();
for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
static public List takeFirst(int n, Iterable i) {
if (i == null)
return null;
return i == null ? null : takeFirst(n, i.iterator());
}
static public List takeFirst(int n, IterableIterator i) {
return takeFirst(n, (Iterator ) i);
}
static public int[] takeFirst(int n, int[] a) {
return takeFirstOfIntArray(n, a);
}
static public short[] takeFirst(int n, short[] a) {
return takeFirstOfShortArray(n, a);
}
static public byte[] takeFirst(int n, byte[] a) {
return takeFirstOfByteArray(n, a);
}
static public byte[] takeFirst(byte[] a, int n) {
return takeFirstOfByteArray(n, a);
}
static public double[] takeFirst(int n, double[] a) {
return takeFirstOfDoubleArray(n, a);
}
static public double[] takeFirst(double[] a, int n) {
return takeFirstOfDoubleArray(n, a);
}
static public String intToHex_flexLength(int i) {
return Integer.toHexString(i);
}
static public String getProgramName_cache;
static public String getProgramName() {
Lock __0 = downloadLock();
lock(__0);
try {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitleOpt(programID());
return getProgramName_cache;
} finally {
unlock(__0);
}
}
static public void _onLoad_getProgramName() {
{
startThread(new Runnable() {
public void run() {
try {
getProgramName();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "getProgramName();";
}
});
}
}
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 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 boolean even(BigInteger n) {
return even(n.intValue());
}
static public Frame getAWTFrame(final Object _o) {
return swing(new F0 () {
public Frame get() {
try {
Object o = _o;
if (o instanceof ButtonGroup)
o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component))
return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof Frame)
return (Frame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "O o = _o;\r\n /*\r\n ifdef HaveProcessing\r\n if (o instanceof PApplet) ...";
}
});
}
static public String or2(String a, String b) {
return nempty(a) ? a : b;
}
static public String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
static public void standardTitlePopupMenu(final JFrame frame) {
if (!isSubstanceLAF())
return;
titlePopupMenu(frame, new VF1() {
public void get(JPopupMenu menu) {
try {
boolean alwaysOnTop = frame.isAlwaysOnTop();
menu.add(jmenuItem("Restart Program", new Runnable() {
public void run() {
try {
restart();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "restart();";
}
}));
menu.add(jmenuItem("Duplicate Program", new Runnable() {
public void run() {
try {
duplicateThisProgram();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "duplicateThisProgram();";
}
}));
menu.add(jmenuItem("Show Console", new Runnable() {
public void run() {
try {
showConsole();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "showConsole();";
}
}));
menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() {
public void run() {
try {
toggleAlwaysOnTop(frame);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "toggleAlwaysOnTop(frame)";
}
}));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n ifndef standardTitlePopupMenu_...";
}
});
}
static public Integer centerX(Rect r) {
return rectCenterX(r);
}
static public int random_incl(int min, int max) {
return random_incl(min, max, defaultRandomizer());
}
static public int random_incl(int min, int max, Random random) {
return random(min, max + 1, random);
}
static public int random_incl(int max) {
return random(0, max + 1);
}
static public Integer centerY(Rect r) {
return rectCenterY(r);
}
static public JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static public void autoVMExit() {
call(getJavaX(), "autoVMExit");
}
static public CloseableIterableIterator linesFromFile(File f) {
return linesFromFile(f, null);
}
static public CloseableIterableIterator linesFromFile(File f, IResourceHolder resourceHolder) {
try {
if (!f.exists())
return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)), resourceHolder);
return linesFromReader(utf8bufferedReader(f), resourceHolder);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public CloseableIterableIterator linesFromFile(String path) {
return linesFromFile(path, null);
}
static public CloseableIterableIterator linesFromFile(String path, IResourceHolder resourceHolder) {
return linesFromFile(newFile(path), resourceHolder);
}
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 Set keys(IMultiMap mm) {
return mm.keySet();
}
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) {
ping();
x.add(callF(f, o));
}
return x;
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
ping();
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
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(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) {
ping();
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) {
ping();
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) {
ping();
x.add(f.get(o));
}
return x;
}
static public List map(Map map, IF2 f) {
List x = new ArrayList();
if (map != null)
for (Map.Entry e : map.entrySet()) {
ping();
x.add(f.get(e.getKey(), e.getValue()));
}
return x;
}
static public List map(IF1 f, A data1, A... moreData) {
List x = emptyList(l(moreData) + 1);
x.add(f.get(data1));
if (moreData != null)
for (A o : moreData) {
ping();
x.add(f.get(o));
}
return x;
}
static public ArrayList cloneListSynchronizingOn(Collection l, Object mutex) {
if (l == null)
return new ArrayList();
synchronized (mutex) {
return new ArrayList (l);
}
}
static public A liftLast(List l) {
if (empty(l))
return null;
int i = l(l) - 1;
A a = l.get(i);
l.remove(i);
return a;
}
static public List liftLast(int n, List l) {
int i = l(l) - n;
List part = cloneSubList(l, i);
removeSubList(l, i);
return part;
}
static public IMeta initMetaOfJComponent(JComponent c) {
if (c == null)
return null;
IMeta meta = (IMeta) (c.getClientProperty(IMeta.class));
if (meta == null)
c.putClientProperty(IMeta.class, meta = new Meta());
return meta;
}
static public String joinStrings(String sep, Object... strings) {
return joinStrings(sep, Arrays.asList(strings));
}
static public String joinStrings(String sep, Iterable strings) {
StringBuilder buf = new StringBuilder();
for (Object o : unnull(strings)) {
String s = strOrNull(o);
if (nempty(s)) {
if (nempty(buf))
buf.append(sep);
buf.append(s);
}
}
return str(buf);
}
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 odd(int i) {
return (i & 1) != 0;
}
static public boolean odd(long i) {
return (i & 1) != 0;
}
static public boolean odd(BigInteger i) {
return odd(toInt(i));
}
static public int findEndOfCurlyBracketPart(List cnc, int i) {
int j = i + 2, level = 1;
while (j < cnc.size()) {
if (eq(cnc.get(j), "{"))
++level;
else if (eq(cnc.get(j), "}"))
--level;
if (level == 0)
return j + 1;
++j;
}
return cnc.size();
}
static public String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
static public String joinSubList(List l, int i) {
return join(subList(l, i));
}
static public String joinSubList(List l, IntRange r) {
return r == null ? null : joinSubList(l, r.start, r.end);
}
static public boolean regionMatches(String a, int offsetA, String b, int offsetB, int len) {
return a != null && b != null && a.regionMatches(offsetA, b, offsetB, len);
}
static public boolean regionMatches(String a, int offsetA, String b) {
return regionMatches(a, offsetA, b, 0, l(b));
}
static public String javaTok_substringN(String s, int i, int j) {
if (i == j)
return "";
if (j == i + 1 && s.charAt(i) == ' ')
return " ";
return s.substring(i, j);
}
static public String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
static public List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
}
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 List dropFirstAndLast(int n, List l) {
return cloneSubList(l, n, l(l) - n);
}
static public List dropFirstAndLast(int m, int n, List l) {
return cloneSubList(l, m, l(l) - n);
}
static public List dropFirstAndLast(List l) {
return dropFirstAndLast(1, l);
}
static public String dropFirstAndLast(String s) {
return substring(s, 1, l(s) - 1);
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
static public String mainClassNameForClassLoader(ClassLoader cl) {
return or((String) callOpt(cl, "mainClassName"), "main");
}
static public Class loadClassFromClassLoader_orNull(ClassLoader cl, String name) {
try {
return cl == null ? null : cl.loadClass(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public IF0 f0ToIF0(F0 f) {
return f == null ? null : () -> f.get();
}
static public void _onJavaXSet() {
}
static public Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
static public boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
static public File getProgramDir() {
return programDir();
}
static public File getProgramDir(String snippetID) {
return programDir(snippetID);
}
public static File mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) {
dir.mkdirs();
if (!dir.isDirectory())
if (dir.isFile())
throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
else
throw fail("Unknown IO exception during mkdirs of " + f2s(file));
}
return file;
}
public static String mkdirsForFile(String path) {
mkdirsForFile(new File(path));
return path;
}
static public String getCanonicalPath(File f) {
try {
return f == null ? null : f.getCanonicalPath();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String getCanonicalPath(String path) {
return getCanonicalPath(newFile(path));
}
static public FileOutputStream newFileOutputStream(File path) throws IOException {
return newFileOutputStream(path.getPath());
}
static public FileOutputStream newFileOutputStream(String path) throws IOException {
return newFileOutputStream(path, false);
}
static public FileOutputStream newFileOutputStream(File path, boolean append) throws IOException {
return newFileOutputStream(path.getPath(), append);
}
static public FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
mkdirsForFile(path);
FileOutputStream f = new FileOutputStream(path, append);
_registerIO(f, path, true);
return f;
}
static public AutoCloseable tempCleaningUp() {
AutoCloseable result = null;
result = tempSetTL(ping_isCleanUpThread, true);
return result;
}
static public void closeAllWriters(Collection extends Writer> l) {
for (Writer w : unnull(l)) {
try {
w.close();
} catch (Throwable __e) {
printStackTrace(__e);
}
}
}
static public Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static public Collection values(Object map) {
return values((Map) map);
}
static public Collection values(MultiMap mm) {
return mm == null ? emptyList() : concatLists(values(mm.data));
}
static public JTextArea jTextAreaWithUndo() {
return jTextAreaWithUndo("");
}
static public JTextArea jTextAreaWithUndo(final String text) {
return jenableUndoRedo(swingNu(JTextArea.class, text));
}
static public List screenDevices() {
return asList(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices());
}
static public boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static public Map vm_threadInterruptionReasonsMap() {
return vm_generalWeakSubMap("Thread interruption reasons");
}
static public String strOr(Object o, String ifNull) {
return o == null ? ifNull : str(o);
}
static public void lockOrFail(Lock lock, long timeout) {
try {
ping();
vmBus_send("locking", lock, "thread", currentThread());
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
vmBus_send("locked", lock, "thread", currentThread());
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static public IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
static public boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static public File loadImageAsFile(String snippetIDOrURL) {
try {
if (isURL(snippetIDOrURL))
throw fail("not implemented");
if (!isSnippetID(snippetIDOrURL))
throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
String snippetID = "" + parseSnippetID(snippetIDOrURL);
File file = imageSnippetCacheFile(snippetID);
if (fileSize(file) > 0)
return file;
String imageURL = snippetImageURL_noHttps(snippetID);
System.err.println("Loading image: " + imageURL);
byte[] data = loadBinaryPage(imageURL);
saveBinaryFile(file, data);
return file;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = DiskSnippetCache_file(snippetID);
return file.exists() ? file : null;
}
public static File DiskSnippetCache_getLibrary(String snippetID) {
try {
return DiskSnippetCache_getLibrary(psI(snippetID));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(DiskSnippetCache_file(snippetID), data);
}
static public byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL(dataSnippetLink(snippetID));
print("Loading library: " + hideCredentials(url));
try {
data = loadBinaryPage(url.openConnection());
} catch (RuntimeException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID));
print("Loading library: " + hideCredentials(url));
data = loadBinaryPage(url.openConnection());
}
print("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
static public long fileSize(String path) {
return getFileSize(path);
}
static public long fileSize(File f) {
return getFileSize(f);
}
static public File loadDataSnippetToFile(String snippetID) {
try {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
return loadDataSnippetToFile_noResourceLoader(snippetID);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File loadDataSnippetToFile_noResourceLoader(String snippetID) {
try {
snippetID = fsI(snippetID);
File f = DiskSnippetCache_file(parseSnippetID(snippetID));
List urlsTried = new ArrayList();
List errors = new ArrayList();
try {
URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
print("Loading library: " + hideCredentials(url));
try {
loadBinaryPageToFile(openConnection(url), f);
if (fileSize(f) == 0)
throw fail();
} catch (Throwable e) {
errors.add(e);
url = addAndReturn(urlsTried, new URL(tb_mainServer() + "/blobs/" + psI(snippetID)));
print(e);
print("Trying other server: " + hideCredentials(url));
loadBinaryPageToFile(openConnection(url), f);
print("Got bytes: " + fileSize(f));
}
if (fileSize(f) == 0)
throw fail();
System.err.println("Bytes loaded: " + fileSize(f));
} catch (Throwable e) {
errors.add(e);
throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
}
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] isGIF_magic = bytesFromHex("47494638");
static public boolean isGIF(byte[] data) {
return byteArrayStartsWith(data, isGIF_magic);
}
static public boolean isGIF(File f) {
return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
}
static public String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static public String f2s(String s) {
return f2s(newFile(s));
}
static public String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static public void setVar(IVar v, A value) {
if (v != null)
v.set(value);
}
static public IVF1 setVar(IVar v) {
return a -> {
if (v != null)
v.set(a);
};
}
static public boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
static public BufferedImage imageIO_readURL(String url) {
try {
return ImageIO.read(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File imageSnippetsCacheDir() {
return javaxCachesDir("Image-Snippets");
}
static public String snippetImageURL_http(String snippetID) {
return snippetImageURL_http(snippetID, "png");
}
static public String snippetImageURL_http(String snippetID, String contentType) {
return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080");
}
static public BufferedImage loadBufferedImageFile(File file) {
try {
return isFile(file) ? ImageIO.read(file) : null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Set synchroHashSet() {
return synchronizedSet(new HashSet ());
}
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 List newSubListOrSame(List l, IntRange r) {
return newSubListOrSame(l, r.start, r.end);
}
static public int[] takeFirstOfIntArray(int[] b, int n) {
return subIntArray(b, 0, n);
}
static public int[] takeFirstOfIntArray(int n, int[] b) {
return takeFirstOfIntArray(b, n);
}
static public short[] takeFirstOfShortArray(short[] b, int n) {
return subShortArray(b, 0, n);
}
static public short[] takeFirstOfShortArray(int n, short[] b) {
return takeFirstOfShortArray(b, n);
}
static public byte[] takeFirstOfByteArray(byte[] b, int n) {
return subByteArray(b, 0, n);
}
static public byte[] takeFirstOfByteArray(int n, byte[] b) {
return takeFirstOfByteArray(b, n);
}
static public double[] takeFirstOfDoubleArray(double[] b, int n) {
return subDoubleArray(b, 0, n);
}
static public double[] takeFirstOfDoubleArray(int n, double[] b) {
return takeFirstOfDoubleArray(b, n);
}
static public Lock downloadLock_lock = fairLock();
static public Lock downloadLock() {
return downloadLock_lock;
}
static public String getSnippetTitleOpt(String s) {
try {
return isSnippetID(s) ? getSnippetTitle(s) : s;
} catch (Throwable __e) {
printStackTrace(__e);
}
return s;
}
static public boolean isSubstanceLAF() {
return substanceLookAndFeelEnabled();
}
static public boolean titlePopupMenu(final Component c, final Object menuMaker) {
JComponent titleBar = getTitlePaneComponent(getPossiblyInternalFrame(c));
if (titleBar == null) {
print("Can't add title right click!");
return false;
} else {
componentPopupMenu(titleBar, menuMaker);
return true;
}
}
static public void restart() {
Object j = getJavaX();
call(j, "cleanRestart", get(j, "fullArgs"));
}
static public void duplicateThisProgram() {
nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs"))));
}
static public void showConsole() {
callOpt(get(javax(), "console"), "showConsole");
}
static public JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
final JCheckBoxMenuItem mi = swing(() -> new JCheckBoxMenuItem(text, checked));
addActionListener(mi, new Runnable() {
public void run() {
try {
callF(r, isChecked(mi));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r, isChecked(mi))";
}
});
return mi;
}
static public JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, IVF1 r) {
return jCheckBoxMenuItem(text, checked, (Object) r);
}
static public void toggleAlwaysOnTop(Window frame) {
if (frame == null)
return;
{
swing(() -> {
frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
});
}
}
static public Integer rectCenterX(Rect r) {
return r == null ? null : r.x + r.w / 2;
}
static public Random defaultRandomizer() {
return defaultRandomGenerator();
}
static public int random(int n) {
return random(n, defaultRandomGenerator());
}
static public int random(int n, Random r) {
return random(r, n);
}
static public int random(Random r, int n) {
return n <= 0 ? 0 : getRandomizer(r).nextInt(n);
}
static public double random(double max) {
return random() * max;
}
static public double random() {
return defaultRandomGenerator().nextInt(100001) / 100000.0;
}
static public double random(double min, double max) {
return min + random() * (max - min);
}
static public int random(int min, int max) {
return min + random(max - min);
}
static public int random(int min, int max, Random r) {
return random(r, min, max);
}
static public int random(Random r, int min, int max) {
return min + random(r, max - min);
}
static public A random(List l) {
return oneOf(l);
}
static public A random(Collection c) {
if (c instanceof List)
return random((List ) c);
int i = random(l(c));
return collectionGet(c, i);
}
static public int random(IntRange r) {
return random(r.start, r.end);
}
static public Pair random(Map map) {
return entryToPair(random(entries(map)));
}
static public Integer rectCenterY(Rect r) {
return r == null ? null : r.y + r.h / 2;
}
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) {
return linesFromReader(r, null);
}
static public CloseableIterableIterator linesFromReader(Reader r, IResourceHolder resourceHolder) {
final BufferedReader br = bufferedReader(r);
return holdResource(resourceHolder, iteratorFromFunction_f0_autoCloseable(new F0() {
public String get() {
try {
return readLineFromReaderWithClose(br);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return readLineFromReaderWithClose(br);";
}
}, _wrapIOCloseable(r)));
}
static public BufferedReader utf8bufferedReader(InputStream in) {
try {
return in == null ? null : 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