Warning : session_start(): open(/var/lib/php/sessions/sess_o14n8ph31tp1aokr7fiq9db96h, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import java.util.function.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.rethrow;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.IVF2;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.IterableIterator;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import com.github.sarxos.webcam.*;
import javax.swing.undo.UndoManager;
import java.text.SimpleDateFormat;
import java.awt.datatransfer.StringSelection;
import java.awt.geom.*;
import java.text.NumberFormat;
import java.text.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.nio.charset.Charset;
import java.util.TimeZone;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
class main {
static public class LiveWebCam extends DynSCP {
transient public WebcamPanel panel;
public int fpsLimit = -1;
public boolean autoStart = false;
static public boolean _switchableField_alwaysOnTop = true;
public boolean alwaysOnTop = false;
public void enhanceFrame(Container f) {
super.enhanceFrame(f);
minimalFrameSize(((JInternalFrame) f), 320, 240);
internalFramePopupMenuItem(f, "Save to AI Album", runnableThread(new Runnable() {
public void run() {
try {
dm_saveToAIAlbum(getImage());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_saveToAIAlbum(getImage())";
}
}));
internalFramePopupMenuItem(f, "Set FPS...", new Runnable() {
public void run() {
try {
final JTextField tf = jtextfield(str(fpsLimit));
showFormTitled("Set FPS Limit", "FPS Limit (-1 for no limit, 0 for no updates):", tf, runnableThread(new Runnable() {
public void run() {
try {
setFPSLimit(parseInt(gtt(tf)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "setFPSLimit(parseInt(gtt(tf)))";
}
}));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JTextField tf = jtextfield(str(fpsLimit));\r\n showFormTitled(\"Set F...";
}
});
dm_boolFieldMenuItem(f, "autoStart");
internalFramePopupMenuItem(f, "Natural size", new Runnable() {
public void run() {
try {
dm_packFrame();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_packFrame();";
}
});
if (alwaysOnTop)
dm_alwaysOnTop(f);
}
public JComponent visualize2() {
return jcenteredbutton("Start", runnableThread(new Runnable() {
public void run() {
try {
startIt();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startIt();";
}
}));
}
public JComponent visualize() {
JComponent _c = super.visualize();
if (autoStart)
startIt();
return _c;
}
public void startIt() {
selectWebCam(new VF1() {
public void get(Webcam a) {
try {
selectCam(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "selectCam(a)";
}
});
}
public void startPreferredOrSelect() {
selectWebCam_withPreferred(new VF1() {
public void get(Webcam a) {
try {
selectCam(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "selectCam(a)";
}
});
}
public void selectCam(Webcam cam) {
AutoCloseable __10 = enter();
try {
final WebcamPanel panel = new WebcamPanel(cam, false);
LiveWebCam.this.panel = panel;
bindToComponent(panel, null, new Runnable() {
public void run() {
try {
panel.stop();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "panel.stop()";
}
});
updateFPSLimitInPanel();
setComponent(panel);
} finally {
_close(__10);
}
}
public void stopIt() {
if (panel == null)
return;
panel.stop();
}
public BufferedImage getImage() {
return imageFromWebcamPanel(panel);
}
public void setFPSLimit(int limit) {
setField("fpsLimit", limit);
updateFPSLimitInPanel();
}
public void updateFPSLimitInPanel() {
setModuleName((fpsLimit >= 0 ? fpsLimit + " FPS - " : "") + "Live WebCam");
if (panel == null)
return;
panel.stop();
if (fpsLimit == 0)
return;
panel.setFPSDisplayed(fpsLimit < 0);
if (fpsLimit > 0)
panel.setFPSLimit(fpsLimit);
panel.setFPSLimited(fpsLimit > 0);
panel.start();
}
public boolean isWebCamLive() {
return panel != null && fpsLimit != 0;
}
}
static public boolean _moduleClass_LiveWebCam = true;
static public String programID;
static public void _onLoad_initUtils() {
utils.__javax = javax();
}
static public void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (name.startsWith("main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
return null;
}
});
}
static public ThreadLocal dynamicObjectIsLoading_threadLocal() {
return DynamicObject_loading;
}
static volatile public Concepts mainConcepts;
static public Concepts db_mainConcepts() {
if (mainConcepts == null)
mainConcepts = newConceptsWithClassFinder(getDBProgramID());
return mainConcepts;
}
static public void cleanMeUp_concepts() {
if (db_mainConcepts() != null)
db_mainConcepts().cleanMeUp();
}
static public void minimalFrameSize(Component c, int w, int h) {
Container f = getPIFrame(c);
if (f != null)
setSize(f, max(w, getWidth(f)), max(h, getHeight(f)));
}
static public void internalFramePopupMenuItem(Container f, final String name, final Object action) {
internalFrameTitlePopupMenuItem(((JInternalFrame) f), name, action);
}
static public Runnable runnableThread(final Runnable r) {
return new Runnable() {
public void run() {
try {
startThread(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startThread(r)";
}
};
}
static public File dm_saveToAIAlbum(BufferedImage img) {
Lock __0 = vm_getLock("AI Album");
lock(__0);
try {
File f = anonymousAIAlbumFile();
saveJPEG(f, img);
fileSavedInfoBox(f);
return copyFileToClipboard(f);
} finally {
unlock(__0);
}
}
static public JTextField jtextfield() {
return jTextField();
}
static public JTextField jtextfield(String text) {
return jTextField(text);
}
static public JTextField jtextfield(Object o) {
return jTextField(o);
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public int showForm_defaultGap = 4;
static public int showForm_gapBetweenColumns = 10;
static public JPanel showFormTitled(final String title, final Object... _parts) {
JDesktopPane desktop = mainDesktopPane();
if (desktop != null)
return showInternalFrameFormTitled(desktop, title, _parts);
return swing(new F0() {
public JPanel get() {
try {
final Var frame = new Var();
JPanel panel = showForm_makePanel(false, _parts);
showForm_makeFrame(title, panel);
frame.set(getFrame(panel));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final new Var frame;\r\n JPanel panel = showForm_makePanel(false, _p...";
}
});
}
static public JPanel showForm_makePanel(Boolean internalFrame, Object... _parts) {
List out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts));
return vstackWithSpacing(out, showForm_defaultGap);
}
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 String gtt(JTextComponent c) {
return getTextTrim(c);
}
static public String gtt(JComboBox cb) {
return getTextTrim(cb);
}
static public void dm_boolFieldMenuItem(Container frame, final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
final String humanized = humanizeFormLabel(field);
internalFrameTitlePopupMenu(((JInternalFrame) frame), new VF1() {
public void get(JPopupMenu menu) {
try {
menu.add(jCheckBoxMenuItem(humanized, (boolean) _get(m, field), new VF1() {
public void get(Boolean b) {
try {
m.setField(field, b);
callF(optPar(__, "onSet"));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "m.setField(field, b);\r\n callF(optPar(_, 'onSet));";
}
}));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "menu.add(jCheckBoxMenuItem(humanized, (bool) _get(m, field), voidfunc(bool b)...";
}
});
}
static public void dm_packFrame() {
packInternalFrame(dm_frame());
}
static public void dm_alwaysOnTop(Container frame) {
((JInternalFrame) frame).setLayer(JLayeredPane.PALETTE_LAYER);
}
static public JPanel jcenteredbutton(String text, Object action) {
return jcenteredline(jbutton(text, action));
}
static public JPanel jcenteredbutton(String text) {
return jcenteredbutton(text, null);
}
static public List _stickyLibs_1013490 = ll("#1008985", "#1008987", "#1004016", "#1004015");
static public void selectWebCam(final VF1 onSelect) {
selectWebCam(new ArrayList(Webcam.getWebcams()), onSelect);
}
static public void selectWebCam(final List webcams, final VF1 onSelect) {
List camNames = mapMethod("getName", webcams);
addToLocalMechList_uniq("All Web Cam Names", camNames);
if (l(webcams) == 1) {
swingLater(new Runnable() {
public void run() {
try {
callF(onSelect, first(webcams));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onSelect, first(webcams));";
}
});
return;
}
final JComboBox cbCams = jcombobox(camNames);
selectItem(cbCams, preferredWebCamName());
Runnable go = new Runnable() {
public void run() {
try {
swingLater(new Runnable() {
public void run() {
try {
callF(onSelect, webcams.get(getSelectedIndex(cbCams)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onSelect, webcams.get(getSelectedIndex(cbCams)))";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "swingLater(r {\r\n callF(onSelect, webcams.get(getSelectedIndex(cbCams)))\r\n ...";
}
};
onEnter(cbCams, go);
renameSubmitButton(showTitledForm("Select WebCam", "Camera:", cbCams, go), "Select camera");
}
static public void selectWebCam_withPreferred(final VF1 onSelect) {
final List webcams = new ArrayList(Webcam.getWebcams());
String preferred = trim(loadTextFile(preferredWebCamFile()));
final Webcam cam = findWebCamByName(webcams, preferred);
if (cam != null)
swingLater(new Runnable() {
public void run() {
try {
callF(onSelect, cam);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onSelect, cam)";
}
});
else
selectWebCam(webcams, new VF1() {
public void get(Webcam cam) {
try {
if (saveTextFileIfChanged(preferredWebCamFile(), cam.getName()))
infoBox("Saved preferred web cam: " + cam.getName());
callF(onSelect, cam);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (saveTextFileIfChanged(preferredWebCamFile(), cam.getName()))\r\n infoB...";
}
});
}
static public void setComponent(SingleComponentPanel scp, Component c) {
setSCPComponent(scp, c);
}
static public void setComponent(SingleComponentPanel scp, IF0 c) {
if (scp != null)
setComponent(scp, callF(c));
}
static public void _close(AutoCloseable c) {
if (c != null)
try {
c.close();
} catch (Throwable e) {
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else
throw rethrow(e);
}
}
static public BufferedImage imageFromWebcamPanel(WebcamPanel panel) {
return (BufferedImage) get(panel, "image");
}
static public Class javax() {
return getJavaX();
}
static public void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
static public HashMap findClass_fullName_cache = new HashMap();
static public Class findClass_fullName(String name) {
synchronized (findClass_fullName_cache) {
if (findClass_fullName_cache.containsKey(name))
return findClass_fullName_cache.get(name);
Class c;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_fullName_cache.put(name, c);
return c;
}
}
static public Object _defaultClassFinder_value = defaultDefaultClassFinder();
static public Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
static public Concepts newConceptsWithClassFinder(String progID) {
Concepts cc = new Concepts(progID);
cc.classFinder = _defaultClassFinder();
return cc;
}
static public String getDBProgramID_id;
static public String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
static public Container getPIFrame(Component c) {
return (Container) getPossiblyInternalFrame(c);
}
static public A setSize(final A c, final int w, final int h) {
if (c != null) {
swing(() -> {
c.setSize(w, h);
});
}
return c;
}
static public void setSize(Component c, Dimension d) {
setSize(c, d.width, d.height);
}
static public int max(int a, int b) {
return Math.max(a, b);
}
static public int max(int a, int b, int c) {
return max(max(a, b), c);
}
static public long max(int a, long b) {
return Math.max((long) a, b);
}
static public long max(long a, long b) {
return Math.max(a, b);
}
static public double max(int a, double b) {
return Math.max((double) a, b);
}
static public float max(float a, float b) {
return Math.max(a, b);
}
static public double max(double a, double b) {
return Math.max(a, b);
}
static public int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static public double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
static public short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
static public int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
static public > A max(A a, A b) {
return cmp(a, b) >= 0 ? a : b;
}
static public int getWidth(Component c) {
return c == null ? 0 : (int) swingCall(c, "getWidth");
}
static public int getHeight(Component c) {
return c == null ? 0 : (int) swingCall(c, "getHeight");
}
static public void internalFrameTitlePopupMenuItem(JInternalFrame f, final String name, final Object action) {
internalFrameTitlePopupMenu(f, new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, name, action);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, name, action)";
}
});
}
static public Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static public Thread startThread(String name, Runnable runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(runnable, name));
}
static public Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static public Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static public Lock vm_getLock(String name) {
return vm_generalMap_getOrCreate("Lock: " + name, new F0() {
public Lock get() {
try {
return lock();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return lock();";
}
});
}
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 File anonymousAIAlbumFile() {
return prepareFile(countTillNewFileOrKeep(newFile(aiImageAlbumDir(), ymd_minus_hms()), ".jpg"));
}
static public void saveJPEG(BufferedImage img, File file) {
saveJPG(img, file);
}
static public void saveJPEG(File file, BufferedImage img) {
saveJPG(img, file);
}
static public void saveJPEG(String path, BufferedImage img) {
saveJPG(img, newFile(path));
}
static public void fileSavedInfoBox(File f) {
infoBox("Saved " + fileInfo(f));
}
static public File copyFileToClipboard(File f) {
if (f == null)
return null;
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new FileTransferable(f), null);
vmBus_send("newClipboardContents", f);
return f;
}
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 JTextField jTextField() {
return jTextField("");
}
static public JTextField jTextField(final String text) {
return swing(new F0() {
public JTextField get() {
try {
JTextField tf = new JTextField(unnull(text));
standardTextFieldPopupMenu(tf);
jenableUndoRedo(tf);
tf.selectAll();
return tf;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JTextField tf = new JTextField(unnull(text));\r\n standardTextFieldPopupMenu...";
}
});
}
static public JTextField jTextField(Object o) {
return jTextField(strOrEmpty(o));
}
static public JDesktopPane mainDesktopPane_value;
static public JDesktopPane mainDesktopPane() {
return mainDesktopPane_value;
}
static public JPanel showInternalFrameFormTitled(final JDesktopPane desktop, final String title, final Object... _parts) {
JPanel panel = showForm_makePanel(true, _parts);
showForm_makeInternalFrame(desktop, title, panel);
return panel;
}
static public Object swing(Object f) {
return swingAndWait(f);
}
static public void swing(Runnable f) {
swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public IVF2 showForm_makeFrame;
static public void showForm_makeFrame(String title, JPanel panel) {
if (showForm_makeFrame != null)
showForm_makeFrame.get(title, panel);
else
showForm_makeFrame_base(title, panel);
}
final static public void showForm_makeFrame_fallback(IVF2 _f, String title, JPanel panel) {
if (_f != null)
_f.get(title, panel);
else
showForm_makeFrame_base(title, panel);
}
static public void showForm_makeFrame_base(String title, JPanel panel) {
handleEscapeKey(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400));
}
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 List showForm_arrange1(List> l) {
int minW = showForm_leftWidth(l);
List out = new ArrayList();
for (List row : l) out.add(westAndCenter(withRightMargin(showForm_gapBetweenColumns, jMinWidthAtLeast(minW, first(row))), second(row)));
return out;
}
static public List> showForm_makeComponents(final Boolean internalFrame, Object... _parts) {
List> l = new ArrayList();
List parts = asList(_parts);
JButton submitButton = null;
for (int i = 0; i < l(parts); i++) {
final Object o = parts.get(i), next = get(parts, i + 1);
if (o instanceof String && next instanceof Component)
setComponentID((Component) next, (String) o);
if (o instanceof Component || o instanceof String || next instanceof Component) {
l.add(mapLL(__35 -> wrapForSmartAdd_jComponent(__35), o == null ? new JPanel() : o instanceof String ? humanizeFormLabel((String) o) : o, next));
if (next instanceof JButton && submitButton == null)
submitButton = (JButton) next;
i++;
} else if (isRunnable(o))
l.add(mapLL(__36 -> wrapForSmartAdd_jComponent(__36), null, submitButton = jbutton(showFormSubmitButtonName(), new Runnable() {
public void run() {
try {
Object result = call(o);
print("Result of form runnable: " + result + ". Button: " + heldInstance(JButton.class));
if (neq(Boolean.FALSE, result)) {
if (isTrue(internalFrame))
disposeInternalFrame(heldInstance(JButton.class));
else if (isFalse(internalFrame))
disposeFrame(heldInstance(JButton.class));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Object result = call(o);\r\n print(\"Result of form runnable: \" + result ...";
}
})));
else
print("showForm: Unknown element type: " + getClassName(o));
}
if (submitButton != null) {
final JButton _submitButton = submitButton;
onEnterInAllTextFields(concatLists(l), new Runnable() {
public void run() {
try {
clickButton(_submitButton);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "clickButton(_submitButton)";
}
});
}
for (List row : l) {
JComponent left = first(row);
if (left instanceof JLabel)
makeBold((JLabel) left).setVerticalAlignment(JLabel.TOP);
}
return l;
}
static public int vstackWithSpacing_default = 10;
static public JPanel vstackWithSpacing(final List parts) {
return vstackWithSpacing(parts, vstackWithSpacing_default);
}
static public JPanel vstackWithSpacing(final List parts, final int spacing) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(spacing / 2, 0, (spacing + 1) / 2, 0);
smartAddWithLayout(panel, gbc, toObjectArray(nonNulls(parts)));
gbc.weighty = 1;
gbc.insets = new Insets(0, 0, 0, 0);
panel.add(jrigid(), gbc);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new GridBagLayout);\r\n new GridBagConstraints gbc...";
}
});
}
static public JPanel vstackWithSpacing(Component... parts) {
return vstackWithSpacing(asList(parts), vstackWithSpacing_default);
}
static public JPanel vstackWithSpacing(int spacing, Component... parts) {
return vstackWithSpacing(asList(parts), spacing);
}
static public boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static public String getTextTrim(JTextComponent c) {
return trim(getText(c));
}
static public String getTextTrim(JComboBox cb) {
return trim(getText(cb));
}
static public String getTextTrim(JComponent c) {
if (c instanceof JLabel)
return trim(((JLabel) c).getText());
if (c instanceof JComboBox)
return getTextTrim((JComboBox) c);
return getTextTrim((JTextComponent) c);
}
static public Map humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5");
static public String humanizeFormLabel(String s) {
if (containsSpace(s))
return s;
return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID"));
}
static public void internalFrameTitlePopupMenu(final JInternalFrame f, final Object... params) {
{
swing(() -> {
Object menuMaker;
if (l(params) == 1 && !(params[0] instanceof JMenu))
menuMaker = params[0];
else
menuMaker = new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItems(menu, params);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItems(menu, params)";
}
};
Component titleComponent = getInternalFrameTitlePaneComponent(f);
if (!(titleComponent instanceof JComponent))
print("Can't add internal frame title popup menu!");
else {
componentPopupMenu((JComponent) titleComponent, menuMaker);
setOpt(componentPopupMenu_initForComponent((JComponent) titleComponent), "internalFrameLeftButtonMagic", isTrue(vm_generalMap_get("internalFramePopupOnLeftButton")));
}
componentPopupMenu(f, menuMaker);
});
}
}
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 A _get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static public Object _get(Object o, String field) {
return get(o, field);
}
static public Object _get(String field, Object o) {
return get(o, field);
}
static public A _get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
static public Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
return x30_util.callF(f, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static public 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 A packInternalFrame(final A c) {
{
swing(() -> {
JInternalFrame w = getInternalFrame(c);
if (w != null) {
w.pack();
fixInternalFrame(w);
}
});
}
return c;
}
static public Container dm_frame() {
return dm_frame(dm_current_generic());
}
static public Container dm_frame(Object module) {
return (Container) getPossiblyInternalFrame(dm_vis(module));
}
static public JPanel jcenteredline(final Component... components) {
return swing(new F0() {
public JPanel get() {
try {
return jFullCenter(hstackWithSpacing(components));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return jFullCenter(hstackWithSpacing(components));";
}
});
}
static public JPanel jcenteredline(List extends Component> components) {
return jcenteredline(asArray(Component.class, components));
}
static public JButton jbutton(String text, Object action) {
return newButton(text, action);
}
static public JButton jbutton(String text) {
return newButton(text, null);
}
static public JButton jbutton(Action action) {
return swingNu(JButton.class, action);
}
static public List mapMethod(Object[] l, final String methodName) {
return map(l, new F1() {
public Object get(Object o) {
try {
return callOpt(o, methodName);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callOpt(o, methodName)";
}
});
}
static public List mapMethod(Iterable c, final String methodName) {
return map(c, new F1() {
public Object get(Object o) {
try {
return callOpt(o, methodName);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callOpt(o, methodName)";
}
});
}
static public List mapMethod(String methodName, Iterable c) {
return mapMethod(c, methodName);
}
static public List mapMethod(String methodName, Enumeration c) {
return mapMethod(methodName, enumerationToIterator(c));
}
static public String getName() {
return getProgramName();
}
static public String addToLocalMechList_uniq(String listName, String text) {
return addToLocalMechList_uniq(listName, lines(text));
}
static public String addToLocalMechList_uniq(String listName, Collection lines) {
List existing = tlft(localMechList_opt_raw_fresh(listName));
List newLines = listMinusSet(lines, existing);
if (empty(newLines))
return "No change";
appendToLocalMechList(listName, lines(newLines));
return n2(l(newLines), "line") + " added";
}
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 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 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 JComboBox jcombobox(final String... items) {
return swing(new F0() {
public JComboBox get() {
try {
return new JComboBox(items);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return new JComboBox(items);";
}
});
}
static public JComboBox jcombobox(Collection items) {
return jcombobox(toStringArray(items));
}
static public JComboBox jcombobox(Collection items, String selectedItem) {
return selectItem(selectedItem, jcombobox(items));
}
static public JComboBox selectItem(A item, JComboBox cb) {
if (cb != null) {
swing(() -> {
cb.setSelectedItem(item);
});
}
return cb;
}
static public JComboBox selectItem(JComboBox cb, A item) {
return selectItem(item, cb);
}
static public JList selectItem(JList list, A item) {
{
swing(() -> {
selectRow(list, jlist_indexOf(list, item));
});
}
return list;
}
static public String preferredWebCamName() {
return trim(loadTextFile(preferredWebCamFile()));
}
static public int getSelectedIndex(final JComboBox cb) {
return cb == null ? -1 : swing(new F0() {
public Integer get() {
try {
return cb.getSelectedIndex();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return cb.getSelectedIndex();";
}
});
}
static public int getSelectedIndex(final JList l) {
return l == null ? -1 : swing(new F0() {
public Integer get() {
try {
return l.getSelectedIndex();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return l.getSelectedIndex();";
}
});
}
static public JTextField onEnter(final JTextField tf, final Object action) {
if (action == null || tf == null)
return tf;
tf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
tf.selectAll();
callF(action);
} catch (Throwable __e) {
messageBox(__e);
}
}
});
return tf;
}
static public JButton onEnter(JButton btn, final Object action) {
if (action == null || btn == null)
return btn;
btn.addActionListener(actionListener(action));
return btn;
}
static public JList onEnter(JList list, Object action) {
list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
return list;
}
static public JComboBox onEnter(final JComboBox cb, final Object action) {
{
swing(() -> {
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(Object action, JTextField tf) {
return onEnter(tf, action);
}
static public A renameSubmitButton(A form, String newName) {
renameButton(form, showFormSubmitButtonName(), newName);
return form;
}
static public A renameSubmitButton(String newName, A form) {
return renameSubmitButton(form, newName);
}
static public JComponent showTitledForm(String title, Object... _parts) {
return showFormTitled(title, _parts);
}
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 String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
static public String loadTextFile(File f, String defaultContents) {
return loadTextFile(f, defaultContents, "UTF-8");
}
static public String loadTextFile(File f, String defaultContents, String encoding) {
try {
checkFileNotTooBigToRead(f);
if (f == null || !f.exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(f);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding);
return loadTextFile(inputStreamReader);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
static public String loadTextFile(String fileName, String defaultContents) {
return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
}
static public String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
} finally {
reader.close();
}
return str(builder);
}
static public File preferredWebCamFile() {
return javaxDataDir("preferred-web-cam.txt");
}
static public Webcam findWebCamByName(List cams, String name) {
if (empty(name))
return null;
for (Webcam cam : unnull(cams)) if (eqic(cam.getName(), name))
return cam;
return null;
}
static public boolean saveTextFileIfChanged(File f, String contents) {
return saveTextFileIfDifferent(f, contents);
}
static public JWindow infoBox(Object text) {
return infoMessage(strOrNull(text));
}
static public JWindow infoBox(String text) {
return infoMessage(text);
}
static public JWindow infoBox(String text, double seconds) {
return infoMessage(text, seconds);
}
static public JWindow infoBox(Throwable e) {
return infoMessage(e);
}
static public void setSCPComponent(SingleComponentPanel scp, Component c) {
if (scp != null)
scp.setComponent(c);
}
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 Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
Class c = get2(name);
return c;
}
public Class get2(String name) {
if (eq(name, ""))
return mc();
{
Class c = findClass_fullName(name);
if (c != null)
return c;
}
if (startsWithAny(name, "loadableUtils.utils$", "main$", mcDollar()))
for (String pkg : ll("loadableUtils.utils$", mcDollar())) {
String newName = pkg + afterDollar(name);
{
Class c = findClass_fullName(newName);
if (c != null)
return c;
}
}
return null;
}
};
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(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(MultiMap mm) {
return mm != null && !mm.isEmpty();
}
static public boolean nempty(Object o) {
return !empty(o);
}
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 programIDWithCase() {
return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID();
}
static public RootPaneContainer getPossiblyInternalFrame(Component c) {
JInternalFrame f = getInternalFrame(c);
if (f != null)
return f;
return optCast(RootPaneContainer.class, getWindow(c));
}
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 swingCall(final Object o, final String method, final Object... args) {
return swing(new F0() {
public Object get() {
try {
return call(o, method, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return call(o, method, args);";
}
});
}
static public void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static public void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
if (menu != null && menuItem != null)
menu.add(menuItem);
}
static public void addMenuItem(JMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static public void addMenuItem(Menu menu, String text, Object action) {
menu.add(menuItem(text, action));
}
static public void addMenuItem(JMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static public void addMenuItem(JMenuBar menuBar, String text, Runnable action) {
addMenuItem(menuBar, jmenuItem(text, action));
}
static public void addMenuItem(JMenuBar menuBar, JMenuItem menuItem) {
addDirectMenuItem(menuBar, menuItem);
}
static public String defaultThreadName_name;
static public String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static public Runnable wrapAsActivity(Object r) {
if (r == null)
return null;
Runnable r2 = toRunnable(r);
Object mod = dm_current_generic();
if (mod == null)
return r2;
return new Runnable() {
public void run() {
try {
AutoCloseable c = (AutoCloseable) (rcall("enter", mod));
AutoCloseable __1 = c;
try {
r2.run();
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable c = (AutoCloseable) (rcall enter(mod));\r\n temp c;\r\n r2.r...";
}
};
}
static public Thread newThread(Object runnable) {
return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)));
}
static public Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static public Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
static public Runnable toRunnable(final Object o) {
if (o instanceof Runnable)
return (Runnable) o;
if (o instanceof String)
throw fail("callF_legacy");
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
static public Map _registerThread_threads;
static public Object _onRegisterThread;
static public Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static public void _registerThread() {
_registerThread(Thread.currentThread());
}
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 volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal ping_isCleanUpThread = new ThreadLocal();
static public boolean ping() {
newPing();
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg);
pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static public Thread currentThread() {
return Thread.currentThread();
}
static public Map vm_threadInterruptionReasonsMap() {
return vm_generalWeakSubMap("Thread interruption reasons");
}
static volatile public StringBuffer local_log = new StringBuffer();
static public boolean printAlsoToSystemOut = true;
static volatile public Appendable print_log = local_log;
static volatile public int print_log_max = 1024 * 1024;
static volatile public int local_log_max = 100 * 1024;
static public boolean print_silent = false;
static public Object print_byThread_lock = new Object();
static volatile public ThreadLocal print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print(combinePrintParameters(s, o));
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = o + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
try {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
} catch (Throwable e) {
System.out.println(getStackTrace(e));
}
print_raw(s);
}
static public void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
if (printAlsoToSystemOut)
System.out.print(s);
vmBus_send("printed", mc(), s);
}
static public void print_autoRotate() {
}
static public String strOr(Object o, String ifNull) {
return o == null ? ifNull : str(o);
}
static public A printStackTrace(A e) {
if (e != null)
print(getStackTrace(e));
return e;
}
static public void printStackTrace() {
printStackTrace(new Throwable());
}
static public void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static public void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static public void lockOrFail(Lock lock, long timeout) {
try {
ping();
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 File prepareFile(File file) {
return mkdirsForFile(file);
}
static public File prepareFile(File dir, String name) {
return mkdirsForFile(newFile(dir, name));
}
static public File countTillNewFileOrKeep(File base) {
return countTillNewFileOrKeep(base, "");
}
static public File countTillNewFileOrKeep(File base, String suffix) {
File f = newFile(f2s(base) + suffix);
long i = 1;
while (f.exists()) f = newFile(f2s(base) + ++i + suffix);
return f;
}
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 File aiImageAlbumDir() {
return javaxDataDir("AI Image Album");
}
static public String ymd_minus_hms() {
return ymd() + "-" + hms();
}
static public void saveJPG(BufferedImage img, File file) {
try {
if (!ImageIO.write(img, "jpeg", mkdirsFor(file))) {
print("Reconstructing image for saving JPEG");
img = reconstructBufferedImage(img);
if (!ImageIO.write(img, "jpeg", file))
throw fail("Couldn't write JPEG: " + file + " (" + img + ")");
}
vmBus_send("wroteFile", file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void saveJPG(File file, BufferedImage img) {
try {
saveJPG(img, file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String fileInfo(File f) {
return renderFileInfo(f);
}
static public String fileInfo(String f) {
return renderFileInfo(newFile(f));
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public int[] unnull(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnull(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnull(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnull(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public int unnull(Integer i) {
return i == null ? 0 : i;
}
static public long unnull(Long l) {
return l == null ? 0L : l;
}
static public double unnull(Double l) {
return l == null ? 0.0 : l;
}
static public JTextField standardTextFieldPopupMenu(final JTextField tf) {
final WeakReference ref = weakRef(tf);
componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() {
public void run() {
try {
copyTextToClipboard(ref.get().getText());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyTextToClipboard(ref.get().getText())";
}
});
componentPopupMenuItem(tf, "Paste", new Runnable() {
public void run() {
try {
ref.get().paste();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ref.get().paste()";
}
});
return tf;
}
static public A jenableUndoRedo(final A textcomp) {
{
swing(() -> {
final UndoManager undo = new UndoManager();
vm_generalWeakSet("Undo Managers").add(undo);
textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() {
public void run() {
try {
if (undo.canUndo())
undo.undo();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (undo.canUndo()) undo.undo()";
}
}));
textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() {
public void run() {
try {
if (undo.canRedo())
undo.redo();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (undo.canRedo()) undo.redo()";
}
}));
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
});
}
return textcomp;
}
static public String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static public JInternalFrame showForm_makeInternalFrame(JDesktopPane desktop, String title, JPanel panel) {
JInternalFrame f = addInternalFrame(desktop, title, withMargin(panel));
minInternalFrameWidth(f, 400);
packInternalFrameVertically(f);
centerInternalFrame(f);
return f;
}
static public void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
static public JFrame handleEscapeKey(final JFrame frame) {
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
frame.getRootPane().registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
frame.dispose();
}
}, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
return frame;
}
static public JFrame minFrameWidth(JFrame frame, int w) {
if (frame != null && frame.getWidth() < w)
frame.setSize(w, frame.getHeight());
return frame;
}
static public JFrame minFrameWidth(int w, JFrame frame) {
return minFrameWidth(frame, w);
}
static public JFrame showPackedFrame(String title, Component contents) {
return packFrame(showFrame(title, contents));
}
static public JFrame showPackedFrame(Component contents) {
return packFrame(showFrame(contents));
}
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 List buttonsInGroup(ButtonGroup g) {
if (g == null)
return ll();
return asList(g.getElements());
}
static public int showForm_leftWidth_safetyMargin = 10;
static public int showForm_leftWidth(List> l) {
forEachLevel2(l, x -> vmBus_send("updateLayoutNow", x));
int minW = 0;
for (List row : l) minW = max(minW, getMinimumSize(first(row)).width);
return minW + or((Integer) vmBus_query("formSafetyMargin"), showForm_leftWidth_safetyMargin);
}
static public JPanel westAndCenter(final Component w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.WEST, wrap(w));
panel.add(BorderLayout.CENTER, wrap(c));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST...";
}
});
}
static public int withRightMargin_defaultWidth = 6;
static public JPanel withRightMargin(Component c) {
return withRightMargin(withRightMargin_defaultWidth, c);
}
static public JPanel withRightMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = marginPanel();
p.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, w));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = marginPanel();\r\n p.setBorder(BorderFactory.createEmptyBorder(0,...";
}
});
}
static public A jMinWidthAtLeast(int w, final A c) {
if (c == null)
return null;
return swing(new F0 () {
public A get() {
try {
Dimension size = c.getMinimumSize();
Dimension d = new Dimension(max(w, size.width), size.height);
c.setMinimumSize(d);
return jPreferWidth(d.width, c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Dimension size = c.getMinimumSize();\r\n Dimension d = new Dimension(max(w, ...";
}
});
}
static public A second(List l) {
return get(l, 1);
}
static public A second(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
if (!it.hasNext())
return null;
it.next();
return it.hasNext() ? it.next() : null;
}
static public A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static public B second(Pair p) {
return p == null ? null : p.b;
}
static public char second(String s) {
return charAt(s, 1);
}
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(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static public void setComponentID(Component c, String id) {
if (c != null)
componentID_map.put(c, id);
}
static public List mapLL(Object f, Object... data) {
return map(f, ll(data));
}
static public List mapLL(IF1 f, A... data) {
return map(f, ll(data));
}
static public JComponent wrapForSmartAdd_jComponent(Object o) {
return componentToJComponent(wrapForSmartAdd(o));
}
static public boolean isRunnable(Object o) {
return o instanceof Runnable || hasMethod(o, "get");
}
static public String showFormSubmitButtonName() {
return "Submit";
}
static public A heldInstance(Class c) {
List l = holdInstance_l.get();
for (int i = l(l) - 1; i >= 0; i--) {
Object o = l.get(i);
if (isInstanceOf(o, c))
return (A) o;
}
throw fail("No instance of " + className(c) + " held");
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public void disposeInternalFrame(Component c) {
final JInternalFrame f = getInternalFrame(c);
if (f != null) {
swing(() -> {
vmBus_send("disposingInternalFrame", f);
f.dispose();
});
}
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
static public void disposeFrame(final Component c) {
disposeWindow(c);
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public void onEnterInAllTextFields(JComponent c, Object action) {
if (action == null)
return;
for (Component tf : allChildren(c)) onEnterIfTextField(tf, action);
}
static public void onEnterInAllTextFields(List c, Object action) {
for (Object o : unnull(c)) if (o instanceof JComponent)
onEnterInAllTextFields((JComponent) o, action);
}
static public List concatLists(Iterable ... lists) {
List l = new ArrayList();
if (lists != null)
for (Iterable list : lists) addAll(l, list);
return l;
}
static public List concatLists(Collection extends Iterable > lists) {
List l = new ArrayList();
if (lists != null)
for (Iterable list : lists) addAll(l, list);
return l;
}
static public void clickButton(final JButton b) {
if (b != null) {
swing(() -> {
if (b.isEnabled())
b.doClick();
});
}
}
static public A makeBold(final A c) {
if (c != null) {
swing(() -> {
c.setFont(c.getFont().deriveFont(java.awt.Font.BOLD));
});
}
return c;
}
static public JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
for (Object o : parts) panel.add(wrapForSmartAdd(o), layout);
return panel;
}
static public JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
return smartAddWithLayout(panel, layout, asList(flattenArray2(parts)));
}
static public Object[] toObjectArray(Collection c) {
return toObjectArray((Iterable) c);
}
static public Object[] toObjectArray(Iterable c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static public List nonNulls(Iterable l) {
return withoutNulls(l);
}
static public List nonNulls(A[] l) {
return withoutNulls(l);
}
static public Map nonNulls(Map map) {
return withoutNulls(map);
}
static public Component jrigid() {
return javax.swing.Box.createRigidArea(new Dimension(0, 0));
}
static public String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return c.getText();";
}
});
}
static public String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return c.getText();";
}
});
}
static public String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return l.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return l.getText();";
}
});
}
static public String getText(final JComboBox cb) {
if (cb == null)
return null;
if (isEditableComboBox(cb))
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
static public HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static public void litmap_impl(Map map, Object... x) {
if (x != null)
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
static public boolean containsSpace(String s) {
return containsSpaces(s);
}
static public String firstToUpper(String s) {
if (empty(s))
return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
static public String joinWithSpace(Iterable c) {
return join(" ", c);
}
static public String joinWithSpace(String... c) {
return join(" ", c);
}
static public List replaceElementsUsingMap(Iterable l, final Map map) {
return map(l, new F1 () {
public A get(A a) {
try {
return getOrKeep(map, a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "getOrKeep(map, a)";
}
});
}
static public List splitCamelCase(String s) {
return ai_splitCamelCase(s);
}
static public void addMenuItems(JMenu m, Object... x) {
fillJMenu(m, x);
}
static public void addMenuItems(JPopupMenu m, Object... x) {
fillJPopupMenu(m, x);
}
static public JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) {
return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane");
}
static public Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
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 boolean isChecked(JCheckBox checkBox) {
return checkBox != null && (boolean) swing(new F0() {
public Boolean get() {
try {
return checkBox.isSelected();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return checkBox.isSelected();";
}
});
}
static public boolean isChecked(JCheckBoxMenuItem mi) {
return mi != null && (boolean) swing(new F0() {
public Boolean get() {
try {
return mi.isSelected();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return mi.isSelected();";
}
});
}
static public boolean isChecked(JRadioButton rb) {
return rb != null && (boolean) swing(() -> rb.isSelected());
}
static public Class mc() {
return main.class;
}
static public Object call_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static 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 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 int fixInternalFrame_borderTopLeft = 0;
static public int fixInternalFrame_borderBottomRight = 40;
static public JInternalFrame fixInternalFrame(final JInternalFrame f) {
return swing(new F0() {
public JInternalFrame get() {
try {
Container c = f.getParent();
if (c == null)
return f;
Rect r = toRect(f.getBounds());
int a = fixInternalFrame_borderTopLeft, b = fixInternalFrame_borderBottomRight;
Rect outer = new Rect(a, a, c.getWidth() - b, c.getHeight() - b);
if (!rectContains(outer, r))
f.setLocation(max(a, min(r.x, outer.x2())), max(a, min(r.y, outer.y2())));
if (r.w > c.getWidth() || r.h > c.getHeight())
f.setSize(c.getWidth() - a, c.getHeight() - a);
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Container c = f.getParent();\r\n if (c == null) ret f;\r\n Rect r = toRect(...";
}
});
}
static public JComponent dm_vis(Object module) {
return dm_getVisualization(module);
}
static public JComponent dm_vis() {
return dm_getVisualization();
}
static public JPanel jFullCenter(final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(c);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new GridBagLayout);\r\n panel.add(c);\r\n ret panel;";
}
});
}
static public int hstackWithSpacing_spacing = 10;
static public JPanel hstackWithSpacing(Object... parts) {
parts = flattenArray2(parts);
int spacing = hstackWithSpacing_spacing;
int i = 0;
if (first(parts) instanceof Integer) {
spacing = toInt(first(parts));
++i;
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.gridheight = GridBagConstraints.REMAINDER;
for (; i < l(parts); i++) {
if (i != 0)
panel.add(javax.swing.Box.createRigidArea(new Dimension(spacing, 0)), gbc);
panel.add(wrapForSmartAdd(parts[i]), gbc);
}
gbc.weightx = 1;
panel.add(jrigid(), gbc);
return panel;
}
static public Object[] asArray(List l) {
return toObjectArray(l);
}
static public A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static public boolean 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);
final JButton btn = new JButton(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 final JButton btn = new JButt...";
}
});
}
static public A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
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(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(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
ping();
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static public 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 IterableIterator enumerationToIterator(final Enumeration e) {
return e == null ? null : new IterableIterator() {
public boolean hasNext() {
return e.hasMoreElements();
}
public A next() {
return e.nextElement();
}
};
}
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 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 List tlft(String s) {
return toLinesFullTrim(s);
}
static public List tlft(File f) {
return toLinesFullTrim(f);
}
static public String localMechList_opt_raw_fresh(String name) {
return unnull(loadTextFile(localMechListFile(name)));
}
static public List listMinusSet(Iterable l, Collection extends A> stuff) {
if (l == null)
return null;
if (empty(stuff))
return asList(l);
Set extends A> set = asSet(stuff);
List l2 = new ArrayList();
for (A a : l) if (!set.contains(a))
l2.add(a);
return l2;
}
static public List listMinusSet(Iterable l, Collection stuff, Collection extends A> stuff2) {
return listMinusSet(listMinusSet(l, stuff), stuff2);
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean empty(Iterable c) {
return c == null || !c.iterator().hasNext();
}
static public boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean empty(Map map) {
return map == null || map.isEmpty();
}
static public boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static public boolean empty(BitSet bs) {
return bs == null || bs.isEmpty();
}
static public boolean empty(Object o) {
if (o instanceof Collection)
return empty((Collection) o);
if (o instanceof String)
return empty((String) o);
if (o instanceof Map)
return empty((Map) o);
if (o instanceof Object[])
return empty((Object[]) o);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static public boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
static public boolean empty(double[] a) {
return a == null || a.length == 0;
}
static public boolean empty(float[] a) {
return a == null || a.length == 0;
}
static public boolean empty(int[] a) {
return a == null || a.length == 0;
}
static public boolean empty(long[] a) {
return a == null || a.length == 0;
}
static public boolean empty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean empty(short[] a) {
return a == null || a.length == 0;
}
static public boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
static public boolean empty(MultiMap mm) {
return mm == null || mm.isEmpty();
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public boolean empty(Rect r) {
return !(r != null && r.w != 0 && r.h != 0);
}
static public void appendToLocalMechList(String listName, String text) {
logMechListAppendLocally(listName, text);
}
static public String n2(long l) {
return formatWithThousands(l);
}
static public String n2(AtomicLong l) {
return n2(l.get());
}
static public String n2(Collection l) {
return n2(l(l));
}
static public String n2(Map map) {
return n2(l(map));
}
static public String n2(double l, String singular) {
return empty(singular) ? str(l) : n2(l, singular, singular + "s");
}
static public String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static public String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(long l, String singular) {
return empty(singular) ? n2(l) : n_fancy2(l, singular, singular + "s");
}
static public String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static public String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static public String n2(Map m, String singular) {
return n2(l(m), singular);
}
static public String n2(long[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
static public String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static public 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 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 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 Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
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 String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++) a[i] = it.next();
return a;
}
static public String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
static public void selectRow(final JTable table, final int i) {
if (table != null) {
swing(() -> {
if (i >= 0 && i < table.getRowCount()) {
table.setRowSelectionInterval(i, i);
scrollRowToVisible(table, i);
} else
table.clearSelection();
});
}
}
static public void selectRow(final JList list, final int i) {
if (list != null) {
swing(() -> {
if (i >= 0 && i < listRowCount(list))
list.setSelectedIndex(i);
else
list.clearSelection();
});
}
}
static public int jlist_indexOf(JList list, A item) {
return swing(new F0() {
public Integer get() {
try {
ListModel model = list.getModel();
int n = model.getSize();
for (int i = 0; i < n; i++) if (eq(model.getElementAt(i), item))
return i;
return -1;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ListModel model = list.getModel();\r\n int n = model.getSize();\r\n for ...";
}
});
}
static public void messageBox(final String msg) {
if (headless())
print(msg);
else {
swing(() -> {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
});
}
}
static public void messageBox(Throwable e) {
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
static public KeyListener enterKeyListener(final Object action) {
return new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER)
pcallF(action);
}
};
}
static public Runnable rCallOnSelectedListItem(final JList list, final Object action) {
return new Runnable() {
public void run() {
try {
pcallF(action, getSelectedItem(list));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcallF(action, getSelectedItem(list))";
}
};
}
static public AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
static public JButton renameButton(JComponent c, String name) {
JButton b = first(childrenOfType(c, JButton.class));
if (b != null)
b.setText(name);
return b;
}
static public JButton renameButton(JComponent c, String oldName, String newName) {
JButton b = findButton(c, oldName);
if (b != null)
b.setText(newName);
return b;
}
static public ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal();
static public void checkFileNotTooBigToRead(File f) {
callF(checkFileNotTooBigToRead_tl.get(), f);
}
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 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 boolean saveTextFileIfDifferent(File f, String contents) {
if (eq(loadTextFile(f), contents))
return false;
{
saveTextFile(f, contents);
return true;
}
}
static public boolean infoMessage_alwaysOnTop = true;
static public double infoMessage_defaultTime = 5.0;
static public JWindow infoMessage(String text) {
return infoMessage(text, infoMessage_defaultTime);
}
static public JWindow infoMessage(final String text, final double seconds) {
printHidingCredentials(text);
return infoMessage_noprint(text, seconds);
}
static public JWindow infoMessage_noprint(String text) {
return infoMessage_noprint(text, infoMessage_defaultTime);
}
static public JWindow infoMessage_noprint(final String _text, final double seconds) {
final String text = hideCredentials(_text);
if (empty(text))
return null;
logQuotedWithDate(infoBoxesLogFile(), text);
if (isHeadless())
return null;
return (JWindow) swingAndWait(new F0() {
public Object get() {
try {
JWindow window = makeWindow(infoMessage_makePanel(text));
window.setSize(300, 150);
moveToTopRightCorner(window);
if (infoMessage_alwaysOnTop)
window.setAlwaysOnTop(true);
if (vmBus_noObjections("shouldShowInfoBox", window, text))
window.setVisible(true);
if (seconds != 0)
disposeWindowAfter(iround(seconds * 1000), window);
return window;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JWindow window = makeWindow(infoMessage_makePanel(text));\r\n window.setSize...";
}
});
}
static public JWindow infoMessage(Throwable e) {
printStackTrace(e);
return infoMessage(exceptionToStringShort(e));
}
static public String strOrNull(Object o) {
return o == null ? null : str(o);
}
static public void _onJavaXSet() {
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public Map componentID_map = weakHashMap();
static public String componentID(Component c) {
return c == null ? null : componentID_map.get(c);
}
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 Object get2(Object o, String field1, String field2) {
return get(get(o, field1), field2);
}
static public boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public boolean eq(Symbol a, String b) {
return eq(str(a), b);
}
static public boolean startsWithAny(String a, Collection b) {
for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix))
return true;
return false;
}
static public boolean startsWithAny(String a, String... b) {
if (b != null)
for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix))
return true;
return false;
}
static public boolean startsWithAny(String a, Collection b, Matches m) {
for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix, m))
return true;
return false;
}
static public String mcDollar() {
return mcName() + "$";
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static public String afterDollar(String s) {
return substring(s, smartIndexOf(s, '$') + 1);
}
static volatile public String caseID_caseID;
static public String caseID() {
return caseID_caseID;
}
static public void caseID(String id) {
caseID_caseID = id;
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public String quoteUnlessIdentifierOrInteger(String s) {
return quoteIfNotIdentifierOrInteger(s);
}
static public A optCast(Class c, Object o) {
return isInstance(c, o) ? (A) o : null;
}
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 boolean jmenuItem_newThreads = false;
static public JMenuItem jmenuItem(final String text) {
return jMenuItem(text, null);
}
static public JMenuItem jmenuItem(final String text, final Object r) {
return swing(new F0() {
public JMenuItem get() {
try {
Pair p = jmenu_autoMnemonic(dropPrefix("[disabled] ", text));
JMenuItem mi = new JMenuItem(p.a);
if (startsWith(text, "[disabled] "))
disableMenuItem(mi);
if (p.b != 0)
mi.setMnemonic(p.b);
mi.addActionListener(jmenuItem_newThreads ? actionListenerInNewThread(r) : actionListener(r));
return mi;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Pair p = jmenu_autoMnemonic(dropPrefix(\"[disabled] \", text));\r\n JM...";
}
});
}
static public MenuItem menuItem(String text, final Object r) {
MenuItem mi = new MenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
static public void addDirectMenuItem(JMenuBar mb, String text, Object action) {
if (mb != null) {
swing(() -> {
addDirectMenuItem(mb, directJMenuItem(text, action));
});
}
}
static public void addDirectMenuItem(Component c, String text, Object action) {
addDirectMenuItem(addMenuBar(c), text, action);
}
static public void addDirectMenuItem(JMenuBar mb, JMenuItem menuItem) {
if (mb != null) {
swing(() -> {
mb.add(menuItem);
revalidate(mb);
});
}
}
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();
if (info == null && mod == null)
return r;
return 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 r....";
}
};
}
static public RuntimeException fail() {
throw new RuntimeException("fail");
}
static public RuntimeException fail(Throwable e) {
throw asRuntimeException(e);
}
static public RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static public RuntimeException fail(Object... objects) {
throw new Fail(objects);
}
static public RuntimeException fail(String msg) {
throw new RuntimeException(msg == null ? "" : msg);
}
static public RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
static public WeakReference weakRef(A a) {
return newWeakReference(a);
}
static public IF0 f0ToIF0(F0 f) {
return f == null ? null : () -> f.get();
}
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 Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static public void newPing() {
var tl = newPing_actionTL();
Runnable action = tl == null ? null : tl.get();
{
if (action != null)
action.run();
}
}
static public boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
static public boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static public void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static public Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public void pcallFAll_minimalExceptionHandling(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
ping();
pcallF_minimalExceptionHandling(f, args);
}
}
static public void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) {
while (it.hasNext()) {
ping();
pcallF_minimalExceptionHandling(it.next(), args);
}
}
static public Set vm_busListeners_live_cache;
static public Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
static public Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static public Map vm_busListenersByMessage_live_cache;
static public Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
static public Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public String combinePrintParameters(String s, Object o) {
return (endsWithLetterOrDigit(s) ? s + ": " : s) + o;
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static public Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static public A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static public A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static public String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static public String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static public String getStackTrace(String msg) {
return getStackTrace_noRecord(new Throwable(msg));
}
static public String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
static public void print_append(Appendable buf, String s, int max) {
try {
synchronized (buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 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 String ymd() {
return ymd(now());
}
static public String ymd(long now) {
return year(now) + formatInt(month(now), 2) + formatInt(dayOfMonth(now), 2);
}
static public String ymd(long now, TimeZone tz) {
return year(now, tz) + formatInt(month(now, tz), 2) + formatInt(dayOfMonth(now, tz), 2);
}
static public String hms() {
return hms(now());
}
static public String hms(long time) {
return new SimpleDateFormat("HHmmss").format(time);
}
public static File mkdirsFor(File file) {
return mkdirsForFile(file);
}
static public BufferedImage reconstructBufferedImage(BufferedImage img) {
if (img == null)
return null;
RGBImage rgb = new RGBImage(img);
rgb.uncacheBufferedImage();
return rgb.getBufferedImage();
}
static public String renderFileInfo(File f) {
return f == null ? "-" : f2s(f) + " " + (f.isFile() ? "(file, " + n2(fileSize(f)) + " bytes)" : f.isDirectory() ? "(dir)" : "(not found)");
}
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 A componentPopupMenuItem(A c, final String name, final Object action) {
componentPopupMenu(c, new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, name, action);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, name, action);";
}
});
return c;
}
static public void componentPopupMenuItem(JComponent c, final JMenuItem menuItem) {
componentPopupMenu(c, new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, menuItem);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, menuItem);";
}
});
}
static public String copyTextToClipboard(Object _text) {
String text = str(_text);
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
vmBus_send("newClipboardContents", text);
return text;
}
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 ThreadLocal addInternalFrame_dontSelect = new ThreadLocal();
static public ThreadLocal addInternalFrame_layer = new ThreadLocal();
static public ThreadLocal addInternalFrame_toBack = new ThreadLocal();
static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h) {
return addInternalFrame(desktop, title, x, y, w, h, null);
}
static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h, final Component contents) {
return addInternalFrame(desktop, title, rect(x, y, w, h), contents);
}
static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Component contents) {
return addInternalFrame(desktop, title, null, contents);
}
static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Rect r, final Component contents) {
final boolean dontSelect = isTrue(optParam(addInternalFrame_dontSelect));
final boolean toBack = isTrue(optParam(addInternalFrame_toBack));
final Integer layer = optParam(addInternalFrame_layer);
return swing(new F0() {
public JInternalFrame get() {
try {
JInternalFrame frame;
if (contents instanceof JInternalFrame)
frame = (JInternalFrame) contents;
else {
frame = jInternalFrame(title);
setInternalFrameContents(frame, contents);
}
frame.setVisible(true);
desktop.add(frame, layer);
if (r != null)
setBounds(frame, r);
else
internalFrameDefaultPosition(frame);
if (dontSelect)
if (toBack)
frame.toBack();
else
frame.toFront();
else
frame.setSelected(true);
return fixInternalFrame(frame);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JInternalFrame frame;\r\n if (contents instanceof JInternalFrame)\r\n fra...";
}
});
}
static public JInternalFrame addInternalFrame(JDesktopPane desktop, String title) {
return addInternalFrame(desktop, title, jpanel());
}
static public JInternalFrame minInternalFrameWidth(final JInternalFrame frame, final int w) {
{
swing(() -> {
if (frame != null && frame.getWidth() < w)
frame.setSize(w, frame.getHeight());
});
}
return frame;
}
static public JInternalFrame minInternalFrameWidth(int w, JInternalFrame frame) {
return minInternalFrameWidth(frame, w);
}
static public A packInternalFrameVertically(A c) {
return packInternalFrameVertically(-1, c);
}
static public A packInternalFrameVertically(int width, A c) {
final JInternalFrame win = getInternalFrame(c);
if (win == null)
return c;
final int w = width < 0 ? win.getWidth() : width;
{
swing(() -> {
win.pack();
win.setSize(w, win.getHeight());
fixInternalFrame(win);
});
}
return c;
}
static public JInternalFrame centerInternalFrame(final JInternalFrame f) {
{
swing(() -> {
Container c = f.getParent();
if (c != null) {
f.setLocation((c.getWidth() - f.getWidth()) / 2, (c.getHeight() - f.getHeight()) / 2);
}
});
}
return f;
}
static public JInternalFrame centerInternalFrame(final int w, final int h, final JInternalFrame f) {
{
swing(() -> {
f.setSize(w, h);
});
}
return centerInternalFrame(f);
}
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 int packFrame_minw = 150, packFrame_minh = 50;
static public A packFrame(final A c) {
{
swing(() -> {
Window w = getWindow(c);
if (w != null) {
w.pack();
int maxW = getScreenWidth() - 50, maxH = getScreenHeight() - 50;
w.setSize(min(maxW, max(w.getWidth(), packFrame_minw)), min(maxH, max(w.getHeight(), packFrame_minh)));
}
});
}
return c;
}
static public JFrame packFrame(ButtonGroup g) {
return packFrame(getFrame(g));
}
static public JFrame showFrame() {
return makeFrame();
}
static public JFrame showFrame(Object content) {
return makeFrame(content);
}
static public JFrame showFrame(String title) {
return makeFrame(title);
}
static public JFrame showFrame(String title, Object content) {
return makeFrame(title, content);
}
static public JFrame showFrame(final JFrame f) {
if (f != null) {
swing(() -> {
if (frameTooSmall(f))
frameStandardSize(f);
if (!f.isVisible())
f.setVisible(true);
if (f.getState() == Frame.ICONIFIED)
f.setState(Frame.NORMAL);
});
}
return f;
}
static public JFrame showFrame(String title, Object content, JFrame frame) {
if (frame == null)
return showFrame(title, content);
else {
frame.setTitle(title);
setFrameContents(frame, content);
return frame;
}
}
static public JPanel marginPanel() {
return jtransparent(borderLayoutPanel());
}
static public > void forEachLevel2(Iterable l, IVF1 f) {
if (l != null)
for (B b : l) forEach(b, f);
}
static public > void forEachLevel2(IVF1 f, Iterable l) {
forEachLevel2(f, l);
}
static public Dimension getMinimumSize(final Component c) {
return c == null ? null : swing(new F0() {
public Dimension get() {
try {
return c.getMinimumSize();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return c.getMinimumSize();";
}
});
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static public Object vmBus_query(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
{
Object __1 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg);
if (__1 != null)
return __1;
}
return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public Object vmBus_query(String msg) {
return vmBus_query(msg, (Object) null);
}
static public JComponent wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
static public JComponent wrap_2(Object swingable) {
if (swingable == null)
return null;
JComponent c;
if (swingable instanceof Component)
c = componentToJComponent((Component) swingable);
else
c = componentToJComponent((Component) callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
static public A jPreferWidth(int w, A c) {
Dimension size = c.getPreferredSize();
c.setPreferredSize(new Dimension(w, size.height));
return c;
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public char charAt(String s, int i) {
return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
}
static public JComponent componentToJComponent(Component c) {
if (c instanceof JComponent)
return (JComponent) c;
if (c instanceof JFrame)
return ((JFrame) c).getRootPane();
if (c == null)
return null;
throw fail("boohoo " + getClassName(c));
}
static public Component wrapForSmartAdd(Object o) {
if (o == null)
return jpanel();
if (o instanceof String)
return jlabel((String) o);
return wrap(o);
}
static public boolean hasMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args) != null;
}
static public boolean isInstanceOf(Object o, Class type) {
return type.isInstance(o);
}
static public String className(Object o) {
return getClassName(o);
}
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 List allChildren(Component c) {
return childrenOfType(c, Component.class);
}
static public void onEnterIfTextField(Component c, Object action) {
if (action == null)
return;
if (c instanceof JTextField)
onEnter((JTextField) c, action);
else if (c instanceof JComboBox)
onEnter((JComboBox) c, action);
}
static public void addAll(Collection c, Iterable b) {
if (c != null && b != null)
for (A a : b) c.add(a);
}
static public boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static public boolean addAll(Collection c, B... b) {
return c != null && b != null && c.addAll(Arrays.asList(b));
}
static public Map addAll(Map a, Map extends A, ? extends B> b) {
if (a != null && b != null)
a.putAll(b);
return a;
}
static public Object[] flattenArray2(Object... a) {
List l = new ArrayList();
if (a != null)
for (Object x : a) if (x instanceof Object[])
l.addAll(asList((Object[]) x));
else if (x instanceof Collection)
l.addAll((Collection) x);
else
l.add(x);
return asObjectArray(l);
}
static public List withoutNulls(Iterable l) {
if (l instanceof List)
if (!containsNulls((List) l))
return ((List) l);
List l2 = new ArrayList();
for (A a : l) if (a != null)
l2.add(a);
return l2;
}
static public Map withoutNulls(Map map) {
Map map2 = similarEmptyMap(map);
for (A a : keys(map)) if (a != null) {
B b = map.get(a);
if (b != null)
map2.put(a, b);
}
return map2;
}
static public List withoutNulls(A[] l) {
List l2 = new ArrayList();
if (l != null)
for (A a : l) if (a != null)
l2.add(a);
return l2;
}
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 boolean containsSpaces(String s) {
return indexOf(s, ' ') >= 0;
}
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 A getOrKeep(Map map, A a) {
if (map == null)
return a;
A v = map.get(a);
return v != null ? v : a;
}
static public List ai_splitCamelCase(String s) {
int j = 0;
List l = new ArrayList();
if (isAllUpperCase(s)) {
l.add(s);
return l;
}
for (int i = 0; i < l(s); i++) if (i > j && isUpperCaseLetter(s.charAt(i))) {
l.add(substring(s, j, i));
j = i;
}
if (j < l(s))
l.add(substring(s, j));
return l;
}
static public void fillJMenu(final JMenu m, Object... x) {
if (x == null)
return;
for (int i = 0; i < l(x); i++) {
Object o = x[i], y = get(x, i + 1);
if (o instanceof List)
fillJMenu(m, asArray((List) o));
else if (isMenuSeparatorIndicator(o)) {
if (menuItemCount(m) != 0)
m.addSeparator();
} else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) {
final LiveValue lv = (LiveValue) o;
final JMenuItem mi = jmenuItem(or2(unCurlyBracket(lv.get()), "..."), y);
bindLiveValueListenerToComponent(mi, lv, new Runnable() {
public void run() {
try {
String s = lv.get();
if (isCurlyBracketed(s)) {
setEnabled(mi, false);
s = unCurlyBracket(s);
} else
setEnabled(mi, true);
setText(mi, s);
revalidate(m);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "String s = lv!;\r\n if (isCurlyBracketed(s)) {\r\n setEnabled(mi,...";
}
});
print("bound live value " + lv + " to menu item " + mi);
m.add(mi);
++i;
} else if (o instanceof String && isRunnableX(y)) {
m.add(jmenuItem((String) o, y));
++i;
} else if (o instanceof JMenuItem)
m.add((JMenuItem) o);
else if (o instanceof String || o instanceof Action || o instanceof Component)
call(m, "add", o);
else if (o == null && y instanceof Runnable)
++i;
else if (o != null)
print("Unknown menu item: " + o);
}
}
static public void fillJPopupMenu(JPopupMenu m, Object... x) {
if (x == null)
return;
for (int i = 0; i < l(x); i++) {
Object o = x[i], y = get(x, i + 1);
if (o instanceof IVF1)
callF(o, m);
else if (o instanceof List)
fillJPopupMenu(m, asArray((List) o));
else if (isMenuSeparatorIndicator(o))
m.addSeparator();
else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) {
final LiveValue lv = (LiveValue) o;
final JMenuItem mi = jmenuItem("", y);
bindLiveValueListenerToComponent(mi, lv, new Runnable() {
public void run() {
try {
String s = lv.get();
if (isCurlyBracketed(s)) {
setEnabled(mi, false);
s = unCurlyBracket(s);
} else
setEnabled(mi, true);
setText(mi, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "String s = lv!;\r\n if (isCurlyBracketed(s)) {\r\n setEnabled(mi,...";
}
});
m.add(mi);
} else if (o instanceof String && isRunnableX(y)) {
m.add(jmenuItem((String) o, y));
++i;
} else if (o instanceof JMenuItem)
m.add((JMenuItem) o);
else if (o instanceof String || o instanceof Action || o instanceof Component)
call(m, "add", o);
else if (o != null)
print("Unknown menu item: " + o);
}
}
static public Component childWithClassNameEndingWith(Component c, String suffix) {
if (endsWith(className(c), suffix))
return c;
Component x;
for (Component comp : getComponents(c)) if ((x = childWithClassNameEndingWith(comp, suffix)) != null)
return x;
return null;
}
static 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 invokeMethod(Method m, Object o, Object... args) {
try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static public Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = args.length;
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs - n);
arraycopy(args, n, varArgs, 0, nArgs - n);
newArgs[n] = varArgs;
return newArgs;
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(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 List classNames(Collection l) {
return getClassNames(l);
}
static public List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
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 Rect toRect(Rectangle r) {
return r == null ? null : new Rect(r);
}
static public Rect toRect(RectangularShape r) {
return r == null ? null : toRect(r.getBounds());
}
static public Rect toRect(Rect r) {
return r;
}
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 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 JComponent dm_getVisualization(Object module) {
return (JComponent) callOpt(dm_getStem(module), "vis");
}
static public JComponent dm_getVisualization() {
return dm_getVisualization(dm_current_mandatory_generic());
}
static public String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static public A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () {
public A get() {
try {
return nuObject(c, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return nuObject(c, args);";
}
});
}
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 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 List toLinesFullTrim(String s) {
List l = new ArrayList();
for (String line : toLines(s)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
static public List toLinesFullTrim(File f) {
List l = new ArrayList();
for (String line : linesFromFile(f)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
static public File localMechListFile(String listName) {
return newFile(localMechListsDir(), uniqueFileNameUsingMD5_80_v2(listName) + ".text");
}
static public Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array) if (o != null)
set.add(o);
return set;
}
static public Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array) if (o != null)
set.add(o);
return set;
}
static public Set asSet(Iterable l) {
if (l instanceof Set)
return (Set) l;
HashSet set = new HashSet();
for (A o : unnull(l)) if (o != null)
set.add(o);
return set;
}
static public Set asSet(MultiSet ms) {
return ms == null ? null : ms.asSet();
}
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 void logMechListAppendLocally(String listName, String text) {
if (empty(text))
return;
logStructureWithDate(mechListAppendLogFile(listName), litorderedmap("list", listName, "text", text));
appendToFile(createLocalMechListFile(listName), assureTrailingNewLine(text));
}
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 boolToInt(boolean b) {
return b ? 1 : 0;
}
static public Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public void pcallF(VF1 f, A a) {
try {
{
if (f != null)
f.get(a);
}
} catch (Throwable __e) {
printStackTrace(__e);
}
}
static public Object pcallF(Runnable r) {
try {
{
if (r != null)
r.run();
}
return null;
} catch (Throwable __e) {
return null;
}
}
static public A pcallF(IF0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(IF1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
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 void scrollRowToVisible(JTable t, int rowIndex) {
int colIndex = 0;
if (!(t.getParent() instanceof JViewport))
return;
JViewport viewport = (JViewport) t.getParent();
Rectangle rect = t.getCellRect(rowIndex, colIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)) {
} else if (rect.x < viewRect.x) {
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)) {
} else if (rect.y < viewRect.y) {
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)) {
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x, y));
}
static public int listRowCount(JList list) {
return list == null ? 0 : swing(new F0() {
public Integer get() {
try {
return list.getModel().getSize();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return list.getModel().getSize();";
}
});
}
static public boolean headless() {
return isHeadless();
}
static public String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
static public String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=");
}
static public String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static public Throwable innerException2(Throwable e) {
if (e == null)
return null;
while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
return e;
}
static public String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
static public String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
static public List childrenOfType(Component c, Class theClass) {
List l = new ArrayList();
scanForComponents(c, theClass, l);
return l;
}
static public List childrenOfType(Class theClass, Component c) {
return childrenOfType(c, theClass);
}
static public JButton findButton(Component c, String name) {
for (JButton b : childrenOfType(c, JButton.class)) if (eq(b.getText(), name))
return b;
for (JButton b : childrenOfType(getFrame(c), JButton.class)) if (eq(b.getText(), name))
return b;
return null;
}
static public JButton findButton(Component c) {
return childOfType(c, JButton.class);
}
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 String asString(Object o) {
return o == null ? null : o.toString();
}
static public File saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
File file = new File(fileName);
mkdirsForFile(file);
String tempFileName = fileName + "_temp";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists())
try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) {
printStackTrace(e);
}
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
vmBus_send("wroteFile", file);
return file;
} finally {
action.done();
}
}
static public File saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A printHidingCredentials(A o) {
print(hideCredentials(str(o)));
return o;
}
static public void logQuotedWithDate(String s) {
logQuotedWithTime(s);
}
static public void logQuotedWithDate(String logFile, String s) {
logQuotedWithTime(logFile, s);
}
static public void logQuotedWithDate(File logFile, String s) {
logQuotedWithTime(logFile, s);
}
static public File infoBoxesLogFile() {
return new File(javaxDataDir(), "Logs/infoBoxes.txt");
}
static public JWindow makeWindow(final Component c) {
return swing(new F0() {
public JWindow get() {
try {
JWindow w = new JWindow();
w.add(wrap(c));
return w;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new JWindow w;\r\n w.add(wrap(c));\r\n ret w;";
}
});
}
static public JPanel infoMessage_makePanel(String text) {
final JTextArea ta = wrappedTextArea(text);
onClick(ta, new Runnable() {
public void run() {
try {
disposeWindow(ta);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "disposeWindow(ta)";
}
});
int size = 14;
if (l(text) <= 50)
size *= 2;
else if (l(text) < 100)
size = iround(size * 1.5);
ta.setFont(typeWriterFont(size));
JScrollPane sp = jscroll(ta);
return withMargin(sp);
}
static public int moveToTopRightCorner_inset = 20;
static public A moveToTopRightCorner(A a) {
return moveToTopRightCorner(moveToTopRightCorner_inset, moveToTopRightCorner_inset, a);
}
static public A moveToTopRightCorner(int insetX, int insetY, A a) {
{
swing(() -> {
Window w = getWindow(a);
if (w != null) {
var bounds = preferredScreenBounds();
w.setLocation(bounds.x2() - w.getWidth() - insetX, bounds.y1() + insetY);
}
});
}
return a;
}
static public boolean vmBus_noObjections(String msg, Object... args) {
return !vmBus_anyFalse(msg, args);
}
static public A disposeWindowAfter(int delay, final A w) {
if (w != null)
swingLater(delay, new Runnable() {
public void run() {
try {
w.dispose();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "w.dispose();";
}
});
return w;
}
static public A disposeWindowAfter(A w, double seconds) {
return disposeWindowAfter(toMS_int(seconds), w);
}
static public A disposeWindowAfter(double seconds, A w) {
return disposeWindowAfter(w, seconds);
}
static public int iround(double d) {
return (int) Math.round(d);
}
static public int iround(Number n) {
return iround(toDouble(n));
}
static public String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
static 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 ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
static public AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static public Map weakHashMap() {
return newWeakHashMap();
}
static public void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null)
tl.set(l = new ArrayList());
l.add(a);
}
static public A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null)
return null;
A a = popLast(l);
if (empty(l))
tl.set(null);
return a;
}
static public boolean 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 String mcName() {
return mc().getName();
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
int n = s.length();
if (y < x)
y = x;
if (y > n)
y = n;
if (x >= y)
return "";
return s.substring(x, y);
}
static public String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static public int smartIndexOf(String s, String sub, int i) {
if (s == null)
return 0;
i = s.indexOf(sub, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static public int smartIndexOf(String s, int i, char c) {
return smartIndexOf(s, c, i);
}
static public int smartIndexOf(String s, char c, int i) {
if (s == null)
return 0;
i = s.indexOf(c, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static public int smartIndexOf(String s, String sub) {
return smartIndexOf(s, sub, 0);
}
static public int smartIndexOf(String s, char c) {
return smartIndexOf(s, c, 0);
}
static public int smartIndexOf(List l, A sub) {
return smartIndexOf(l, sub, 0);
}
static public int smartIndexOf(List l, int start, A sub) {
return smartIndexOf(l, sub, start);
}
static public int smartIndexOf(List l, A sub, int start) {
int i = indexOf(l, sub, start);
return i < 0 ? l(l) : i;
}
static public String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
static public String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static public String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static public String quoteIfNotIdentifierOrInteger(String s) {
if (s == null)
return null;
return isJavaIdentifier(s) || isInteger(s) ? s : quote(s);
}
static public boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
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 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 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 RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
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 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 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 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 boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
static volatile public PersistableThrowable lastException_lastException;
static public PersistableThrowable lastException() {
return lastException_lastException;
}
static public void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static public int indexOf(List l, A a, int startIndex) {
if (l == null)
return -1;
int n = l(l);
for (int i = startIndex; i < n; i++) if (eq(l.get(i), a))
return i;
return -1;
}
static public int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
static public int indexOf(List l, A a) {
if (l == null)
return -1;
return l.indexOf(a);
}
static public int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static public int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static public int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
static public int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
static public int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static public int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static public int indexOf(A[] x, A a) {
int n = l(x);
for (int i = 0; i < n; i++) if (eq(x[i], a))
return i;
return -1;
}
static public int indexOf(Iterable l, A a) {
if (l == null)
return -1;
int i = 0;
for (A x : l) {
if (eq(x, a))
return i;
i++;
}
return -1;
}
static public void rotateStringBuffer(StringBuffer buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void rotateStringBuilder(StringBuilder buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static public int year() {
return localYear();
}
static public int year(long now) {
return localYear(now);
}
static public int year(long now, TimeZone tz) {
return parseInt(simpleDateFormat("y", tz).format(now));
}
static public String formatInt(int i, int digits) {
return padLeft(str(i), '0', digits);
}
static public String formatInt(long l, int digits) {
return padLeft(str(l), '0', digits);
}
static public int month() {
return localMonth();
}
static public int month(long now) {
return localMonth(now);
}
static public int month(long now, TimeZone tz) {
return parseInt(simpleDateFormat("M", tz).format(now));
}
static public int dayOfMonth() {
return localDayOfMonth();
}
static public int dayOfMonth(long now) {
return localDayOfMonth(now);
}
static public int dayOfMonth(long now, TimeZone tz) {
return parseInt(simpleDateFormat("d", tz).format(now));
}
static public long fileSize(String path) {
return getFileSize(path);
}
static public long fileSize(File f) {
return getFileSize(f);
}
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 Rect rect(int x, int y, int w, int h) {
return new Rect(x, y, w, h);
}
static public Rect rect(Pt p, int w, int h) {
return new Rect(p.x, p.y, w, h);
}
static public Rect rect(int w, int h) {
return new Rect(0, 0, w, h);
}
static public boolean jInternalFrame_iconifiable = true;
static public JInternalFrame jInternalFrame() {
return jInternalFrame("");
}
static public JInternalFrame jInternalFrame(final String title) {
return swing(new F0() {
public JInternalFrame get() {
try {
JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame_iconifiable);
f.setVisible(true);
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame...";
}
});
}
static public void setInternalFrameContents(final Component c, final Object contents) {
{
swing(() -> {
JInternalFrame frame = getInternalFrame(c);
if (frame == null)
return;
frame.getContentPane().removeAll();
frame.getContentPane().setLayout(new BorderLayout());
if (contents != null)
frame.getContentPane().add(wrap(contents));
revalidate(frame);
});
}
}
static public A setBounds(final int x, final int y, final int w, final int h, final A a) {
if (a != null) {
swing(() -> {
a.setBounds(x, y, w, h);
});
}
return a;
}
static public A setBounds(A a, Rect r) {
if (a != null && r != null) {
swing(() -> {
a.setBounds(toRectangle(r));
});
}
return a;
}
static public A setBounds(A a, Rectangle r) {
if (a != null && r != null) {
swing(() -> {
a.setBounds(r);
});
}
return a;
}
static public A setBounds(Rect r, A a) {
return setBounds(a, r);
}
static public A setBounds(A a, int x, int y, int w, int h) {
return setBounds(x, y, w, h, a);
}
static public void internalFrameDefaultPosition(JInternalFrame f) {
f.setSize(500, 300);
centerInternalFrame(f);
}
static public JPanel jpanel(LayoutManager layout) {
return swingNu(JPanel.class, layout);
}
static public JPanel jpanel() {
return swingNu(JPanel.class);
}
static public Runnable asRunnable(Object o) {
return toRunnable(o);
}
static public void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static public int getScreenWidth() {
return getScreenSize().width;
}
static public int getScreenHeight() {
return getScreenSize().height;
}
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 boolean frameTooSmall(JFrame frame) {
return frame.getWidth() < 100 || frame.getHeight() < 50;
}
static public void frameStandardSize(JFrame frame) {
frame.setBounds(300, 100, 500, 400);
}
static public void setFrameContents(final Component c, final Object contents) {
swing(() -> {
JFrame frame = getFrame(c);
if (frame == null)
return;
frame.getContentPane().removeAll();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrap(contents));
revalidate(frame);
});
}
static public A jtransparent(final A a) {
{
swing(() -> {
a.setOpaque(false);
});
}
return a;
}
static public JPanel borderLayoutPanel() {
return jpanel(new BorderLayout());
}
static public void forEach(Iterable l, IVF1 f) {
if (f != null && l != null)
for (A a : l) callF(f, a);
}
static public void forEach(IVF1 f, Iterable l) {
forEach(l, f);
}
static public void forEach(A[] l, IVF1 f) {
if (f != null && l != null)
for (A a : l) callF(f, a);
}
static public void forEach(IVF1 f, A[] l) {
forEach(l, f);
}
static public void forEach(Map map, IVF2 f) {
for (Map.Entry extends A, ? extends B> __0 : _entrySet(map)) {
A a = __0.getKey();
B b = __0.getValue();
f.get(a, b);
}
}
static public Object pcallFAll_returnFirstNotNull(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
Object __1 = pcallF(f, args);
if (__1 != null)
return __1;
}
return null;
}
static public Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) {
while (it.hasNext()) {
Object __2 = pcallF(it.next(), args);
if (__2 != null)
return __2;
}
return null;
}
static public A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
return c;
}
static public JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return new JScrollPane(c);";
}
});
}
static public JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
static public JLabel jlabel() {
return jlabel(" ");
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
static public Method findMethod_cached(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
_MethodCache cache = callOpt_getCache((Class) o);
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
return m;
return null;
} else {
_MethodCache cache = callOpt_getCache(o.getClass());
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (findMethod_checkArgs(m, args, false))
return m;
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object[] asObjectArray(Collection l) {
return toObjectArray(l);
}
static public boolean containsNulls(Collection c) {
return contains(c, null);
}
static public Map similarEmptyMap(Map m) {
if (m instanceof TreeMap)
return new TreeMap(((TreeMap) m).comparator());
if (m instanceof LinkedHashMap)
return new LinkedHashMap();
return new HashMap();
}
static public Map similarEmptyMap(Iterable m) {
if (m instanceof TreeSet)
return new TreeMap(((TreeSet) m).comparator());
if (m instanceof LinkedHashSet)
return new LinkedHashMap();
return new HashMap();
}
static 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(MultiMap mm) {
return mm.keySet();
}
static public boolean isAllUpperCase(String s) {
return hasLettersAllUpperCase(s);
}
static public boolean isUpperCaseLetter(char c) {
return Character.isUpperCase(c);
}
static public boolean isMenuSeparatorIndicator(Object o) {
return eqOneOf(o, "***", "---", "===", "");
}
static public int menuItemCount(JMenu menu) {
return menu == null ? 0 : swing(() -> menu.getItemCount());
}
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 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 String unCurlyBracket(String s) {
return tok_unCurlyBracket(s);
}
static public A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) {
if (lv != null)
bindToComponent(component, new Runnable() {
public void run() {
try {
lv.onChangeAndNow(listener);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindLiveValueListenerToComponent_debug\r\n print(\"bindLiveValueL...";
}
}, new Runnable() {
public void run() {
try {
lv.removeChangeListener(listener);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "lv.removeChangeListener(listener)";
}
});
return component;
}
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 boolean setText_opt = true;
static public A setText(A c, Object text) {
setText((JComponent) c, text);
return c;
}
static public A setText(final A c, Object text) {
final String s = strUnnull(text);
{
swing(() -> {
c.getEditor().setItem(s);
});
}
return c;
}
static public void setText(JLabel c, Object text) {
setText((JComponent) c, text);
}
static public JButton setText(JButton c, Object text) {
setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text)));
return c;
}
static public A setText(final A c, Object text) {
if (c == null)
return null;
final String s = strUnnull(text);
{
swing(() -> {
if (!setText_opt || neq(callOpt(c, "getText"), s))
call(c, "setText", s);
});
}
return c;
}
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 getComponents(final Component c) {
return !(c instanceof Container) ? emptyList() : asList(swing(new F0() {
public Component[] get() {
try {
return ((Container) c).getComponents();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return ((Container) c).getComponents();";
}
}));
}
static public Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static public boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static public boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
static public void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, Math.min(a.length, b.length));
}
static public void arraycopy(Object src, int srcPos, 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 A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
static public A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
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 dm_getStem(Object moduleOrID) {
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
moduleOrID = dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_getStemByID(moduleOrID);
return or(getOpt(dm_getModule(moduleOrID), "_host"), moduleOrID);
}
static public Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static public boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static public String getSnippetTitle(String id) {
if (id == null)
return null;
if (!isSnippetID(id))
return "?";
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.getSnippetTitle(id);
return getSnippetTitle_noResourceLoader(id);
}
static public String getSnippetTitle_noResourceLoader(String id) {
try {
if (isLocalSnippetID(id))
return localSnippetTitle(id);
long parsedID = parseSnippetID(id);
String url;
if (isImageServerSnippet(parsedID))
url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery();
else if (isGeneralFileServerSnippet(parsedID))
url = "http://butter.botcompany.de:8080/files/name/" + parsedID;
else
url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies();
String title = trim(loadPageSilently(url));
if (title != null)
try {
saveTextFileIfChanged(snippetTitle_cacheFile(id), title);
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
return or(title, "?");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String getSnippetTitle(long id) {
return getSnippetTitle(fsI(id));
}
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 File localMechListsDir() {
return javaxDataDir("Mech Lists");
}
static public String uniqueFileNameUsingMD5_80_v2(String fullName) {
return uniqueFileNameUsingMD5_80_v2(fullName, md5(fullName));
}
static public String uniqueFileNameUsingMD5_80_v2(String fullName, String md5) {
return takeFirst(80 - 33, fileNameEncode(fullName)) + " - " + md5;
}
static public A logStructureWithDate(File logFile, A o) {
logQuoted(logFile, now() + " " + structure(o));
return o;
}
static public A logStructureWithDate(String fileName, A o) {
return logStructureWithDate(getProgramFile(fileName), o);
}
static public File mechListAppendLogFile(String listName) {
return javaxDataDir("Mech List Appends/" + uniqueFileNameUsingMD5_80(listName));
}
static public LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
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 File createLocalMechListFile(String listName) {
File nameFile = localMechListNameFile(listName);
if (!nameFile.exists())
saveTextFile(nameFile, listName);
return localMechListFile(listName);
}
static public String assureTrailingNewLine(String s) {
return addSuffix(s, "\n");
}
static public String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
static public Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
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 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 scanForComponents(final Component c, final Class theClass, final List l) {
if (theClass.isInstance(c))
l.add((A) c);
if (c instanceof Container) {
swing(() -> {
for (Component comp : ((Container) c).getComponents()) scanForComponents(comp, theClass, l);
});
}
}
static public A childOfType(Component c, Class theClass) {
return first(childrenOfType(c, theClass));
}
static public A childOfType(Class theClass, Component c) {
return childOfType(c, theClass);
}
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 List beginCriticalAction_inFlight = synchroList();
static public class CriticalAction {
public String description;
public CriticalAction() {
}
public CriticalAction(String description) {
this.description = description;
}
public void done() {
beginCriticalAction_inFlight.remove(this);
}
}
static public CriticalAction beginCriticalAction(String description) {
ping();
CriticalAction c = new CriticalAction(description);
beginCriticalAction_inFlight.add(c);
return c;
}
static public void cleanMeUp_beginCriticalAction() {
int n = 0;
while (nempty(beginCriticalAction_inFlight)) {
int m = l(beginCriticalAction_inFlight);
if (m != n) {
n = m;
try {
print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
} catch (Throwable __e) {
printStackTrace(__e);
}
}
sleepInCleanUp(10);
}
}
static public File copyFile(File src, File dest) {
try {
FileInputStream inputStream = new FileInputStream(src.getPath());
FileOutputStream outputStream = newFileOutputStream(dest.getPath());
try {
copyStream(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
return dest;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static 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 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 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(final A c, final 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, final Object runnable) {
onEnter(btn, runnable);
}
static public Font typeWriterFont() {
return typeWriterFont(iround(14 * getSwingFontScale()));
}
static public Font typeWriterFont(int size) {
return new Font("Courier", Font.PLAIN, size);
}
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 int toMS_int(double seconds) {
return toInt_checked((long) (seconds * 1000));
}
static public double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o instanceof String)
return parseDouble((String) o);
if (o == null)
return 0.0;
throw fail(o);
}
static 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 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 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 A popLast(List l) {
return liftLast(l);
}
static public List popLast(int n, List l) {
return liftLast(n, l);
}
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 int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
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 boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static public boolean isInteger(String s) {
int n = l(s);
if (n == 0)
return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n)
return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9')
return false;
++i;
}
return true;
}
static public String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
static public String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
static public void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\t')
out.append("\\t");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static public boolean isLetterOrDigit(char c) {
return Character.isLetterOrDigit(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 void _handleError(Error e) {
call(javax(), "_handleError", e);
}
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 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 Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static public Throwable _storeException_value;
static public void _storeException(Throwable e) {
_storeException_value = e;
}
static public PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static public int localYear() {
return localYear(now());
}
static public int localYear(long time) {
return parseInt(simpleDateFormat_local("yyyy").format(time));
}
static public java.text.SimpleDateFormat simpleDateFormat(String format, TimeZone timeZone) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
sdf.setTimeZone(timeZone);
return sdf;
}
static public String padLeft(String s, char c, int n) {
return rep(c, n - l(s)) + s;
}
static public String padLeft(String s, int n) {
return padLeft(s, ' ', n);
}
static public int localMonth(long time) {
return parseInt(simpleDateFormat_local("MM").format(time));
}
static public int localMonth() {
return localMonth(now());
}
static public int localDayOfMonth(long time) {
return parseInt(simpleDateFormat_local("dd").format(time));
}
static public int localDayOfMonth() {
return localDayOfMonth(now());
}
static public Set synchroWeakHashSet() {
return Collections.newSetFromMap((Map) newWeakHashMap());
}
static public Rectangle toRectangle(Rect r) {
return r == null ? null : r.getRectangle();
}
static public Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
static public String programTitle() {
return getProgramName();
}
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 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 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 hasLettersAllUpperCase(String s) {
return hasLetters(s) && !containsLowerCase(s);
}
static public boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
static public String tok_unCurlyBracket(String s) {
return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
}
static public boolean isCurlyBraced(String s) {
List tok = tok_combineCurlyBrackets_keep(javaTok(s));
return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}");
}
static public String strUnnull(Object o) {
return o == null ? "" : str(o);
}
static public String jlabel_textAsHTML_center_ifNeeded(String text) {
if (swic(text, "") && ewic(text, ""))
return text;
if (!containsNewLines(text))
return text;
return jlabel_textAsHTML_center(text);
}
static public char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s) - 1);
}
static public A[] dropLast(A[] a) {
return dropLast(a, 1);
}
static public A[] dropLast(A[] a, int n) {
if (a == null)
return null;
n = Math.min(n, a.length);
A[] b = arrayOfSameType(a, a.length - n);
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static public List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
static public List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
static public List dropLast(Iterable l) {
return dropLast(asList(l));
}
static public String dropLast(String s) {
return substring(s, 0, l(s) - 1);
}
static public String dropLast(String s, int n) {
return substring(s, 0, l(s) - n);
}
static public String dropLast(int n, String s) {
return dropLast(s, n);
}
static public boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class)
return arg instanceof Boolean;
if (type == int.class)
return arg instanceof Integer;
if (type == long.class)
return arg instanceof Long;
if (type == float.class)
return arg instanceof Float;
if (type == short.class)
return arg instanceof Short;
if (type == char.class)
return arg instanceof Character;
if (type == byte.class)
return arg instanceof Byte;
if (type == double.class)
return arg instanceof Double;
return type.isInstance(arg);
}
static public A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
static public boolean isString(Object o) {
return o instanceof String;
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public Object dm_getService(String serviceName) {
return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName)));
}
static public boolean isStringOrIntOrLong(Object o) {
return o instanceof String || o instanceof Integer || o instanceof Long;
}
static public Object dm_getStemByID(Object id) {
return dm_callOS("getModuleByID", str(id));
}
static public Object dm_getModule(Object moduleOrID) {
if (moduleOrID == null || eq(moduleOrID, ""))
return null;
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
return dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
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