Warning : session_start(): open(/var/lib/php/sessions/sess_4ud0c60ac7l5qjbccp9v0nquu3, 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
//FILENAME: loadableUtils/utils.java
package loadableUtils;
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import java.awt.datatransfer.StringSelection;
import javax.swing.border.*;
import java.awt.geom.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import java.awt.datatransfer.*;
import java.text.SimpleDateFormat;
import javax.swing.undo.UndoManager;
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 net.coobird.thumbnailator.Thumbnailator;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.*;
import static x30_pkg.x30_util.VF1;
import x30_pkg.x30_util.DynamicObject;
public class utils {
static public ThreadLocal DynamicObject_loading = x30_pkg.x30_util.DynamicObject_loading;
static public File nohupJavax(String javaxargs) {
return directNohupJavax(javaxargs);
}
static public File nohupJavax(String javaxargs, String vmArgs) {
return directNohupJavax(javaxargs, vmArgs);
}
static public interface DynamicMethods {
abstract public Object _dynCall(String methodName, Object[] args);
}
static public class BetterLabel extends JLabel {
public boolean autoToolTip = true;
public BetterLabel() {
final WeakReference me = new WeakReference<>(this);
componentPopupMenu(this, BetterLabel_menuItems(me));
}
public BetterLabel(String text) {
this();
this.setText(text);
}
public void setText(String text) {
super.setText(text);
if (autoToolTip)
if (!swic(text, ""))
setToolTipText(nullIfEmpty(text));
}
}
static public VF1 BetterLabel_menuItems(final WeakReference me) {
return new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, "Copy text to clipboard", new Runnable() {
public void run() {
try {
copyTextToClipboard(me.get().getText());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyTextToClipboard(me.get().getText());";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(me...";
}
};
}
static public class SingleComponentPanel extends JPanel {
public SingleComponentPanel() {
super(new BorderLayout());
}
public SingleComponentPanel(Component component) {
this();
if (component != null)
setComponent(component);
}
public void setComponent(final Component component) {
{
swing(new Runnable() {
public void run() {
try {
removeAll();
if (component != null)
add(BorderLayout.CENTER, wrap(component));
_revalidate(SingleComponentPanel.this);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "removeAll();\r\n if (component != null)\r\n add(BorderLayout.CENTER, ...";
}
});
}
}
public void setComponentAndRevalidateParent(Component component) {
setComponent(component);
_revalidate(_getParent(this));
}
public void noComponent() {
setComponent(null);
}
public Component getComponent() {
return getComponentCount() == 0 ? null : getComponent(0);
}
}
static public class Snippet {
public String id, title, md5, type, text;
public boolean isPublic = false;
public Snippet() {
}
public Snippet(String id, String title) {
this.title = title;
this.id = id;
}
public Snippet(String id, String title, String md5) {
this.md5 = md5;
this.title = title;
this.id = id;
}
public String toString() {
return id + " - " + title;
}
public boolean equals(Object o) {
return stdEq2(this, o);
}
public int hashCode() {
return stdHash2(this);
}
}
static final public class BWImage implements MakesBufferedImage, IBWImage {
public int width, height;
public byte[] pixels;
public float borderColor = 0.0f;
public BWImage() {
}
public BWImage(int width, int height) {
this.height = height;
this.width = width;
pixels = new byte[width * height];
}
public BWImage(int width, int height, float brightness) {
this.height = height;
this.width = width;
pixels = new byte[width * height];
fillArrayUnlessZero(pixels, _toByte(brightness));
}
public BWImage(int width, int height, float[] pixels) {
this.pixels = new byte[pixels.length];
this.height = height;
this.width = width;
for (int i = 0; i < pixels.length; i++) this.pixels[i] = _toByte(pixels[i]);
}
public BWImage(int width, int height, byte[] pixels) {
this.height = height;
this.width = width;
this.pixels = pixels;
}
public BWImage(BWImage image) {
width = image.getWidth();
height = image.getHeight();
byte[] pixels = this.pixels = new byte[width * height];
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) pixels[y * width + x] = image.getByte(x, y);
}
public BWImage(RGBImage image) {
width = image.getWidth();
height = image.getHeight();
byte[] pixels = this.pixels = new byte[height * width];
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) {
RGB rgb = image.getRGB(x, y);
pixels[y * width + x] = BWImage._toByte(rgb.getBrightness());
}
}
public BWImage(BufferedImage image) {
try {
width = image.getWidth();
height = image.getHeight();
int[] pixels = new int[width * height];
byte[] bytePixels = this.pixels = new byte[width * height];
PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
if (!pixelGrabber.grabPixels())
throw fail("Could not grab pixels");
int n = width * height;
for (int i = 0; i < n; i++) {
int packed = pixels[i];
int r = ((packed >> 16) & 0xFF);
int g = ((packed >> 8) & 0xFF);
int b = (packed & 0xFF);
bytePixels[i] = (byte) ((r + g + b + 1) / 3);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte pixelToByte(int packed) {
float r = ((packed >> 16) & 0xFF) / 255f;
float g = ((packed >> 8) & 0xFF) / 255f;
float b = (packed & 0xFF) / 255f;
return (byte) ((r + g + b) / 3.0f * 255f);
}
public byte getByte(int x, int y) {
return inRange(x, y) ? getByte_noRangeCheck(x, y) : _toByte(borderColor);
}
public int getInt(int x, int y) {
return ubyteToInt(getByte(x, y));
}
public double averageBrightness() {
double sum = 0;
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) sum += getPixel(x, y);
return (sum / (double) (height * width));
}
public float minimumBrightness() {
float min = 1;
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) min = Math.min(min, getPixel(x, y));
return min;
}
public float maximumBrightness() {
float max = 0;
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) max = Math.max(max, getPixel(x, y));
return max;
}
public float getPixel(int x, int y) {
return inRange(x, y) ? _toFloat(getByte(x, y)) : borderColor;
}
public float getFloatPixel(int x, int y) {
return getPixel(x, y);
}
public float getPixel(Pt p) {
return getPixel(p.x, p.y);
}
static public byte _toByte(float pixel) {
return (byte) (pixel * 255f);
}
static public float _toFloat(byte pixel) {
return (((int) pixel) & 255) / 255f;
}
final public boolean inRange(int x, int y) {
return x >= 0 && x < width && y >= 0 && y < height;
}
public int getWidth() {
return width;
}
public int w() {
return width;
}
public int getHeight() {
return height;
}
public int h() {
return height;
}
public RGBImage toRGB() {
int[] rgbs = new int[width * height];
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) {
int b = getByte(x, y) & 0xFF;
rgbs[y * width + x] = 0xFF000000 | b * 0x010101;
}
return new RGBImage(width, height, rgbs);
}
public RGBImage toRGB_slow() {
RGB[] rgbs = new RGB[width * height];
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) {
float p = getPixel(x, y);
rgbs[y * width + x] = new RGB(p, p, p);
}
return new RGBImage(width, height, rgbs);
}
public BWImage clip(int x, int y, int w, int h) {
return clip(new Rectangle(x, y, w, h));
}
final public Rectangle fixClipRect(Rectangle r) {
return r.intersection(new Rectangle(0, 0, width, height));
}
public BWImage clip(Rect r) {
return clip(r.getRectangle());
}
public BWImage clip(Rectangle r) {
r = fixClipRect(r);
byte[] newPixels = new byte[r.height * r.width];
for (int y = 0; y < r.height; y++) for (int x = 0; x < r.width; x++) newPixels[y * r.width + x] = getByte(r.x + x, r.y + y);
return new BWImage(r.width, r.height, newPixels);
}
public void setPixel(int x, int y, float brightness) {
setByte(x, y, _toByte(fixPixel(brightness)));
}
public void setInt(int x, int y, int i) {
setByte(x, y, (byte) limitToUByte(i));
}
public void setByte(int x, int y, byte b) {
if (x >= 0 && x < width && y >= 0 && y < height)
pixels[y * width + x] = b;
}
public byte getByte_noRangeCheck(int x, int y) {
return pixels[y * width + x];
}
public void setByte(int x, int y, int brightness) {
setByte(x, y, (byte) brightness);
}
final public float fixPixel(float pixel) {
return Math.max(0, Math.min(1, pixel));
}
public float getBorderColor() {
return borderColor;
}
public void setBorderColor(float borderColor) {
this.borderColor = borderColor;
}
public boolean anyPixelBrighterThan(double threshold) {
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) if (getPixel(x, y) > threshold)
return true;
return false;
}
public BufferedImage getBufferedImage() {
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) {
int b = ((int) getByte(x, y) & 0xFF);
bufferedImage.setRGB(x, y, b * 0x010101);
}
return bufferedImage;
}
public byte[] getBytes() {
return pixels;
}
}
static public class Cache {
public Object maker;
public A value;
public long loaded;
static public boolean debug = false;
public long changeCount;
public Lock lock = lock();
public Cache() {
}
public Cache(Object maker) {
this.maker = maker;
}
public Cache(IF0 maker) {
this.maker = maker;
}
public A get() {
if (hasLock(lock))
return value;
Lock __14 = lock;
lock(__14);
try {
if (loaded == 0) {
value = make();
changeCount++;
loaded = sysNow();
}
return value;
} finally {
unlock(__14);
}
}
public void clear() {
Lock __15 = lock;
lock(__15);
try {
if (debug && loaded != 0)
print("Clearing cache");
value = null;
changeCount++;
loaded = 0;
} finally {
unlock(__15);
}
}
public void clear(double seconds) {
Lock __16 = lock;
lock(__16);
try {
if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000)
clear();
} finally {
unlock(__16);
}
}
public void set(A a) {
Lock __17 = lock;
lock(__17);
try {
value = a;
++changeCount;
loaded = sysNow();
} finally {
unlock(__17);
}
}
public A make() {
return (A) callF(maker);
}
}
static abstract public class DynModule {
public String name, toolTip;
public PersistableThrowable _error;
public Map> mechLists;
public Map _persistenceInfo;
transient public Object _host;
transient public Map timers = newWeakHashMap();
transient public Set _resources = synchroHashSet();
transient public Lock lock;
transient public boolean persistOnChangedField = true;
transient public int changeCount;
transient public Object changeCountSync = new Object();
transient public List onChange;
transient public List onTransientChange;
transient public boolean verboseTimers = false;
transient public ReliableSingleThread rstUpdate;
transient public Set componentFieldsToKeep;
transient public Map transientGeneralMap = synchroHashMap();
transient public Q q;
transient public List onFieldChange;
transient public boolean _hasPreviousBounds = false;
transient public StringBuffer _printLog = new StringBuffer();
transient public boolean deleted = false;
public DynModule() {
dm_initErrorHandling();
setMainDesktopPane((JDesktopPane) getCreatorOpt("desktop"));
}
public boolean isVisible() {
return isTrue(getOpt(_host, "visible"));
}
public String moduleName() {
return name;
}
public void setModuleName(String name) {
String oldName = this.name;
if (!eq(name, oldName)) {
setField("name", name);
possiblyInternalFrameTitle(vis(), name);
vmBus_send("moduleNameChange", this, oldName, name);
}
}
public void setModuleToolTip(String toolTip) {
this.toolTip = toolTip;
}
public JComponent vis() {
return (JComponent) getOpt(_host, "vis");
}
public A ownResource(A a) {
if (a != null)
_resources.add(a);
return a;
}
public A ownTimer(A timer) {
if (timer instanceof AutoCloseable)
ownResource((AutoCloseable) timer);
ownTimer(timer, "cancelTimerOrInterruptThread");
return timer;
}
public void ownTimer(Object timer, Object closerHelper) {
timers.put(timer, closerHelper);
}
public void singleTimer(java.util.Timer timer) {
stopAllTimers();
ownTimer(timer);
}
public void stopAllTimers() {
for (AutoCloseable resource : getAndClearList(_resources)) {
if (verboseTimers)
print("Releasing resource: " + resource);
try {
resource.close();
} catch (Throwable __e) {
_handleException(__e);
}
}
{
final Map __20 = getAndClearMap(timers);
for (Object timer : keys(__20)) {
Object closerHelper = __20.get(timer);
if (verboseTimers)
print("Stopping timer: " + closerHelper + " / " + timer);
pcallFInRealOrMyMC(this, closerHelper, timer);
}
}
}
public boolean isDeleted() {
return deleted;
}
public void cleanMeUp_dynModule() {
deleted = true;
stopAllTimers();
}
public void persistMe() {
synchronized (changeCountSync) {
++changeCount;
}
pcallFAll(onChange);
callOpt(_host, "_change");
updateMe();
}
public void fireChangeWithoutPersisting() {
pcallFAll(onChange);
}
public void fireTransientChange() {
pcallFAll(onTransientChange);
}
public void _change() {
persistMe();
}
public void change() {
persistMe();
}
public void updateMe() {
rstUpdate().trigger();
}
public void changeAndUpdate() {
_change();
updateMe();
}
public boolean setField(String name, Object value) {
AutoCloseable __25 = enter();
try {
{
try {
if (eq(get(this, name), value))
return false;
} catch (Throwable __e) {
_handleException(__e);
}
set(this, name, value);
}
pcallFAll(onFieldChange, name);
if (persistOnChangedField && !isFalse(mapGet(_persistenceInfo, name)))
_change();
return true;
} finally {
_close(__25);
}
}
public A setFieldAndReturn(String name, A value) {
setField(name, value);
return value;
}
public boolean setFields(Object... params) {
boolean change = false;
for (int i = 0; i < l(params); i += 2) if (setField((String) params[i], params[i + 1]))
change = true;
return change;
}
public void start() {
_hasPreviousBounds = dm_getBounds() != null;
if (hasMethod_onTypes(this, "onTopInput", String.class))
dm_onTopInput_q(new VF1() {
public void get(String s) {
try {
call(module(), "onTopInput", s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "call(module(), 'onTopInput, s)";
}
});
}
public void revisualize() {
call(creator(), "revisualizeModule", _host);
}
public AutoCloseable enter() {
AutoCloseable c = tempSetThreadLocal(dm_currentModule_value, new WeakReference(this));
final Object realMC = getMainClass(this);
if (printToModule())
c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(_printToModuleInterceptor()));
if (realMC != mc()) {
if (printToModule())
c = combineAutoCloseables(c, (AutoCloseable) callOpt(realMC, "tempInterceptPrintIfNotIntercepted", _printToModuleInterceptor()));
else
c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(new F1() {
public Boolean get(String s) {
try {
{
call(realMC, "print", s);
return false;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret false with call(realMC, 'print, s);";
}
}));
c = combineAutoCloseables(c, tempSetTL(realMC_tl(), realMC));
}
return c;
}
public F1 _printToModuleInterceptor() {
return new F1() {
public Boolean get(String s) {
try {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = _printLog;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (print_preprocess != null) s = (S) callF(print_preprocess, s);\r\n s = ...";
}
};
}
public boolean printToModule() {
return true;
}
public AutoCloseable enterAndLock() {
return combineAutoCloseables(enter(), tempLock(lock));
}
public boolean setError(Throwable e) {
setField("_error", persistableThrowable(e));
return true;
}
public void clearError() {
setField("_error", null);
}
public void onChange(Runnable r) {
Lock __21 = lock;
lock(__21);
try {
if (onChange == null)
onChange = synchroList();
addIfNotThere(onChange, r);
} finally {
unlock(__21);
}
}
public void onFieldChange(VF1 r) {
Lock __22 = lock;
lock(__22);
try {
if (onFieldChange == null)
onFieldChange = synchroList();
addIfNotThere(onFieldChange, r);
} finally {
unlock(__22);
}
}
public void onChangeAndNow(Runnable r) {
onChange(r);
callF(r);
}
public void onChangeAndNow(JComponent c, Object r) {
onUpdateAndNow(c, r);
}
public A onChange(A tc, Object r) {
onUpdate(tc, r);
return tc;
}
public void update() {
}
public void unvisualize() {
zeroAllFieldsOfTypeExcept(this, Component.class, componentFieldsToKeep);
}
public Object menuItems() {
return null;
}
public void enhanceFrame(Container f) {
Object items = menuItems();
if (items instanceof Object[])
items = paramsToAbstractActions((Object[]) items);
internalFramePopupMenuFromActions_threaded(f, (List) items);
String switchableFields = (String) (callOpt(this, "switchableFields"));
Set set = asLinkedHashSet(splitAtSpace(switchableFields));
Matches m = new Matches();
for (String field : allFields(this)) if (startsWith(field, "_switchableField_", m))
set.add(m.rest());
for (String field : set) {
Class type = fieldType(this, field);
if (eq(boolean.class, type))
dm_boolFieldMenuItem(f, field);
else if (eq(int.class, type))
dm_intFieldMenuItem(f, field);
else if (eq(double.class, type))
dm_doubleFieldMenuItem(f, field);
else if (eq(String.class, type))
dm_stringFieldMenuItem(f, field);
else if (eq(File.class, type))
dm_fileFieldMenuItem(f, field);
}
}
public ReliableSingleThread rstUpdate() {
if (rstUpdate == null)
rstUpdate = dm_rst(this, new Runnable() {
public void run() {
try {
AutoCloseable __26 = enter();
try {
update();
} finally {
_close(__26);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); update();";
}
});
return rstUpdate;
}
public Q q() {
AutoCloseable __27 = enter();
try {
if (q == null) {
Lock __23 = lock;
lock(__23);
try {
if (q == null)
q = dm_startQ();
} finally {
unlock(__23);
}
}
return q;
} finally {
_close(__27);
}
}
public A withUpdate(A a) {
rstUpdate().trigger();
return a;
}
public DynModule module() {
return this;
}
public DynModule me() {
return this;
}
public JComponent visualize() {
return dm_noVisualisation();
}
public String programTitle_cache;
public String programTitle() {
if (programTitle_cache == null)
programTitle_cache = snippetTitle(programID(mainClass(this)));
return programTitle_cache;
}
public void doPersist(String field) {
_persistenceInfo = mapMinus(_persistenceInfo, field);
}
public void dontPersist(String field) {
_persistenceInfo = mapPlus(_persistenceInfo, "field", false);
}
public Appendable _actualPrintLog() {
return printToModule() ? _printLog : print_log;
}
}
static public void _registerTimer(java.util.Timer timer) {
_registerTimer_original(timer);
dm_currentModule().ownTimer(timer);
}
abstract static public class DynPrintLog extends DynModule {
transient public JFastLogView_noWrap printLogView;
transient public Lock updatePrintLog_lock = lock();
transient public StringBuffer actualPrintLog;
transient public int printLogUpdateInterval = 500;
public JComponent visualize() {
JComponent section = jSection("Log", jscroll_copyBackground(printLogView = jFastLogView_noWrap(getPrintLog())));
componentPopupMenuItem(section, "Clear", new Runnable() {
public void run() {
try {
AutoCloseable __34 = enter();
try {
dm_clearModulePrintLog();
} finally {
_close(__34);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); dm_clearModulePrintLog();";
}
});
return awtEvery(section, printLogUpdateInterval, new Runnable() {
public void run() {
try {
updatePrintLog();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "updatePrintLog();";
}
});
}
public void updatePrintLog() {
swing(new Runnable() {
public void run() {
try {
Lock __31 = updatePrintLog_lock;
lock(__31);
try {
JFastLogView_noWrap _view = printLogView;
if (_view == null)
return;
if (_view.setText(getPrintLog())) {
scrollAllTheWayDown(_view);
awtLater(100, new Runnable() {
public void run() {
try {
scrollAllTheWayDown(_view);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "scrollAllTheWayDown(_view)";
}
});
}
} finally {
unlock(__31);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "// TODO: optimize\r\n Lock __31 = updatePrintLog_lock; lock(__31); try {\r\n ...";
}
});
}
public JFastLogView_noWrap myPrintLogComponent() {
return printLogView;
}
public void enableWordWrap() {
}
public String getPrintLog() {
if (actualPrintLog == null) {
if (printToModule())
actualPrintLog = _printLog;
else
actualPrintLog = liveLocalPrintLog_realMC(this);
}
return str(actualPrintLog);
}
}
abstract static public class DynObjectTable extends DynModule {
public List data = new ArrayList();
transient public JTable table;
transient public F1 itemToMap;
transient public VF1 defaultAction;
transient public boolean debug, fieldsInOrder = true, withSearcher;
transient public TableSearcher searcher;
transient public List onListChanged;
transient public Set hideFields;
transient public boolean useStruct = false;
public void start() {
try {
super.start();
itemToMap = new F1() {
public Map get(A a) {
try {
if (a instanceof String)
return litorderedmap("", (String) a);
Map map = humanizeKeys(fieldsInOrder ? objectToMap_inOrder_withoutFields(a, hideFields) : objectToMap(a));
if (!useStruct)
map = mapValues(__70 -> strOrEmpty(__70), map);
return map;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (a instanceof S) ret litorderedmap(\"\" := (S) a);\r\n Map map = humanize...";
}
};
onChange(new Runnable() {
public void run() {
try {
updateTable();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "updateTable();";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void onListChanged(Runnable r) {
if (r == null)
return;
onListChanged = addDyn_sync(onListChanged, r);
}
public void onListChangedAndNow(Runnable r) {
if (r == null)
return;
onListChanged(r);
r.run();
}
public void addCountToName() {
onListChangedAndNow(new Runnable() {
public void run() {
try {
addCountToNameNow();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addCountToNameNow();";
}
});
}
public void addCountToNameNow() {
AutoCloseable __38 = enter();
try {
setModuleName(programTitle() + " (" + count() + ")");
} finally {
_close(__38);
}
}
public JComponent visualize() {
List l = map(itemToMap, data);
table = dataToTable_uneditable(sexyTable(), l);
onDoubleClickOrEnter(table, new VF1() {
public void get(Integer row) {
try {
AutoCloseable __39 = enter();
try {
A a = _get(data, row);
if (a != null)
onDoubleClick(a);
} finally {
_close(__39);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter();\r\n A a = _get(data, row);\r\n if (a != null) onDoubleCli...";
}
});
if (withSearcher)
return (searcher = tableWithSearcher2(table)).panel;
return table;
}
public void unvisualize() {
super.unvisualize();
searcher = null;
}
public void onDoubleClick(A line) {
callF(defaultAction, line);
}
public void updateTable() {
AutoCloseable __40 = enter();
try {
if (table != null) {
swing(new Runnable() {
public void run() {
try {
Point scrollPosition = enclosingViewPosition(table);
if (debug)
print("Scroll position: " + scrollPosition);
dataToTable_uneditable(table, map(itemToMap, data));
setEnclosingViewPosition(table, scrollPosition);
if (searcher != null)
searcher.rowIndices = null;
if (debug)
print("dataToTable done, alerting " + n2(onListChanged, "listener"));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Point scrollPosition = enclosingViewPosition(table);\r\n if (debug) print(...";
}
});
}
pcallFAll(onListChanged);
} finally {
_close(__40);
}
}
public void dontPersist() {
_persistenceInfo = mapPlus(_persistenceInfo, "data", false);
}
public void clear() {
syncClear(data);
fireDataChanged();
}
public void add(A a) {
syncAdd(data, a);
fireDataChanged();
}
public A addAndReturn(A a) {
add(a);
return a;
}
public void add(int idx, A a) {
syncAdd(data, idx, a);
fireDataChanged();
}
public void addAll(Collection l) {
if (empty(l))
return;
syncAddAll(data, l);
fireDataChanged();
}
public void addAndScrollDown(A a) {
add(a);
scrollDown();
}
public void remove(A a) {
syncRemove(data, a);
fireDataChanged();
}
public void removeAll(List a) {
syncRemoveAll(data, a);
fireDataChanged();
}
public void setList(Iterable data) {
setData(data);
}
public void removeSelected() {
removeAll(allSelected());
}
public void setData(Collection data) {
setData((Iterable) data);
}
public void setData(Iterable data) {
setData(data, false);
}
public void setData(Iterable data, boolean force) {
{
swing(new Runnable() {
public void run() {
try {
int[] selection = selectedTableRows_array(table);
List cloned = cloneList(data);
if (setField("data", cloned) || force) {
updateTable();
dm_vmBus_send("listChanged", module(), cloned);
}
if (force)
change();
selectTableRows(table, selection);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "//int selection = selectedIndex();\r\n int[] selection = selectedTableRows...";
}
});
}
}
public int count() {
return syncL(data);
}
public void setData_force(Collection data) {
setData(data, true);
}
public void fireDataChanged() {
setData_force(data);
}
public int rowFromSearcher(int i) {
return searcher == null || searcher.rowIndices == null ? i : or(get(searcher.rowIndices, i), -1);
}
public A selected() {
return syncGet(data, rowFromSearcher(selectedTableRowInModel(table)));
}
public List allSelected() {
return syncListGetMulti(data, selectedIndices());
}
public int selectedIndex() {
return selectedTableRow(table);
}
public List selectedIndices() {
return map(i -> rowFromSearcher(i), selectedTableRowsInModel(table));
}
public boolean selectItem(A a) {
int i = indexOf(data, a);
selectRow(table, i);
return i >= 0;
}
public void doubleClickItem(A a) {
if (selectItem(a))
onDoubleClick(a);
}
public void popupMenuItem(String text, Object r) {
tablePopupMenuItemsThreaded(table, text, _convertRunnable(r));
}
public void popupMenuItem_top(String text, Object r) {
tablePopupMenuItemsThreaded_top(table, text, _convertRunnable(r));
}
public Object _convertRunnable(final Object r) {
if (r == null || r instanceof Runnable)
return r;
return new VF1() {
public void get(Integer idx) {
try {
callF(r, syncGet(data, idx));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r, syncGet(data, idx))";
}
};
}
public JTable table() {
return table;
}
public void hideFields(String... fields) {
if (hideFields == null)
hideFields = new HashSet();
_addAll(hideFields, fields);
}
public A getRow(int row) {
return get(data, row);
}
public void scrollDown() {
scrollTableDownNow(table);
}
public List getData() {
return data;
}
public List data() {
return getData();
}
public List list() {
return getData();
}
public List getList() {
return getData();
}
public List clonedList() {
return cloneList(data);
}
public File quickBackup() {
File f = programFile("backup-" + ymd_minus_hms_minus_millis() + ".gz");
saveGZStructToFile(f, module());
printFileInfo(f);
return f;
}
}
abstract static public class DynImageSurface extends DynModule {
transient public ImageSurface imageSurface;
transient public BufferedImage image;
transient public String imageID;
transient public boolean useUpdateHack, zoomToWindowOnSetImage;
transient public Object onNewImage;
static public boolean _switchableField_autoSaveToDisk = true;
public boolean autoSaveToDisk = autoSaveToDiskDefault();
public JComponent visualize() {
return _visualize();
}
final public JComponent _visualize() {
imageSurface = imageSurface(image);
imageSurface.onNewImage = new Runnable() {
public void run() {
try {
newImageFromSurface();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "newImageFromSurface();";
}
};
return jscroll_center(imageSurface);
}
public void enableDoubleBuffering() {
if (imageSurface != null)
imageSurface.setDoubleBuffered(true);
}
public JComponent visualizeWithDoubleBuffering() {
JComponent c = _visualize();
enableDoubleBuffering();
return c;
}
public Object _getReloadData() {
return image;
}
public void _setReloadData(BufferedImage image) {
this.image = image;
}
public void start() {
try {
super.start();
if (autoSaveToDisk)
autoLoadNow();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void autoLoadNow() {
AutoCloseable __45 = enter();
try {
try {
File f = autoSaveImageFile();
if (fileExists(f)) {
print("Auto-loading " + f);
setImage(loadImage2(f), true);
}
} catch (Throwable __e) {
_handleException(__e);
}
} finally {
_close(__45);
}
}
public void autoSaveNow() {
AutoCloseable __46 = enter();
try {
try {
File f = autoSaveImageFile();
savePNG(f, image);
infoBox("Auto-saved " + renderFileInfo(f));
} catch (Throwable __e) {
_handleException(__e);
}
} finally {
_close(__46);
}
}
public boolean autoSaveToDiskDefault() {
return false;
}
public void enhanceFrame(Container f) {
super.enhanceFrame(f);
internalFramePopupMenuItem(f, "Auto-save now", runnableThread(new Runnable() {
public void run() {
try {
autoSaveNow();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "autoSaveNow();";
}
}));
}
public void setImage(MakesBufferedImage image) {
imageID = null;
setImage(image == null ? null : image.getBufferedImage());
}
public void newImageFromSurface() {
setImage(imageSurface.getImage());
}
public void setImage(BufferedImage image) {
setImage(image, false);
}
public void setImage(BufferedImage image, boolean loadingFromAutoSave) {
this.image = image;
imageID = null;
if (imageSurface != null) {
AutoCloseable __47 = tempSetField(imageSurface, "onNewImage", null);
try {
imageSurface.setImage(image);
if (zoomToWindowOnSetImage)
imageSurface.zoomToWindow();
if (autoSaveToDisk && !loadingFromAutoSave)
autoSaveNow();
} finally {
_close(__47);
}
}
vmBus_send("newImage", this);
pcallF(onNewImage, image);
}
public void setImage(String imageID) {
if (sameSnippetID(this.imageID, imageID))
return;
setImage(loadImage2(imageID));
this.imageID = imageID;
}
public File autoSaveImageFile() {
String id = dm_moduleID(me());
return javaxDataDir("Image Autosaves/" + id + "-autosave.png");
}
public BufferedImage getImage() {
if (useUpdateHack) {
ImageSurface is = imageSurface;
if (is != null && is.getImage() != image)
setImage(is.getImage());
}
return image;
}
public boolean hasImage() {
return image != null;
}
public void setZoom(double zoom) {
if (imageSurface != null)
imageSurface.setZoom(zoom);
}
public Rect getSelection() {
return imageSurface == null ? null : toRect(imageSurface.getSelection());
}
public void setSelection(Rect r) {
if (imageSurface != null)
imageSurface.setSelection(toRectangle(r));
}
public int imageWidth() {
return imageSurface.getImage().getWidth();
}
public int imageHeight() {
return imageSurface.getImage().getHeight();
}
}
abstract static public class DynCalculatedList extends DynModule {
transient public JList list;
transient public List results;
transient public boolean calculateWhenHidden = false;
public JComponent visualize() {
return list = jlist(calc());
}
public void unvisualize() {
list = null;
}
public void update() {
AutoCloseable __52 = enter();
try {
if (list != null || calculateWhenHidden)
fillListWithStrings(list, results = calc());
} finally {
_close(__52);
}
}
abstract public List calc();
public void scrollDown() {
scrollAllTheWayDown(list);
}
public String selected() {
return selectedItem(list);
}
}
static public Object creator() {
return callOpt(assertNotNull("No real MC", realMC_tl()).get(), "creator");
}
static public String programID;
static public String getProgramID() {
Object mc = realMC_tl().get();
if (mc != null)
return getProgramID(mc);
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 Concepts db_mainConcepts() {
return (Concepts) call(assertNotNull("No real MC", realMC()), "db_mainConcepts");
}
static public List myInnerClasses_list = litlist(null, "Derefable", "Var", "SecretValue", "ImageSurface", "BWImage", "talkToThisVM_IO", "IFieldIndex", "Str", "SingleComponentPanel", "DynModule", "FixedRateTimer", "Rect", "Pt", "AbstractLayoutManager", "IterableIterator", "betterCIComparator_C", "RemoteDB", "MakesBufferedImage", "SynchronizedArrayList", "ScannedBot", "Concepts", "RC", "XRef", "CloseableIterableIterator", "PNGFile", "getOpt_Map", "IFieldsToList", "structure_Data", "IVar", "Matches", "HCRUD_Concepts", "TableWithTooltips", "DynCalculatedList", "Surface", "Q", "OrError", "LongRange", "CriticalAction", "IResourceLoader", "MultiSet", "DynObjectTable", "DialogIO", "HCRUD_Data", "SimpleCRUD", "SynchronizedArrayList_Base", "IntRange", "IConceptCounter", "BetterLabel", "componentPopupMenu_Adapter", "MRUCache", "AlphanumComparator", "PersistableThrowable", "talkToSubBot_IO", "Scored", "RGBImage", "SmartTimerTask", "HasIndex", "Responder", "VF2", "TableSearcher", "JSection", "ValueConverterForField", "TokCondition", "HTML", "RightAlignedLine", "GlobalID", "HCRUD", "listPopupMenu_Maker", "findCodeTokens_Matcher", "ReliableSingleThread", "JFastLogView_noWrap", "ImageSurfaceSelector", "Concept", "IBWImage", "AutoComboBox", "ProgramScan", "F0", "HAbstractRenderable", "Snippet", "F1", "DynImageSurface", "F2", "RGB", "RandomAccessAbstractList", "Flag", "unstructure_Receiver", "ContentsIndexedList", "IF0", "BaseXRef", "DefaultValueConverterForField", "IContentsIndexedList2", "IF2", "Producer", "IF1", "IF3", "tablePopupMenu_Maker", "IVF1", "IVF2", "Cache", "_MethodCache", "talkTo_IO", "structure_ClassInfo", "LiveValue", "IContentsIndexedList", "LetterLayout", "DialogHandler", "Lowest", "proxy_InvocationHandler", "HTMLPaginator", "Pair", "DynPrintLog", "UniqueString", "TransferableImage", "IConceptIndex", "Android3", "DynamicMethods");
static public List myInnerClasses() {
return myInnerClasses_list;
}
static public DynModule dm_currentModule() {
return (DynModule) dm_current_generic();
}
static public void cancelTimerOrInterruptThread(Object timer) {
if (timer instanceof Thread && !(timer instanceof AutoCloseable))
interruptThread((Thread) timer);
else
cancelTimer(timer);
}
static public RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
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 _handleError(Error e) {
call(javax(), "_handleError", e);
}
static public boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static public 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(String msg) {
throw new RuntimeException(msg == null ? "" : msg);
}
static public RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
static public void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static public boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
static public Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static public int isAndroid_flag;
static public boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static public Boolean isHeadless_cache;
static public boolean isHeadless() {
if (isHeadless_cache != null)
return isHeadless_cache;
if (isAndroid())
return isHeadless_cache = true;
if (GraphicsEnvironment.isHeadless())
return isHeadless_cache = true;
try {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) {
return isHeadless_cache = true;
}
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static public String joinWithSpace(Iterable c) {
return join(" ", c);
}
static public String joinWithSpace(String... c) {
return join(" ", c);
}
static public Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static public int javaTok_n, javaTok_elements;
static public boolean javaTok_opt = false;
static public List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static public void print_append(Appendable buf, String s, int max) {
try {
synchronized (buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static public A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
static public boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
static public Object get(Object o, String field) {
try {
if (o == null)
return null;
if (o instanceof Class)
return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static public Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static public Object get_raw(Object o, String field) {
try {
if (o == null)
return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static public Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static public Object get(String field, Object o) {
return get(o, field);
}
static public Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static public Object getOpt(String field, Object o) {
return getOpt_cached(o, field);
}
static public Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null)
return null;
makeAccessible(f);
return f.get(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object getOpt(Class c, String field) {
try {
if (c == null)
return null;
Field f = getOpt_findStaticField(c, field);
if (f == null)
return null;
makeAccessible(f);
return f.get(null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public A set(A o, String field, Object value) {
if (o == null)
return null;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
static public void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static public Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static public Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
static public void setOpt(Object o, String field, Object value) {
try {
if (o == null)
return;
Class c = o.getClass();
HashMap map;
if (getOpt_cache == null)
map = getOpt_makeCache(c);
else
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null) {
smartSet(f, o, value);
return;
}
if (o instanceof DynamicObject)
setDyn(((DynamicObject) o), field, value);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void setOpt(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field setOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
makeAccessible(f);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public void setOpt_raw(Object o, String field, Object value) {
try {
if (o == null)
return;
if (o instanceof Class)
setOpt_raw((Class) o, field, value);
else {
Field f = setOpt_raw_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
smartSet(f, o, value);
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void setOpt_raw(Class c, String field, Object value) {
try {
if (c == null)
return;
Field f = setOpt_raw_findStaticField(c, field);
if (f != null) {
makeAccessible(f);
smartSet(f, null, value);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Field setOpt_raw_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public Field setOpt_raw_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public Map> callF_cache = newDangerousWeakHashMap();
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMCWithVarArgs((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null)
return null;
Class c = f.getClass();
ArrayList methods;
synchronized (callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1)
return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods()) if (m.getName().equals("get")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty())
break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] { arg });
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static public Object callOpt(Object o) {
return callF(o);
}
static public A callOpt(Object o, String method, Object... args) {
return (A) callOpt_withVarargs(o, method, args);
}
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 Map uniqueString_map = weakHashMap();
static public UniqueString uniqueString(String s) {
if (s == null)
return null;
synchronized (uniqueString_map) {
UniqueString us = uniqueString_map.get(s);
if (us == null)
uniqueString_map.put(s, us = new UniqueString(s, true));
return us;
}
}
static public UniqueString uniqueString(CharSequence s) {
return s == null ? null : uniqueString(str(s));
}
static public FixedRateTimer doEvery(long delay, final Object r) {
return doEvery(delay, delay, r);
}
static public FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
return vmBus_timerStarted(timer);
}
static public FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
}
static public FixedRateTimer doEvery(double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), r);
}
static public java.util.Timer doLater(long delay, final Object r) {
ping();
final java.util.Timer timer = new java.util.Timer();
timer.schedule(timerTask(r, timer), delay);
return vmBus_timerStarted(timer);
}
static public java.util.Timer doLater(double delaySeconds, final Object r) {
return doLater(toMS(delaySeconds), r);
}
static public boolean hasBot(String searchPattern) {
try {
DialogIO io = findBot(searchPattern);
if (io != null) {
io.close();
return true;
} else
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
static public JLabel jlabel() {
return jlabel(" ");
}
static public JTextArea newTypeWriterTextArea() {
return newTypeWriterTextArea("");
}
static public JTextArea newTypeWriterTextArea(String text) {
return setFont(jTextArea(text), typeWriterFont());
}
static public String struct(Object o) {
return structure(o);
}
static public String struct(Object o, structure_Data data) {
return structure(o, data);
}
static public String sfu(Object o) {
return structureForUser(o);
}
static public String loadPageSilentlyWithTimeout(double timeoutSeconds, String url) {
return loadPageSilentlyWithTimeout(url, toMS_int(timeoutSeconds));
}
static public String loadPageSilentlyWithTimeout(int timeout, String url) {
return loadPageSilentlyWithTimeout(url, timeout);
}
static public String loadPageSilentlyWithTimeout(String url, int timeout) {
try {
url = loadPage_preprocess(url);
URL _url = new URL(url);
return loadPage(setURLConnectionTimeouts(_url.openConnection(), timeout), _url);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean loadPageWithUserAgent_verbose = false;
static public String loadPageWithUserAgent(String url, String userAgent) {
try {
URL tURL = new URL(url);
URLConnection conn = tURL.openConnection();
conn.setRequestProperty("User-Agent", userAgent);
loadPage_anonymous = true;
if (loadPageWithUserAgent_verbose)
print("Loading as " + userAgent + ": " + hideCredentials(url));
return loadPage(conn, tURL);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void db() {
conceptsAndBot();
}
static public void db(Integer autoSaveInterval) {
conceptsAndBot(autoSaveInterval);
}
static public A cget(Object c, String field) {
Object o = getOpt(c, field);
if (o instanceof Concept.Ref)
return (A) ((Concept.Ref) o).get();
return (A) o;
}
static public A cget(String field, Object c) {
return cget(c, field);
}
static public int cset(Concept c, Object... values) {
try {
if (c == null)
return 0;
warnIfOddCount(values = expandParams(c.getClass(), values));
int changes = 0;
for (int i = 0; i + 1 < l(values); i += 2) if (_csetField(c, (String) values[i], values[i + 1]))
++changes;
return changes;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public int cset(Iterable extends Concept> l, Object... values) {
int changes = 0;
for (Concept c : unnull(l)) changes += cset(c, values);
return changes;
}
static volatile public StringBuffer local_log = new StringBuffer();
static volatile public Appendable print_log = local_log;
static volatile public int print_log_max = 1024 * 1024;
static volatile public int local_log_max = 100 * 1024;
static public boolean print_silent = false;
static public Object print_byThread_lock = new Object();
static volatile public ThreadLocal print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = o + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
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;
print_raw(s);
}
static public void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
vmBus_send("printed", mc(), s);
}
static public void print_autoRotate() {
}
static public ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public List> _threadInfo_makers = synchroList();
static public Object _threadInfo() {
if (empty(_threadInfo_makers))
return null;
HashMap map = new HashMap();
pcallFAll(_threadInfo_makers, map);
return map;
}
static public List> _threadInheritInfo_retrievers = synchroList();
static public void _threadInheritInfo(Object info) {
if (info == null)
return;
pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
static public void _threadInfo_addMakerAndRetriever(VF1 maker, VF1 retriever) {
_threadInfo_makers.add(maker);
_threadInheritInfo_retrievers.add(retriever);
}
static public boolean match(String pat, String s) {
return match3(pat, s);
}
static public boolean match(String pat, String s, Matches matches) {
return match3(pat, s, matches);
}
static public boolean match(String pat, List toks, Matches matches) {
return match3(pat, toks, matches);
}
static public Field getField(Object o, String field) {
if (o == null)
return null;
return setOpt_findField(_getClass(o), field);
}
static public Class fieldType(Object o, String field) {
Field f = getField(o, field);
return f == null ? null : f.getType();
}
static public String format3(String pat, Object... args) {
if (args.length == 0)
return pat;
List tok = javaTokPlusPeriod(pat);
int argidx = 0;
for (int i = 1; i < tok.size(); i += 2) if (tok.get(i).equals("*"))
tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null"));
return join(tok);
}
static public String format3_formatArg(Object arg) {
if (arg == null)
return "null";
if (arg instanceof String) {
String s = (String) arg;
return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s);
}
if (arg instanceof Integer || arg instanceof Long)
return String.valueOf(arg);
return quote(structure(arg));
}
static public Set vm_generalIdentityHashSet(Object name) {
synchronized (get(javax(), "generalMap")) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = syncIdentityHashSet());
return set;
}
}
static public Map vm_generalHashMap(Object name) {
synchronized (get(javax(), "generalMap")) {
Map m = (Map) (vm_generalMap_get(name));
if (m == null)
vm_generalMap_put(name, m = syncHashMap());
return m;
}
}
static public Map vm_generalWeakSubMap(Object name) {
synchronized (get(javax(), "generalMap")) {
Map map = (Map) (vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = newWeakMap());
return map;
}
}
static public A bindToComponent(final A component, final Runnable onShow, final Runnable onUnShow) {
{
swing(new Runnable() {
public void run() {
try {
final Var flag = new Var<>(false);
component.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
if (flag.get())
print("Warning: bindToComponent logic failure");
flag.set(true);
pcallF(onShow);
}
public void ancestorRemoved(AncestorEvent event) {
if (!flag.get())
print("Warning: bindToComponent logic failure");
flag.set(false);
pcallF(onUnShow);
}
public void ancestorMoved(AncestorEvent event) {
}
});
if (component.isShowing()) {
flag.set(true);
pcallF(onShow);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final Var flag = new(false);\r\n component.addAncestorListener(new ...";
}
});
}
return component;
}
static public A bindToComponent(A component, Runnable onShow) {
return bindToComponent(component, onShow, null);
}
static public int loadPage_defaultTimeout = 60000;
static public ThreadLocal loadPage_charset = new ThreadLocal();
static public boolean loadPage_allowGzip = true, loadPage_debug;
static public boolean loadPage_anonymous = false;
static public int loadPage_verboseness = 100000;
static public int loadPage_retries = 1;
static public ThreadLocal loadPage_silent = new ThreadLocal();
static volatile public int loadPage_forcedTimeout;
static public ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal();
static public ThreadLocal>> loadPage_responseHeaders = new ThreadLocal();
static public ThreadLocal> loadPage_extraHeaders = new ThreadLocal();
static public ThreadLocal loadPage_sizeLimit = new ThreadLocal();
public static String loadPageSilently(String url) {
try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadPageSilently(URL url) {
try {
if (!networkAllowanceTest(str(url)))
throw fail("Not allowed: " + url);
IOException e = null;
for (int tries = 0; tries < loadPage_retries; tries++) try {
URLConnection con = loadPage_openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPageThroughProxy_enabled) {
print("Trying proxy because of: " + e);
try {
return loadPageThroughProxy(str(url));
} catch (Throwable e2) {
print(" " + exceptionToStringShort(e2));
}
} else if (loadPage_debug)
print(exceptionToStringShort(e));
if (tries < loadPage_retries - 1)
sleepSeconds(1);
}
throw e;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage_preprocess(String url) {
if (url.startsWith("tb/"))
url = tb_mainServer() + "/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
static public String loadPage(String url) {
try {
url = loadPage_preprocess(url);
if (!isTrue(loadPage_silent.get()))
printWithTime("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage(URL url) {
return loadPage(url.toExternalForm());
}
static public String loadPage(URLConnection con, URL url) throws IOException {
return loadPage(con, url, true);
}
static public String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
Long limit = optPar(loadPage_sizeLimit);
if (addHeaders)
try {
if (!loadPage_anonymous)
setHeaders(con);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
con.setRequestProperty("X-No-Cookies", "1");
for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
} catch (Throwable e) {
}
vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
loadPage_responseHeaders.set(con.getHeaderFields());
InputStream in = null;
try {
in = urlConnection_getInputStream(con);
if (loadPage_debug)
print("Put stream in map: " + currentThread());
String contentType = con.getContentType();
if (contentType == null) {
throw new IOException("Page could not be read: " + hideCredentials(url));
}
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null)
charset = loadPage_guessCharset(contentType);
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = newGZIPInputStream(in);
}
Reader r;
try {
r = new InputStreamReader(in, unquote(charset));
} catch (UnsupportedEncodingException e) {
print(toHex(utf8(charset)));
throw e;
}
boolean silent = isTrue(loadPage_silent.get());
StringBuilder buf = new StringBuilder();
int n = 0;
while (limit == null || n < limit) {
ping();
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
if (!silent && (n % loadPage_verboseness) == 0)
print(" " + n + " chars read");
}
return buf.toString();
} finally {
if (loadPage_debug)
print("loadPage done");
vm_generalSubMap("URLConnection per thread").remove(currentThread());
if (in != null)
in.close();
}
}
static public String loadPage_guessCharset(String contentType) {
Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
String match = m.matches() ? m.group(1) : null;
if (loadPage_debug)
print("loadPage: contentType=" + contentType + ", match: " + match);
return or(match, "UTF-8");
}
static public URLConnection loadPage_openConnection(URL url) {
URLConnection con = openConnection(url);
int timeout = toInt(loadPage_forcedTimeout_byThread.get());
if (timeout == 0)
timeout = loadPage_forcedTimeout;
if (timeout != 0)
setURLConnectionTimeouts(con, loadPage_forcedTimeout);
else
setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
return con;
}
static public String loadPage_utf8(URL url) {
return loadPage_utf8(url.toString());
}
static public String loadPage_utf8(String url) {
AutoCloseable __1 = tempSetTL(loadPage_charset, "UTF-8");
try {
return loadPage(url);
} finally {
_close(__1);
}
}
static public String loadPage_utf8(URLConnection con, URL url, boolean addHeaders) throws IOException {
AutoCloseable __2 = tempSetTL(loadPage_charset, "UTF-8");
try {
return loadPage(con, url, addHeaders);
} finally {
_close(__2);
}
}
static public boolean preferCached = false;
static public boolean loadSnippet_debug = false;
static public ThreadLocal loadSnippet_silent = new ThreadLocal();
static public ThreadLocal loadSnippet_publicOnly = new ThreadLocal();
static public int loadSnippet_timeout = 30000;
static public String loadSnippet(Snippet s) {
return loadSnippet(s.id);
}
static public String loadSnippet(String snippetID) {
try {
if (snippetID == null)
return null;
return loadSnippet(parseSnippetID(snippetID), preferCached);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadSnippet(String snippetID, boolean preferCached) throws IOException {
return loadSnippet(parseSnippetID(snippetID), preferCached);
}
static public IF1 loadSnippet;
static public String loadSnippet(long snippetID) {
return loadSnippet != null ? loadSnippet.get(snippetID) : loadSnippet_base(snippetID);
}
final static public String loadSnippet_fallback(IF1 _f, long snippetID) {
return _f != null ? _f.get(snippetID) : loadSnippet_base(snippetID);
}
static public String loadSnippet_base(long snippetID) {
try {
return loadSnippet(snippetID, preferCached);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadSnippet(long snippetID, boolean preferCached) throws IOException {
String text;
if (isLocalSnippetID(snippetID))
return loadLocalSnippet(snippetID);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadSnippet(fsI(snippetID));
initSnippetCache();
text = DiskSnippetCache_get(snippetID);
if (preferCached && text != null)
return text;
try {
if (loadSnippet_debug && text != null)
System.err.println("md5: " + md5(text));
String url = tb_mainServer() + "/getraw.php?id=" + snippetID + "&utf8=1";
if (nempty(text))
url += "&md5=" + md5(text);
if (!isTrue(loadSnippet_publicOnly.get()))
url += standardCredentials();
String text2 = loadSnippet_loadFromServer(url);
boolean same = eq(text2, "==*#*==");
if (loadSnippet_debug)
print("loadSnippet: same=" + same);
if (!same)
text = text2;
} catch (RuntimeException e) {
e.printStackTrace();
throw new IOException("Snippet #" + snippetID + " not found or not public");
}
try {
initSnippetCache();
DiskSnippetCache_put(snippetID, text);
} catch (IOException e) {
System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")");
}
return text;
}
static public File DiskSnippetCache_dir;
public static void initDiskSnippetCache(File dir) {
DiskSnippetCache_dir = dir;
dir.mkdirs();
}
public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
}
static public File DiskSnippetCache_getFile(long snippetID) {
return new File(DiskSnippetCache_dir, "" + snippetID);
}
public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
}
public static File DiskSnippetCache_getDir() {
return DiskSnippetCache_dir;
}
public static void initSnippetCache() {
if (DiskSnippetCache_dir == null)
initDiskSnippetCache(getGlobalCache());
}
static public String loadSnippet_loadFromServer(String url) {
Integer oldTimeout = setThreadLocal(loadPage_forcedTimeout_byThread, loadSnippet_timeout);
try {
return isTrue(loadSnippet_silent.get()) ? loadPageSilently(url) : loadPage(url);
} finally {
loadPage_forcedTimeout_byThread.set(oldTimeout);
}
}
static public String loadSnippetQuietly(Snippet s) {
return loadSnippetQuietly(s.id);
}
static public String loadSnippetQuietly(String snippetID) {
loadSnippet_silent.set(true);
try {
return loadSnippet(snippetID);
} finally {
loadSnippet_silent.set(null);
}
}
static public String sendToLocalBot(String bot, String text, Object... args) {
text = format3(text, args);
DialogIO channel = findBot(bot);
try {
if (channel == null)
throw fail(quote(bot) + " not found");
try {
channel.readLine();
print(bot + "> " + shorten(text, 80));
channel.sendLine(text);
String s = channel.readLine();
print(bot + "< " + shorten(s, 80));
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public String sendToLocalBot(int port, String text, Object... args) {
text = format3(text, args);
DialogIO channel = talkTo(port);
try {
try {
channel.readLine();
print(port + "> " + shorten(text, 80));
channel.sendLine(text);
String s = channel.readLine();
print(port + "< " + shorten(s, 80));
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public String sendToLocalBotOpt(String bot, String text, Object... args) {
if (bot == null)
return null;
text = format(text, args);
DialogIO channel = findBot(bot);
try {
if (channel == null) {
print(quote(bot) + " not found, skipping send: " + quote(text));
return null;
}
try {
channel.readLine();
print(shorten(bot + "> " + text, 200));
channel.sendLine(text);
String s = channel.readLine();
print(shorten(bot + "< " + s, 200));
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public String sendToLocalBotQuietly(String bot, String text, Object... args) {
text = format3(text, args);
DialogIO channel = newFindBot2(bot);
try {
if (channel == null)
throw fail(quote(bot) + " not found");
try {
channel.readLine();
channel.sendLine(text);
String s = channel.readLine();
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public String sendToLocalBotQuietly(int port, String text, Object... args) {
text = format3(text, args);
DialogIO channel = talkTo(port);
try {
try {
channel.readLine();
channel.sendLine(text);
String s = channel.readLine();
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public JTable sexyTableWithoutDrag() {
final JTable table = tableWithToolTips();
tablePopupMenu(table, sexyTableWithoutDrag_popupMenuMaker(table));
table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
((InputMap) UIManager.get("Table.ancestorInputMap")).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
return table;
}
static public VF2 sexyTableWithoutDrag_popupMenuMaker(JTable t) {
final WeakReference ref = weakRef(t);
return new VF2() {
public void get(JPopupMenu menu, Integer row) {
try {
final JTable table = ref.get();
final String item = first(getTableLine(table, row));
MouseEvent e = tablePopupMenu_mouseEvent.get();
final int col = table.columnAtPoint(e.getPoint());
final Object value = table.getModel().getValueAt(row, col);
if (value instanceof ImageIcon) {
addMenuItem(menu, "Copy image to clipboard", new Runnable() {
public void run() {
try {
copyImageToClipboard(((ImageIcon) value).getImage());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyImageToClipboard(((ImageIcon) value).getImage());";
}
});
} else {
final String text = str(value);
addMenuItem(menu, "Copy text to clipboard", new Runnable() {
public void run() {
try {
copyTextToClipboard(text);
print("Copied text to clipboard: " + quote(text));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyTextToClipboard(text);\r\n print(\"Copied text to clipboard: \" + quot...";
}
});
}
addMenuItem(menu, "Set row height...", new Runnable() {
public void run() {
try {
final JTextField tf = jTextField(table.getRowHeight());
showTitledForm("Set row height", "Pixels", tf, new Runnable() {
public void run() {
try {
table.setRowHeight(parseInt(trim(tf.getText())));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "table.setRowHeight(parseInt(trim(tf.getText())))";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JTextField tf = jTextField(table.getRowHeight());\r\n showTitledForm...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JTable table = ref!;\r\n final S item = first(getTableLine(table, row)...";
}
};
}
static public class tablePopupMenu_Maker {
public List menuMakers = new ArrayList();
}
static public Map tablePopupMenu_map = newWeakHashMap();
static public ThreadLocal tablePopupMenu_mouseEvent = new ThreadLocal();
static public ThreadLocal tablePopupMenu_first = new ThreadLocal();
static public void tablePopupMenu(final JTable table, final Object menuMaker) {
final boolean first = isTrue(getAndClearThreadLocal(tablePopupMenu_first));
{
swing(new Runnable() {
public void run() {
try {
tablePopupMenu_Maker maker = tablePopupMenu_map.get(table);
if (maker == null) {
tablePopupMenu_map.put(table, maker = new tablePopupMenu_Maker());
final tablePopupMenu_Maker _maker = maker;
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
displayMenu(e);
}
public void mouseReleased(MouseEvent e) {
displayMenu(e);
}
public void displayMenu(MouseEvent e) {
if (!e.isPopupTrigger())
return;
JPopupMenu menu = new JPopupMenu();
int row = table.rowAtPoint(e.getPoint());
if (table.getSelectedRowCount() < 2)
table.setRowSelectionInterval(row, row);
int modelRow = convertTableRowToModel(table, row);
int emptyCount = menu.getComponentCount();
tablePopupMenu_mouseEvent.set(e);
for (Object menuMaker : _maker.menuMakers) pcallF(menuMaker, menu, modelRow);
vmBus_send("showingPopupMenu", table, menu);
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
if (first)
maker.menuMakers.add(0, menuMaker);
else
maker.menuMakers.add(menuMaker);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tablePopupMenu_Maker maker = tablePopupMenu_map.get(table);\r\n if (maker ==...";
}
});
}
}
static public void tablePopupMenuFirst(JTable table, final Object menuMaker) {
tablePopupMenu_first.set(true);
tablePopupMenu(table, menuMaker);
}
static public ThreadLocal componentPopupMenu_mouseEvent;
static public void componentPopupMenu_init() {
{
swing(new Runnable() {
public void run() {
try {
if (componentPopupMenu_mouseEvent == null)
componentPopupMenu_mouseEvent = (ThreadLocal) vm_generalMap_get("mouseEvent");
if (componentPopupMenu_mouseEvent == null)
vm_generalMap_put("componentPopupMenu_mouseEvent", componentPopupMenu_mouseEvent = new ThreadLocal());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (componentPopupMenu_mouseEvent == null)\r\n componentPopupMenu_mouseEve...";
}
});
}
}
static public void componentPopupMenu(final JComponent component, final Object menuMaker) {
if (component == null || menuMaker == null)
return;
{
swing(new Runnable() {
public void run() {
try {
Object adapter = componentPopupMenu_initForComponent(component);
((List) _get(adapter, "maker")).add(menuMaker);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Object adapter = componentPopupMenu_initForComponent(component);\r\n ((List)...";
}
});
}
}
static public Object componentPopupMenu_initForComponent(final JComponent component) {
return component == null ? null : swing(new F0() {
public Object get() {
try {
componentPopupMenu_init();
Object adapter = findComponentPopupMenuListener_gen(component);
if (adapter == null) {
componentPopupMenu_Adapter a = new componentPopupMenu_Adapter();
component.addMouseListener(a);
adapter = a;
}
return adapter;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "componentPopupMenu_init();\r\n O adapter = findComponentPopupMenuListener_ge...";
}
});
}
static public class componentPopupMenu_Adapter extends MouseAdapter {
public List maker = new ArrayList();
public boolean internalFrameLeftButtonMagic = false;
public Point pressedAt;
public void mousePressed(MouseEvent e) {
displayMenu(e);
pressedAt = internalFrameLeftButtonMagic && e.getClickCount() == 1 && internalFrameActive(e.getComponent()) ? e.getLocationOnScreen() : null;
}
public void mouseReleased(MouseEvent e) {
if (internalFrameLeftButtonMagic && eq(pressedAt, e.getLocationOnScreen()))
displayMenu2(e);
else
displayMenu(e);
}
public void displayMenu(MouseEvent e) {
if (e.getSource() instanceof JInternalFrame)
return;
if (e.isPopupTrigger())
displayMenu2(e);
}
public void displayMenu2(MouseEvent e) {
JPopupMenu menu = new JPopupMenu();
int emptyCount = menu.getComponentCount();
AutoCloseable __1 = tempSetTL(componentPopupMenu_mouseEvent, e);
try {
for (Object menuMaker : maker) pcallF(menuMaker, menu);
vmBus_send("showingPopupMenu", e.getComponent(), menu);
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
} finally {
_close(__1);
}
}
}
static public void componentPopupMenu_top(final JComponent component, final VF1 menuMaker) {
if (component != null && menuMaker != null) {
swing(new Runnable() {
public void run() {
try {
Object adapter = componentPopupMenu_initForComponent(component);
((List) get(adapter, "maker")).add(0, menuMaker);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Object adapter = componentPopupMenu_initForComponent(component);\r\n ((List)...";
}
});
}
}
static public MouseEvent componentPopupMenu_getEvent() {
return componentPopupMenu_mouseEvent.get();
}
static public InheritableThreadLocal dm_currentModule_value = new InheritableThreadLocal();
static public Object dm_current_generic() {
return getWeakRef(dm_currentModule_value.get());
}
static public void cleanMeUp_dm_current_generic() {
dm_currentModule_value = new InheritableThreadLocal();
}
static public Object dm_current_mandatory_generic() {
return assertNotNull("No module set", dm_current_generic());
}
static public Object withDBLock(Object r) {
Lock __0 = db_mainConcepts().lock;
lock(__0);
try {
return callF(r);
} finally {
unlock(__0);
}
}
static public A withDBLock(F0 r) {
return (A) withDBLock((Object) r);
}
static public Object withDBLock(Concepts concepts, Object r) {
Lock __1 = concepts.lock;
lock(__1);
try {
return callF(r);
} finally {
unlock(__1);
}
}
static public A withDBLock(Concepts concepts, F0 r) {
return (A) withDBLock(concepts, (Object) r);
}
static public A withDBLock(Concept concept, IF0 r) {
return (A) withDBLock(concept._concepts, r);
}
static public void makePopupMenuConditional(final JComponent c, final F0 condition) {
if (c != null && condition != null) {
swing(new Runnable() {
public void run() {
try {
final componentPopupMenu_Adapter adapter = firstInstanceOf(c.getMouseListeners(), componentPopupMenu_Adapter.class);
c.removeMouseListener(adapter);
c.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (!callF(condition))
adapter.mousePressed(e);
}
public void mouseReleased(MouseEvent e) {
if (!callF(condition))
adapter.mouseReleased(e);
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final componentPopupMenu_Adapter adapter = firstInstanceOf(c.getMouseListener...";
}
});
}
}
static public boolean dynamicObjectIsLoading() {
return isTrue(getThreadLocal(DynamicObject_loading));
}
static public Object interceptPrintInThisThread(Object f) {
Object old = print_byThread().get();
print_byThread().set(f);
return old;
}
static public void rowSorter_setComparators(JTable table, final Object... params) {
setTableModel_fixSorter.put(table, new VF2() {
public void get(JTable table, RowSorter sorter) {
try {
if (sorter instanceof TableRowSorter) {
for (Pair p : (List>) (List) paramsToPairs(params)) ((TableRowSorter) sorter).setComparator(p.a, p.b);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "//print(\"Fixing table sorter\");\r\n if (sorter cast TableRowSorter) {\r\n ...";
}
});
}
static public boolean directNohupJava_loggingOn = true;
static public File directNohupJavax(String javaxargs) {
return directNohupJavax(javaxargs, javaxDefaultVMArgs());
}
static public File directNohupJavax(final String _javaxargs, final String _vmArgs) {
if (directNohupJava_loggingOn)
appendToLocalMechLog("nohupJavax Log", sfu(dropSecondIfEmpty(str(parseFirstInt(_javaxargs)), _vmArgs)));
String javaxargs = _javaxargs.trim();
if (javaxargs.startsWith("#"))
javaxargs = javaxargs.substring(1);
String snippetID = javaTok(javaxargs).get(1);
int idx = javaxargs.indexOf(' ');
String args = idx < 0 ? "" : javaxargs.substring(idx + 1).trim();
String vmArgs = trim(_vmArgs);
if (empty(vmArgs) && usePreSpunVMs()) {
String line;
if (args.length() != 0)
line = format3("please start program * with arguments *", snippetID, args);
else
line = format3("please start program *", snippetID);
String answer = sendToLocalBotOpt("A pre-spun VM.", line);
if (match3("ok", answer)) {
print("OK, used pre-spun VM.");
return null;
}
if (answer != null)
print("> " + answer);
print("Using standard nohup.");
}
return classicNohupJavax(javaxargs, vmArgs);
}
static public boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static public boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
static public A setToolTipText(final A c, final Object toolTip) {
if (c == null)
return null;
{
swing(new Runnable() {
public void run() {
try {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ...";
}
});
}
return c;
}
static public A setToolTipText(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
static public String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static public Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
static public List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
static public void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static public void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
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 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 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 Object swing(Object f) {
return swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public void removeAll(Collection a, Collection b) {
if (a != null && b != null)
a.removeAll(b);
}
static public void removeAll(Map a, Collection b) {
if (a != null && b != null)
for (A x : b) a.remove(x);
}
static public void add(BitSet bs, int i) {
bs.set(i);
}
static public boolean add(Collection c, A a) {
return c != null && c.add(a);
}
static public void add(Container c, Component x) {
addToContainer(c, x);
}
static public 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 _revalidate(A c) {
return revalidate(c);
}
static public void _revalidate(JFrame f) {
revalidate(f);
}
static public void _revalidate(JInternalFrame f) {
revalidate(f);
}
static public Container _getParent(Component c) {
return getParent(c);
}
static public boolean stdEq2(Object a, Object b) {
if (a == null)
return b == null;
if (b == null)
return false;
if (a.getClass() != b.getClass())
return false;
for (String field : allFields(a)) if (neq(getOpt(a, field), getOpt(b, field)))
return false;
return true;
}
static public int stdHash2(Object a) {
if (a == null)
return 0;
return stdHash(a, toStringArray(allFields(a)));
}
static public void fillArrayUnlessZero(byte[] a, byte value) {
if (value != 0)
Arrays.fill(a, value);
}
static public void fillArrayUnlessZero(int[] a, int value) {
if (value != 0)
Arrays.fill(a, value);
}
static public void fillArrayUnlessZero(float[] a, float value) {
if (value != 0)
Arrays.fill(a, value);
}
static public boolean inRange(int x, int n) {
return x >= 0 && x < n;
}
static public boolean inRange(int x, int a, int b) {
return x >= a && x < b;
}
static public int ubyteToInt(byte b) {
return b & 0x0FF;
}
static public double averageBrightness(BufferedImage img) {
return new BWImage(img).averageBrightness();
}
static public int limitToUByte(int i) {
return max(0, min(255, i));
}
static public void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
printStackTrace(e);
rethrow(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static public void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static public ReentrantLock lock() {
return fairLock();
}
static public boolean hasLock(Lock lock) {
return ((ReentrantLock) lock).isHeldByCurrentThread();
}
static public long sysNow() {
ping();
return System.nanoTime() / 1000000;
}
static public void unlock(Lock lock, String msg) {
if (lock == null)
return;
lock.unlock();
print("Unlocked: " + msg);
}
static public void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
}
static public void clear(Collection c) {
if (c != null)
c.clear();
}
static public void clear(Map map) {
if (map != null)
map.clear();
}
static public Set synchroHashSet() {
return Collections.synchronizedSet(new HashSet ());
}
static public Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static public Flag dm_initErrorHandling_flag = new Flag();
static public void dm_initErrorHandling() {
raiseFlagAndDo(dm_initErrorHandling_flag, new Runnable() {
public void run() {
try {
_handleException_addHandler("dm_initErrorHandling_handler");
assertNull(_onRegisterThread);
_onRegisterThread = new VF1() {
public void get(Thread t) {
try {
DynModule m = dm_currentModule();
if (m == null)
printStackTrace("New thread made outside of a module");
else
m.ownTimer(t);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "DynModule m = dm_currentModule();\r\n if (m == null) printStackTrace(\"New ...";
}
};
_threadInfo_makers.add(new VF1() {
public void get(Map map) {
try {
mapPut(map, "dm_currentModule_value", dm_currentModule());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "mapPut(map, 'dm_currentModule_value, dm_currentModule())";
}
});
_threadInheritInfo_retrievers.add(new VF1() {
public void get(Map map) {
try {
Object mod = map.get("dm_currentModule_value");
if (mod instanceof DynModule)
dm_currentModule_value.set(new WeakReference((DynModule) mod));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "O mod = map.get('dm_currentModule_value);\r\n if (mod instanceof DynModule...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_handleException_addHandler(f dm_initErrorHandling_handler);\r\n \r\n asser...";
}
});
}
static public void dm_initErrorHandling_handler(Throwable e) {
DynModule m = dm_currentModule();
if (m == null)
print("Weird: Error outside of module");
else
m.setField("_error", persistableThrowable(e));
}
static public void setMainDesktopPane(JDesktopPane desktop) {
mainDesktopPane_value = desktop;
}
static public A getCreatorOpt(String field) {
return (A) getOpt(creator(), field);
}
static public boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null)
return false;
if (o instanceof ThreadLocal)
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static public boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public A possiblyInternalFrameTitle(A c, String title) {
JInternalFrame f = getInternalFrame(c);
if (f != null)
internalFrameTitle(f, title);
else
frameTitle(getFrame(c), title);
return c;
}
static public String possiblyInternalFrameTitle(Component c) {
JInternalFrame f = getInternalFrame(c);
return f != null ? internalFrameTitle(f) : frameTitle(getFrame(c));
}
static public void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static public void ownResource(AutoCloseable c) {
_registerAutoCloseable(c);
}
static public List getAndClearList(Collection l) {
if (l == null)
return emptyList();
synchronized (collectionMutex(l)) {
List out = cloneList(l);
l.clear();
return out;
}
}
static volatile public PersistableThrowable _handleException_lastException;
static public List _handleException_onException = synchroList(ll("printStackTrace2"));
static public void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
static public Map getAndClearMap(Map map) {
if (map == null)
return emptyMap();
synchronized (collectionMutex(map)) {
Map out = cloneMap(map);
map.clear();
return out;
}
}
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 Object pcallFInRealOrMyMC(final Object realm, final Object f, final Object... args) {
try {
return callFInRealOrMyMC(realm, f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
static public A pcallFInRealOrMyMC(Object realm, F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallFInRealOrMyMC(Object realm, F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public void pcallFAll(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) pcallF(f, args);
}
static public void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
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 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 int l(Object[] a) {
return a == null ? 0 : a.length;
}
static public int l(boolean[] a) {
return a == null ? 0 : a.length;
}
static public int l(byte[] a) {
return a == null ? 0 : a.length;
}
static public int l(short[] a) {
return a == null ? 0 : a.length;
}
static public int l(long[] a) {
return a == null ? 0 : a.length;
}
static public int l(int[] a) {
return a == null ? 0 : a.length;
}
static public int l(float[] a) {
return a == null ? 0 : a.length;
}
static public int l(double[] a) {
return a == null ? 0 : a.length;
}
static public int l(char[] a) {
return a == null ? 0 : a.length;
}
static public int l(Collection c) {
return c == null ? 0 : c.size();
}
static public int l(Iterator i) {
return iteratorCount_int_close(i);
}
static public int l(Map m) {
return m == null ? 0 : m.size();
}
static public int l(CharSequence s) {
return s == null ? 0 : s.length();
}
static public long l(File f) {
return f == null ? 0 : f.length();
}
static public int l(Object o) {
return o == null ? 0 : o instanceof String ? l((String) o) : o instanceof Map ? l((Map) o) : o instanceof Collection ? l((Collection) o) : o instanceof Object[] ? l((Object[]) o) : o instanceof boolean[] ? l((boolean[]) o) : o instanceof byte[] ? l((byte[]) o) : o instanceof char[] ? l((char[]) o) : o instanceof short[] ? l((short[]) o) : o instanceof int[] ? l((int[]) o) : o instanceof float[] ? l((float[]) o) : o instanceof double[] ? l((double[]) o) : o instanceof long[] ? l((long[]) o) : (Integer) call(o, "size");
}
static public int l(MultiSet ms) {
return ms == null ? 0 : ms.size();
}
static public int l(IntRange r) {
return r == null ? 0 : r.length();
}
static public long l(LongRange r) {
return r == null ? 0 : r.length();
}
static public Rect dm_getBounds(Object module) {
return shallowCloneToClass(Rect.class, call(dm_getStem(module), "getFrameRect"));
}
static public Rect dm_getBounds() {
return dm_getBounds(dm_current_generic());
}
static public boolean hasMethod_onTypes(Object o, String method, Class... argTypes) {
return findMethod_precise_onTypes(o, method, argTypes) != null;
}
static public void dm_onTopInput_q(final VF1 r) {
final DynModule m = dm_current_mandatory();
dm_onTopInput(new VF1() {
public void get(final String s) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(r, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r, s);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(r, s);";
}
});
}
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 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;
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public AutoCloseable combineAutoCloseables(final AutoCloseable a, final AutoCloseable b) {
return a == null ? b : b == null ? a : new AutoCloseable() {
public String toString() {
return "a.close(); b.close();";
}
public void close() throws Exception {
a.close();
b.close();
}
};
}
static public AutoCloseable combineAutoCloseables(AutoCloseable a, AutoCloseable b, AutoCloseable c, AutoCloseable... more) {
return combineAutoCloseables(concatLists(ll(a, b, c), asList(more)));
}
static public AutoCloseable combineAutoCloseables(Iterable l) {
return foldl(new F2() {
public AutoCloseable get(AutoCloseable a, AutoCloseable b) {
try {
return combineAutoCloseables(a, b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "combineAutoCloseables(a,b)";
}
}, null, l);
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public Class mc() {
return utils.class;
}
static public AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static public ThreadLocal realMC_tl_tl = new ThreadLocal();
static public ThreadLocal realMC_tl() {
return realMC_tl_tl;
}
static public AutoCloseable tempLock(Lock lock) {
return tempLock("", lock);
}
static public AutoCloseable tempLock(String purpose, Lock lock) {
if (lock == null)
return null;
lock(lock);
return new AutoCloseable() {
public String toString() {
return "unlock(lock);";
}
public void close() throws Exception {
unlock(lock);
}
};
}
static public PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static public List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public boolean addIfNotThere(Collection c, A a) {
return setAdd(c, a);
}
static public A onChange(A spinner, Object r) {
{
swing(new Runnable() {
public void run() {
try {
spinner.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "spinner.addChangeListener(changeListener(r));";
}
});
}
return spinner;
}
static public A onChange(A b, Object r) {
{
swing(new Runnable() {
public void run() {
try {
b.addItemListener(itemListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "b.addItemListener(itemListener(r));";
}
});
}
return b;
}
static public void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
static public A onChange(A slider, final Object r) {
{
swing(new Runnable() {
public void run() {
try {
slider.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "slider.addChangeListener(changeListener(r));";
}
});
}
return slider;
}
static public JComboBox onChange(Object r, JComboBox cb) {
return onChange(cb, r);
}
static public JComboBox onChange(JComboBox cb, final Object r) {
if (isEditableComboBox(cb))
onChange(textFieldFromComboBox(cb), r);
else
onSelectedItem(cb, new VF1() {
public void get(String s) {
try {
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r)";
}
});
return cb;
}
static public void onUpdateAndNow(JComponent c, final Object r) {
onUpdate(c, r);
callF(r);
}
static public void onUpdateAndNow(List extends JComponent> l, Object r) {
for (JComponent c : l) onUpdate(c, r);
callF(r);
}
static public void onUpdate(JComponent c, final Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
call(r);
}
public void removeUpdate(DocumentEvent e) {
call(r);
}
public void changedUpdate(DocumentEvent e) {
call(r);
}
});
else if (c instanceof ItemSelectable)
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
call(r);
}
});
else
print("Warning: onUpdate doesn't know " + getClassName(c));
}
static public void onUpdate(List extends JComponent> l, Object r) {
for (JComponent c : l) onUpdate(c, r);
}
static public void zeroAllFieldsOfTypeExcept(Object o, Class type, String... exceptions) {
zeroAllFieldsOfTypeExcept(o, type, asSet(exceptions));
}
static public void zeroAllFieldsOfTypeExcept(Object o, Class type, Collection exceptions) {
Set set = asSet(exceptions);
for (String field : allFields(o)) if (!set.contains(field) && instanceOf(getOpt(o, field), type))
set(o, field, null);
}
static public List paramsToAbstractActions(Object... params) {
List l = new ArrayList();
for (int i = 0; i + 1 < l(params); i += 2) {
String text = (String) (params[i]);
Runnable action = (Runnable) (params[i + 1]);
if (nempty(text))
l.add(abstractAction(text, action));
}
return l;
}
static public void internalFramePopupMenuFromActions_threaded(Container f, List actions) {
if (!(f instanceof JInternalFrame))
return;
for (final AbstractAction a : unnull(actions)) if (a != null)
internalFramePopupMenuItem(((JInternalFrame) f), str(a.getValue(Action.NAME)), runnableThread(new Runnable() {
public void run() {
try {
callAction(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callAction(a)";
}
}));
}
static public LinkedHashSet asLinkedHashSet(A[] array) {
LinkedHashSet set = new LinkedHashSet();
for (A o : array) if (o != null)
set.add(o);
return set;
}
static public LinkedHashSet asLinkedHashSet(Collection l) {
if (l instanceof LinkedHashSet)
return (LinkedHashSet) l;
LinkedHashSet set = new LinkedHashSet();
for (A o : l) if (o != null)
set.add(o);
return set;
}
static public List splitAtSpace(String s) {
return empty(s) ? emptyList() : asList(s.split("\\s+"));
}
static public Set allFields(Object o) {
TreeSet fields = new TreeSet();
Class _c = _getClass(o);
do {
for (Field f : _c.getDeclaredFields()) fields.add(f.getName());
_c = _c.getSuperclass();
} while (_c != null);
return fields;
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
m.m = new String[] { substring(a, strL(b)) };
return true;
}
static public boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static public 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_intFieldMenuItem(Container frame, final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
final String humanized = humanizeFormLabel(field);
internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() {
public void run() {
try {
final JTextField tf = jtextfield(get(m, field));
showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() {
public void run() {
try {
m.setField(field, parseInt(gtt(tf)));
callF(optPar(__, "onSet"));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "m.setField(field, parseInt(gtt(tf)));\r\n callF(optPar(__, \"onSet\"));";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JTextField tf = jtextfield(get(m, field));\r\n showFormTitled(or2(stri...";
}
});
}
static public void dm_doubleFieldMenuItem(Container frame, final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() {
public void run() {
try {
AutoCloseable __1 = m.enter();
try {
dm_doubleFieldSetterDialog(field, __);
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp m.enter();\r\n dm_doubleFieldSetterDialog(field, __);";
}
});
}
static public void dm_stringFieldMenuItem(Container frame, final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() {
public void run() {
try {
AutoCloseable __1 = m.enter();
try {
dm_stringFieldDialog(field, __);
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp m.enter();\r\n dm_stringFieldDialog(field, __);";
}
});
}
static public void dm_fileFieldMenuItem(Container frame, String field, Object... __) {
DynModule m = dm_current_mandatory();
internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() {
public void run() {
try {
AutoCloseable __1 = m.enter();
try {
dm_fileFieldDialog(field, __);
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp m.enter();\r\n dm_fileFieldDialog(field, __);";
}
});
}
static public ReliableSingleThread dm_rst(Runnable r) {
return dm_rst(dm_current_mandatory(), r);
}
static public ReliableSingleThread dm_rst(DynModule mod, Runnable r) {
return dm_rst(mod, new ReliableSingleThread(r));
}
static public ReliableSingleThread dm_rst(DynModule mod, ReliableSingleThread rst) {
rst.enter = dm_rEnter(mod);
return rst;
}
static public Q dm_startQ() {
return dm_ownQ(startQ());
}
static public Q dm_startQ(String name) {
return dm_ownQ(startQ(name));
}
static public JComponent dm_noVisualisation() {
return setToolTip("Module has no visualization", jimage("#1101480"));
}
static public String snippetTitle(String id) {
return getSnippetTitle(id);
}
static public String snippetTitle(long id) {
return getSnippetTitle(id);
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public Class mainClass() {
return getMainClass();
}
static public Class mainClass(Object o) {
return getMainClass(o);
}
static public Map mapMinus(Map map, Object... keys) {
if (empty(keys))
return map;
Map m2 = cloneMap(map);
for (Object key : keys) m2.remove(key);
return m2;
}
static public Map mapPlus(Map m, Object... data) {
m = cloneMap(m);
litmap_impl(m, data);
return m;
}
static public Set _registerTimer_list = newWeakHashSet();
static public void _registerTimer_original(java.util.Timer timer) {
_registerTimer_list.add(timer);
}
static public void cleanMeUp__registerTimer() {
cancelTimers(getAndClearList(_registerTimer_list));
}
static public JPanel jSection(Component c) {
return jSection("", c);
}
static public JPanel jSection(final String title, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
border = BorderFactory.createTitledBorder(border, title);
JSection panel = new JSection(c);
panel.setBorder(border);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n bo...";
}
});
}
static public JPanel jSection(String title) {
return jSection(title, jpanel());
}
static public JScrollPane jscroll_copyBackground(Component c) {
return setScrollPaneBackground(getBackground(c), jscroll(c));
}
static public JFastLogView_noWrap jFastLogView_noWrap() {
return jFastLogView_noWrap("");
}
static public JFastLogView_noWrap jFastLogView_noWrap(String text) {
return withTypeWriterFont(swingNu(JFastLogView_noWrap.class, text));
}
static public String getPrintLog() {
return str(print_log);
}
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 void dm_clearModulePrintLog() {
clearStringBuffer_gen(dm_current_mandatory()._actualPrintLog());
}
static public A awtEvery(A component, long delay, Object r) {
swingEvery(component, delay, r);
return component;
}
static public A awtEvery(A component, long delay, long firstDelay, Object r) {
swingEvery(component, delay, firstDelay, r);
return component;
}
static public void awtEvery(RootPaneContainer frame, long delay, Object r) {
swingEvery(frame, delay, r);
}
static public A awtEvery(A component, double delaySeconds, Object r) {
return awtEvery(component, toMS(delaySeconds), r);
}
static public boolean scrollAllTheWayDown_bruteForce = true;
static public A scrollAllTheWayDown(A c) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
int h = c.getHeight() - 1;
if (scrollAllTheWayDown_bruteForce)
h = max(h, 100000);
c.scrollRectToVisible(new Rectangle(0, h, 1, 1));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "int h = c.getHeight()-1;\r\n if (scrollAllTheWayDown_bruteForce) h = max(h, ...";
}
});
}
return c;
}
static public void awtLater(int delay, final Object r) {
swingLater(delay, r);
}
static public void awtLater(Object r) {
swingLater(r);
}
static public void awtLater(JComponent component, int delay, Object r) {
installTimer(component, r, delay, delay, false);
}
static public void awtLater(JFrame frame, int delay, Object r) {
awtLater(frame.getRootPane(), delay, r);
}
static public StringBuffer liveLocalPrintLog_realMC(Object o) {
Object realMC = getMainClass(o);
if (realMC != mc())
return (StringBuffer) getOpt(realMC, "local_log");
return liveLocalPrintLog();
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static public Map humanizeKeys(Map map) {
return mapKeys(__71 -> humanizeFormLabel(__71), map);
}
static public Map objectToMap_inOrder_withoutFields(Object o, Collection withoutFields) {
if (o == null)
return null;
if (o instanceof Map)
return (Map) o;
LinkedHashMap map = new LinkedHashMap();
for (String field : listWithoutSet(fieldsInOrder(o), withoutFields)) map.put(field, get(o, field));
return map;
}
static public Map objectToMap(Object o) {
try {
if (o instanceof Map)
return (Map) o;
TreeMap map = new TreeMap();
Class c = o.getClass();
while (c != Object.class) {
Field[] fields = c.getDeclaredFields();
for (final Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
field.setAccessible(true);
final Object value = field.get(o);
if (value != null)
map.put(field.getName(), value);
}
c = c.getSuperclass();
}
if (o instanceof DynamicObject)
map.putAll(((DynamicObject) o).fieldValues);
return map;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public List> objectToMap(Iterable l) {
if (l == null)
return null;
List x = new ArrayList();
for (Object o : l) x.add(objectToMap(o));
return x;
}
static public Map mapValues(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map)) m.put(key, callF(func, map.get(key)));
return m;
}
static public Map mapValues(Map map, IF1 f) {
return mapValues(f, map);
}
static public Map mapValues(IF1 f, Map map) {
return mapValues((Object) f, map);
}
static public Map mapValues(Map map, Object func) {
return mapValues(func, map);
}
static public String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static public List addDyn_sync(List l, A a) {
if (l == null)
l = synchroList();
l.add(a);
return l;
}
static public String programTitle() {
return getProgramName();
}
static public int count(Collection l, Object o) {
int count = 0;
for (Object x : l) if (eq(x, o))
++count;
return count;
}
static public List map(Iterable l, Object f) {
return map(f, l);
}
static public List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
static public List map(Iterable l, F1 f) {
return map(f, l);
}
static public List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(callF(f, o));
return x;
}
static public List map(IF1 f, Iterable l) {
return map(l, f);
}
static public List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(IF1 f, A[] l) {
return map(l, f);
}
static public List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static public JTable dataToTable_uneditable(Object data, final JTable table) {
return dataToTable_uneditable(table, data);
}
static public JTable dataToTable_uneditable(final JTable table, final Object data) {
if (table != null) {
swing(new Runnable() {
public void run() {
try {
dataToTable(table, data, true);
makeTableUneditable(table);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dataToTable(table, data, true);\r\n makeTableUneditable(table);";
}
});
}
return table;
}
static public JTable dataToTable_uneditable(final Object data) {
return dataToTable_uneditable(showTable(), data);
}
static public JTable dataToTable_uneditable(Object data, String title) {
return dataToTable_uneditable(showTable(title), data);
}
static public boolean sexyTable_drag = false;
static public JTable sexyTable() {
final JTable table = sexyTableWithoutDrag();
if (sexyTable_drag)
tableEnableTextDrag(table);
return table;
}
static public JTable onDoubleClickOrEnter(final JTable table, final Object runnable) {
onDoubleClick(table, runnable);
onEnter(table, runnable);
return table;
}
static public JList onDoubleClickOrEnter(final JList list, final Object runnable) {
onDoubleClick(list, runnable);
onEnter(list, runnable);
return list;
}
static public JTable onDoubleClickOrEnter(Object runnable, JTable table) {
return onDoubleClickOrEnter(table, runnable);
}
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 JList onDoubleClick(final JList list, final Object runnable) {
{
swing(new Runnable() {
public void run() {
try {
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2) {
int idx = list.locationToIndex(evt.getPoint());
Object item = list.getModel().getElementAt(idx);
list.setSelectedIndex(idx);
callF(runnable, item);
}
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "list.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(Mous...";
}
});
}
return list;
}
static public JTable onDoubleClick(final JTable table, final Object runnable) {
{
swing(new Runnable() {
public void run() {
try {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2) {
int idx = table.rowAtPoint(evt.getPoint());
table.setRowSelectionInterval(idx, idx);
callF(runnable, idx);
}
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "table.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(Mou...";
}
});
}
return table;
}
static public void onDoubleClick(final JComponent c, final Object runnable) {
{
swing(new Runnable() {
public void run() {
try {
c.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getButton() == 1 && evt.getClickCount() == 2)
callF(runnable, evt.getPoint());
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(MouseEv...";
}
});
}
}
static public class TableSearcher {
public JTable table;
public JTextField tfInput;
public JComponent searchPanel, panel;
public F2 rowTester;
public List rowIndices;
public String input() {
return gtt(tfInput);
}
}
static public TableSearcher tableWithSearcher2(final JTable t, Object... __) {
final TableSearcher s = new TableSearcher();
final boolean precise = true;
s.table = t;
s.tfInput = jtextfield();
s.rowTester = new F2() {
public Boolean get(String pat, Map row) {
try {
return anyValueContainsIgnoreCase(row, pat);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "anyValueContainsIgnoreCase(row, pat)";
}
};
onUpdate(s.tfInput, new Runnable() {
public List lastFiltered, lastOriginal;
public void run() {
String pat = s.input();
List> data = rawTableData(t);
if (eq(lastFiltered, data))
data = lastOriginal;
List data2 = new ArrayList();
List rowIndices = new ArrayList();
for (int i = 0; i < l(data); i++) {
Map map = data.get(i);
if (isTrue(callF(s.rowTester, pat, map))) {
data2.add(map);
rowIndices.add(i);
}
}
lastFiltered = data2;
lastOriginal = data;
dataToTable(t, data2);
if (precise)
lastFiltered = rawTableData(t);
s.rowIndices = rowIndices;
}
});
s.searchPanel = withLabel("Search:", s.tfInput);
JComponent top = s.searchPanel;
s.panel = boolOptPar(__, "withMargin") ? northAndCenterWithMargin(top, t) : northAndCenter(top, t);
return s;
}
static public Point enclosingViewPosition(Component c) {
JScrollPane sp = enclosingScrollPane(c);
return sp == null ? null : swing(new F0() {
public Point get() {
try {
return sp.getViewport().getViewPosition();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret sp.getViewport().getViewPosition();";
}
});
}
static public void setEnclosingViewPosition(Component c, Point p) {
if (p == null)
return;
JScrollPane sp = enclosingScrollPane(c);
if (sp != null) {
swing(new Runnable() {
public void run() {
try {
sp.getViewport().setViewPosition(p);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "sp.getViewport().setViewPosition(p);";
}
});
}
}
static public String n2(long l) {
return formatWithThousands(l);
}
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 n2(l, singular, singular + "s");
}
static public String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static public String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
static public String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static public String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static public String n2(Map m, String singular) {
return n2(l(m), singular);
}
static public String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
static public String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static public void syncClear(Collection c) {
if (c != null)
synchronized (collectionMutex(c)) {
c.clear();
}
}
static public void syncClear(Map map) {
if (map != null)
synchronized (collectionMutex(map)) {
map.clear();
}
}
static public boolean syncAdd(Collection c, A b) {
if (c == null)
return false;
synchronized (collectionMutex(c)) {
return c.add(b);
}
}
static public void syncAdd(List l, int idx, A b) {
if (l != null)
synchronized (collectionMutex(l)) {
l.add(idx, b);
}
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean empty(Iterable c) {
return c == null || !c.iterator().hasNext();
}
static public boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean empty(Map map) {
return map == null || map.isEmpty();
}
static public boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static public boolean empty(Object o) {
if (o instanceof Collection)
return empty((Collection) o);
if (o instanceof String)
return empty((String) o);
if (o instanceof Map)
return empty((Map) o);
if (o instanceof Object[])
return empty((Object[]) o);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static public boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
static public boolean empty(double[] a) {
return a == null || a.length == 0;
}
static public boolean empty(float[] a) {
return a == null || a.length == 0;
}
static public boolean empty(int[] a) {
return a == null || a.length == 0;
}
static public boolean empty(long[] a) {
return a == null || a.length == 0;
}
static public boolean empty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean empty(short[] a) {
return a == null || a.length == 0;
}
static public boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public boolean empty(IntRange r) {
return r == null || r.empty();
}
static public boolean syncAddAll(Collection c, Collection b) {
if (c == null || b == null)
return false;
synchronized (c) {
return c.addAll(b);
}
}
static public boolean syncRemove(Collection c, A b) {
if (c == null)
return false;
synchronized (collectionMutex(c)) {
return c.remove(b);
}
}
static public A syncRemove(List l, int idx) {
if (l == null)
return null;
synchronized (collectionMutex(l)) {
return l.remove(idx);
}
}
static public B syncRemove(Map map, A key) {
return map == null ? null : map.remove(key);
}
static public boolean syncRemoveAll(Collection c, Collection b) {
if (c == null || b == null)
return false;
synchronized (collectionMutex(c)) {
return c.removeAll(b);
}
}
static public int[] selectedTableRows_array(final JTable table) {
return table == null ? null : swing(new F0() {
public int[] get() {
try {
return table.getSelectedRows();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret table.getSelectedRows();";
}
});
}
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 void dm_vmBus_send(String msg, Object... args) {
vmBus_send(msg, args);
}
static public void dm_vmBus_send(String msg) {
vmBus_send(msg);
}
static public void change() {
callOpt(getOptMC("mainConcepts"), "allChanged");
}
static public void selectTableRows(final JTable table, int[] rows) {
if (table != null) {
swing(new Runnable() {
public void run() {
try {
ListSelectionModel model = table.getSelectionModel();
int n = tableRows(table);
model.clearSelection();
if (rows != null)
for (int row : rows) if (row < n)
model.addSelectionInterval(row, row);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ListSelectionModel model = table.getSelectionModel();\r\n int n = tableRows(...";
}
});
}
}
static public int syncL(Collection l) {
if (l == null)
return 0;
synchronized (l) {
return l.size();
}
}
static public List syncL() {
return syncList();
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static public A syncGet(List l, int idx) {
if (l == null || idx < 0)
return null;
synchronized (l) {
return idx < l(l) ? l.get(idx) : null;
}
}
static public B syncGet(Map map, A a) {
if (map == null)
return null;
synchronized (map) {
return map.get(a);
}
}
static public int selectedTableRowInModel(final JTable t) {
return t == null ? -1 : swing(new F0() {
public Integer get() {
try {
int i = t.getSelectedRow();
return i < 0 ? i : t.convertRowIndexToModel(i);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "int i = t.getSelectedRow();\r\n ret i < 0 ? i : t.convertRowIndexToModel(i);";
}
});
}
static public List syncListGetMulti(final List l, List indices) {
synchronized (collectionMutex(l)) {
return listGetMulti(l, indices);
}
}
static public int selectedTableRow(final JTable t) {
return t == null ? -1 : swing(new F0() {
public Integer get() {
try {
return t.getSelectedRow();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret t.getSelectedRow();";
}
});
}
static public List selectedTableRowsInModel(final JTable t) {
return t == null ? emptyList() : swing(new F0>() {
public List get() {
try {
return map(selectedTableRows(t), i -> t.convertRowIndexToModel(i));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret map(selectedTableRows(t), i -> t.convertRowIndexToModel(i));";
}
});
}
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 void selectRow(final JTable table, final int i) {
if (table != null) {
swing(new Runnable() {
public void run() {
try {
if (i >= 0 && i < table.getRowCount()) {
table.setRowSelectionInterval(i, i);
scrollRowToVisible(table, i);
} else
table.clearSelection();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (i >= 0 && i < table.getRowCount()) {\r\n table.setRowSelectionInterval...";
}
});
}
}
static public void selectRow(final JList list, final int i) {
if (list != null) {
swing(new Runnable() {
public void run() {
try {
if (i >= 0 && i < listRowCount(list))
list.setSelectedIndex(i);
else
list.clearSelection();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (i >= 0 && i < listRowCount(list))\r\n list.setSelectedIndex(i);\r\n e...";
}
});
}
}
static public JComboBox selectItem(final String item, final JComboBox cb) {
if (cb != null) {
swing(new Runnable() {
public void run() {
try {
cb.setSelectedItem(item);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.setSelectedItem(item);";
}
});
}
return cb;
}
static public JComboBox selectItem(final JComboBox cb, final String item) {
return selectItem(item, cb);
}
static public JList selectItem(JList list, A item) {
{
swing(new Runnable() {
public void run() {
try {
selectRow(list, jlist_indexOf(list, item));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "selectRow(list, jlist_indexOf(list, item));";
}
});
}
return list;
}
static public JTable tablePopupMenuItemsThreaded(final JTable table, Object... params) {
for (int i = 0; i + 1 < l(params); i += 2) {
final Object action = params[i + 1];
final Object threadInfo = _threadInfo();
tablePopupMenuItem(table, str(params[i]), new VF1() {
public void get(final Integer row) {
try {
_threadInheritInfo(threadInfo);
{
startThread(new Runnable() {
public void run() {
try {
try {
callF(action, row);
} catch (Throwable __e) {
messageBox(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "try {\r\n callF(action, row);\r\n } catch (Throwable __e) { messageBo...";
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_threadInheritInfo(threadInfo);\r\n thread-messagebox {\r\n callF(act...";
}
});
}
return table;
}
static public JTable tablePopupMenuItemsThreaded_top(final JTable table, Object... params) {
params = reverseParams(params);
for (int i = 0; i + 1 < l(params); i += 2) {
final Object action = params[i + 1];
final Object threadInfo = _threadInfo();
tablePopupMenuItem_top(table, str(params[i]), new VF1() {
public void get(final Integer row) {
try {
_threadInheritInfo(threadInfo);
{
startThread(new Runnable() {
public void run() {
try {
try {
callF(action, row);
} catch (Throwable __e) {
messageBox(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "try {\r\n callF(action, row);\r\n } catch (Throwable __e) { messageBo...";
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_threadInheritInfo(threadInfo);\r\n thread-messagebox {\r\n callF(act...";
}
});
}
return table;
}
static public void _addAll(Collection c, Iterable b) {
addAll(c, b);
}
static public boolean _addAll(Collection c, Collection b) {
return addAll(c, b);
}
static public boolean _addAll(Collection c, B... b) {
return addAll(c, b);
}
static public void scrollTableDownNow(final JTable table) {
if (table != null) {
swing(new Runnable() {
public void run() {
try {
table.scrollRectToVisible(table.getCellRect(table.getRowCount() - 1, 0, true));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "table.scrollRectToVisible(table.getCellRect(table.getRowCount()-1, 0, true));";
}
});
}
}
static public List list(Class type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static public List list(String type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, String type) {
return concepts.list(type);
}
static public List getList(Map map, Object key) {
return map == null ? null : (List) map.get(key);
}
static public List getList(List l, int idx) {
return (List) get(l, idx);
}
static public List getList(Object o, Object key) {
if (o instanceof Map)
return getList((Map) o, key);
if (key instanceof String)
return (List) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
static public List getList(String name, Object o) {
return getList(o, name);
}
static public ArrayList clonedList(Iterable l) {
return cloneList(l);
}
static public ArrayList clonedList(Collection l) {
return cloneList(l);
}
static public File programFile(String name) {
return prepareProgramFile(name);
}
static public File programFile(String progID, String name) {
return prepareProgramFile(progID, name);
}
static public String ymd_minus_hms_minus_millis() {
return ymd() + "-" + spliceString(replace(hmsWithColonsAndMS(), ":", ""), 6, 6, "-");
}
static public void saveGZStructToFile(String file, Object o) {
saveGZStructureToFile(file, o);
}
static public void saveGZStructToFile(File file, Object o) {
saveGZStructureToFile(file, o);
}
static public File printFileInfo(File f) {
return printFileInfo("", f);
}
static public File printFileInfo(String s, File f) {
print(s, renderFileInfo(f));
return f;
}
static public ImageSurface imageSurface(BufferedImage img) {
return swingNu(ImageSurface.class, img);
}
static public ImageSurface imageSurface(MakesBufferedImage img) {
return swingNu(ImageSurface.class, img);
}
static public ImageSurface imageSurface() {
return swingNu(ImageSurface.class);
}
static public JScrollPane jscroll_center(Component c) {
return jscroll_centered(c);
}
static public boolean fileExists(String path) {
return path != null && new File(path).exists();
}
static public boolean fileExists(File f) {
return f != null && f.exists();
}
static public JLabel setImage(final BufferedImage img, final JLabel lbl) {
if (lbl != null) {
swing(new Runnable() {
public void run() {
try {
lbl.setIcon(imageIcon(img));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "lbl.setIcon(imageIcon(img));";
}
});
}
return lbl;
}
static public JLabel setImage(JLabel lbl, BufferedImage img) {
return setImage(img, lbl);
}
static public JLabel setImage(final String imageID, final JLabel lbl) {
if (lbl != null) {
swing(new Runnable() {
public void run() {
try {
lbl.setIcon(imageIcon(imageID));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "lbl.setIcon(imageIcon(imageID));";
}
});
}
return lbl;
}
static public JLabel setImage(JLabel lbl, String imageID) {
return setImage(imageID, lbl);
}
static public BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static public BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
static public void savePNG(BufferedImage img, File file) {
try {
File tempFile = new File(file.getPath() + "_temp");
CriticalAction ca = beginCriticalAction("Save " + f2s(file));
try {
ImageIO.write(img, "png", mkdirsFor(tempFile));
file.delete();
tempFile.renameTo(file);
} finally {
ca.done();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void savePNG(File file, BufferedImage img) {
savePNG(img, file);
}
static public void savePNG(File file, RGBImage img) {
savePNG(file, img.getBufferedImage());
}
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 String renderFileInfo(File f) {
return f == null ? "-" : f2s(f) + " " + (f.isFile() ? "(file, " + n2(fileSize(f)) + " bytes)" : f.isDirectory() ? "(dir)" : "(not found)");
}
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 AutoCloseable tempSetField(final Object o, final String field, Object value) {
final Object oldValue = get(o, field);
set(o, field, value);
return new AutoCloseable() {
public void close() {
set(o, field, oldValue);
}
};
}
static public Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public void pcallF(VF1 f, A a) {
try {
if (f != null)
f.get(a);
} catch (Throwable __e) {
_handleException(__e);
}
}
static public boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b))
return false;
return parseSnippetID(a) == parseSnippetID(b);
}
static public String dm_moduleID(Object module) {
return strOrNull(getOpt(dm_getStem(module), "id"));
}
static public String dm_moduleID() {
return dm_moduleID(dm_current_mandatory_generic());
}
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 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 Rectangle toRectangle(Rect r) {
return r == null ? null : r.getRectangle();
}
static public JList jlist(final List l) {
return (JList) swing(new F0() {
public Object get() {
try {
JList list = new JList();
final WeakReference ref = weakRef(list);
listPopupMenuItem(list, "Copy text to clipboard", new Runnable() {
public void run() {
try {
copyTextToClipboardIfNotNull(selectedItem(ref.get()));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyTextToClipboardIfNotNull(selectedItem(ref.get()))";
}
});
fillListWithStrings(list, l);
return list;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new JList list;\r\n final WeakReference ref = weakRef(list);\r\n lis...";
}
});
}
static public JList jlist(String... l) {
return jlist(asList(l));
}
static public void fillListWithStrings(JList list, Collection contents) {
if (list == null)
return;
final DefaultListModel model = new DefaultListModel();
if (contents != null)
for (String s : contents) model.addElement(empty(s) ? " " : s);
{
swing(new Runnable() {
public void run() {
try {
list.setModel(model);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "list.setModel(model);";
}
});
}
}
static public void fillListWithStrings(final JList list, String[] contents) {
fillListWithStrings(list, asList(contents));
}
static public String selectedItem(JList l) {
return getSelectedItem(l);
}
static public String selectedItem(JComboBox cb) {
return getSelectedItem(cb);
}
static public A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static public A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(Object o) {
return !empty(o);
}
static public boolean nempty(IntRange r) {
return !empty(r);
}
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 Object realMC() {
return getThreadLocal(realMC_tl());
}
static public ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
static public class getOpt_Map extends WeakHashMap {
public getOpt_Map() {
if (getOpt_special == null)
getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final public Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
static public HashMap getOpt_special;
static public Object getOpt_cached(Object o, String field) {
try {
if (o == null)
return null;
Class c = o.getClass();
HashMap map;
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null)
return f.get(o);
if (o instanceof DynamicObject)
return mapGet2(((DynamicObject) o).fieldValues, field);
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
if (!reflection_classesNotToScan().contains(c.getName())) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
makeAccessible(f);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
}
if (getOpt_cache != null)
getOpt_cache.put(c, map);
return map;
}
static public Map> setTableModel_after = weakHashMap();
static public Map> setTableModel_fixSorter = weakHashMap();
static public void setTableModel(final JTable table, final TableModel model) {
{
swing(new Runnable() {
public void run() {
try {
Map widths = tableColumnWidthsByName(table);
int[] i = table.getSelectedRows();
TableRowSorter sorter = model.getColumnCount() == tableColumnCount(table) ? (TableRowSorter) table.getRowSorter() : null;
List extends RowSorter.SortKey> sortKeys = sorter == null ? null : sorter.getSortKeys();
table.setModel(model);
int n = model.getRowCount();
ListSelectionModel sel = table.getSelectionModel();
for (int j = 0; j < i.length; j++) if (i[j] < n)
sel.addSelectionInterval(i[j], i[j]);
tableSetColumnPreferredWidths(table, widths);
if (sorter != null) {
sorter.setModel(model);
callF(setTableModel_fixSorter.get(table), table, sorter);
if (sortKeys != null)
sorter.setSortKeys(sortKeys);
}
table.setRowSorter(sorter);
callF(setTableModel_after.get(table), table);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Map widths = tableColumnWidthsByName(table);\r\n int[] i = ...";
}
});
}
}
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 Object _onAWTEnter_f;
static public AutoCloseable _onAWTEnter() {
return (AutoCloseable) callF(_onAWTEnter_f);
}
static public JDesktopPane mainDesktopPane_value;
static public JDesktopPane mainDesktopPane() {
return mainDesktopPane_value;
}
static public Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
static public void printStackTrace2() {
printStackTrace2(new Throwable());
}
static public void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static public boolean interruptThread_verbose = false;
static public void interruptThread(Thread t) {
if (t == null)
return;
if (interruptThread_verbose)
print("Interrupting thread " + t);
vm_threadInterruptionReasonsMap().put(t, getStackTrace());
t.interrupt();
URLConnection c = (URLConnection) (vm_generalSubMap("URLConnection per thread").get(t));
if (c != null) {
try {
print("Closing URLConnection of interrupted thread.");
call(c, "disconnect");
} catch (Throwable __e) {
_handleException(__e);
}
}
}
static public void cancelTimer(javax.swing.Timer timer) {
if (timer != null)
timer.stop();
}
static public void cancelTimer(java.util.Timer timer) {
if (timer != null)
timer.cancel();
}
static public void cancelTimer(Object o) {
if (o instanceof java.util.Timer)
cancelTimer((java.util.Timer) o);
else if (o instanceof javax.swing.Timer)
cancelTimer((javax.swing.Timer) o);
else if (o instanceof AutoCloseable) {
try {
((AutoCloseable) o).close();
} catch (Throwable __e) {
_handleException(__e);
}
}
}
static public Class javax() {
return getJavaX();
}
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 RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public A first(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 List _registerWeakMap_preList;
static public A _registerWeakMap(A map) {
if (javax() == null) {
if (_registerWeakMap_preList == null)
_registerWeakMap_preList = synchroList();
_registerWeakMap_preList.add(map);
return map;
}
try {
call(javax(), "_registerWeakMap", map);
} catch (Throwable e) {
printException(e);
print("Upgrade JavaX!!");
}
return map;
}
static public void _onLoad_registerWeakMap() {
assertNotNull(javax());
if (_registerWeakMap_preList == null)
return;
for (Object o : _registerWeakMap_preList) _registerWeakMap(o);
_registerWeakMap_preList = null;
}
static public Map synchroMap() {
return synchroHashMap();
}
static public Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static public String javaTok_substringN(String s, int i, int j) {
if (i == j)
return "";
if (j == i + 1 && s.charAt(i) == ' ')
return " ";
return s.substring(i, j);
}
static public String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
static public List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
}
static public 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 Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static public Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static public Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static public void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
if (type == int.class && value instanceof Long)
value = ((Long) value).intValue();
if (type == LinkedHashMap.class && value instanceof Map) {
f.set(o, asLinkedHashMap((Map) value));
return;
}
try {
if (f.getType() == Concept.Ref.class) {
f.set(o, ((Concept) o).new Ref((Concept) value));
return;
}
if (o instanceof Concept.Ref) {
f.set(o, ((Concept.Ref) o).get());
return;
}
} catch (Throwable _e) {
}
throw e;
}
}
static public A setDyn(A o, String key, Object value) {
if (o == null)
return o;
setDynObjectValue(o, key, value);
return o;
}
static public Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
static public Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
static public Object callMCWithVarArgs(String method, Object... args) {
return call_withVarargs(mc(), method, args);
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
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 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 Object callOpt_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.findMethod(method, args);
if (me == null) {
return null;
}
if ((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(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);
}
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map weakHashMap() {
return newWeakHashMap();
}
static public int shorten_default = 100;
static public String shorten(CharSequence s) {
return shorten(s, shorten_default);
}
static public String shorten(CharSequence s, int max) {
return shorten(s, max, "...");
}
static public String shorten(CharSequence s, int max, String shortener) {
if (s == null)
return "";
if (max < 0)
return str(s);
return s.length() <= max ? str(s) : subCharSequence(s, 0, min(s.length(), max - l(shortener))) + shortener;
}
static public String shorten(int max, CharSequence s) {
return shorten(s, max);
}
static public TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) {
return new SmartTimerTask(r, timer, delay, _threadInfo());
}
static public class SmartTimerTask extends TimerTask implements IFieldsToList {
public Object r;
public java.util.Timer timer;
public long delay;
public Object threadInfo;
public SmartTimerTask() {
}
public SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) {
this.threadInfo = threadInfo;
this.delay = delay;
this.timer = timer;
this.r = r;
}
public String toString() {
return shortClassName(this) + "(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")";
}
public Object[] _fieldsToList() {
return new Object[] { r, timer, delay, threadInfo };
}
public long lastRun;
public void run() {
if (!licensed())
timer.cancel();
else {
_threadInheritInfo(threadInfo);
AutoCloseable __1 = tempActivity(r);
try {
lastRun = fixTimestamp(lastRun);
long now = now();
if (now >= lastRun + delay * 0.9) {
lastRun = now;
if (eq(false, pcallF(r)))
timer.cancel();
}
} finally {
_close(__1);
}
}
}
}
static public int toInt(Object o) {
if (o == null)
return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt(((String) o));
if (o instanceof Boolean)
return boolToInt(((Boolean) o));
throw fail("woot not int: " + getClassName(o));
}
static public int toInt(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
static public A vmBus_timerStarted(A timer) {
vmBus_send("timerStarted", timer, costCenter());
return timer;
}
static public long toMS(double seconds) {
return (long) (seconds * 1000);
}
static volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal ping_isCleanUpThread = new ThreadLocal();
static public boolean ping() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public TimerTask timerTask(final Object r, final java.util.Timer timer) {
return new TimerTask() {
public void run() {
if (!licensed())
timer.cancel();
else
pcallF(r);
}
};
}
static public Map findBot_cache = synchroHashMap();
static public int findBot_timeout = 5000;
static public DialogIO findBot(String searchPattern) {
String subBot = null;
int i = searchPattern.indexOf('/');
if (i >= 0 && (isJavaIdentifier(searchPattern.substring(0, i)) || isInteger(searchPattern.substring(0, i)))) {
subBot = searchPattern.substring(i + 1);
searchPattern = searchPattern.substring(0, i);
if (!isInteger(searchPattern))
searchPattern = "Multi-Port at " + searchPattern + ".";
}
if (isInteger(searchPattern))
return talkToSubBot(subBot, talkTo(parseInt(searchPattern)));
if (eq(searchPattern, "remote"))
return talkToSubBot(subBot, talkTo("second.tinybrain.de", 4999));
Integer port = findBot_cache.get(searchPattern);
if (port != null)
try {
DialogIO io = talkTo("localhost", port);
io.waitForLine();
String line = io.readLineNoBlock();
if (indexOfIgnoreCase(line, searchPattern) == 0) {
call(io, "pushback", line);
return talkToSubBot(subBot, io);
}
} catch (Exception e) {
e.printStackTrace();
}
List bots = quickBotScan();
for (ProgramScan.Program p : bots) {
if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) {
findBot_cache.put(searchPattern, p.port);
return talkToSubBot(subBot, talkTo("localhost", p.port));
}
}
for (ProgramScan.Program p : bots) {
String botName = firstPartOfHelloString(p.helloString);
boolean isVM = startsWithIgnoreCase(p.helloString, "This is a JavaX VM.");
boolean shouldRecurse = startsWithIgnoreCase(botName, "Multi-Port") || isVM;
if (shouldRecurse)
try {
Map subBots = (Map) unstructure(sendToLocalBotQuietly(p.port, "list bots"));
for (Number vport : subBots.keySet()) {
String name = subBots.get(vport);
if (startsWithIgnoreCase(name, searchPattern))
return talkToSubBot(vport.longValue(), talkTo("localhost", p.port));
}
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
return null;
}
static public A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () {
public A get() {
try {
return nuObject(c, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret nuObject(c, args);";
}
});
}
static public A setFont(final Font font, final A a) {
if (a != null) {
swing(new Runnable() {
public void run() {
try {
a.setFont(font);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.setFont(font);";
}
});
}
return a;
}
static public A setFont(A a, Font font) {
return setFont(font, a);
}
static public A setFont(final String fontID, float fontSize, final A a) {
return setFont(loadFont_cached(fontID, fontSize), a);
}
static public JTextArea jTextArea() {
return jTextArea("");
}
static public JTextArea jTextArea(final String text) {
return jTextAreaWithUndo(text);
}
static public Font typeWriterFont() {
return typeWriterFont(iround(14 * getSwingFontScale()));
}
static public Font typeWriterFont(int size) {
return new Font("Courier", Font.PLAIN, size);
}
static public boolean structure_showTiming, structure_checkTokenCount;
static public String structure(Object o) {
return structure(o, new structure_Data());
}
static public String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static public void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack)) popLast(d.stack).run();
}
static public void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
static public boolean structure_allowShortening = false;
static public class structure_ClassInfo {
public List fields;
public Method customSerializer;
public boolean special, nullInstances;
}
static public class structure_Data {
public PrintWriter out;
public int stringSizeLimit;
public int shareStringsLongerThan = 20;
public boolean noStringSharing = false;
public IdentityHashMap seen = new IdentityHashMap();
public HashMap strings = new HashMap();
public HashSet concepts = new HashSet();
public HashMap infoByClass = new HashMap();
public HashMap persistenceInfo = new HashMap();
public int n;
public List stack = new ArrayList();
public structure_Data append(String token) {
out.print(token);
++n;
return this;
}
public structure_Data append(int i) {
out.print(i);
++n;
return this;
}
public structure_Data append(String token, int tokCount) {
out.print(token);
n += tokCount;
return this;
}
public structure_Data app(String token) {
out.print(token);
return this;
}
public structure_Data app(int i) {
out.print(i);
return this;
}
}
static public void structure_1(final Object o, final structure_Data d) {
try {
if (o == null) {
d.append("null");
return;
}
Class c = o.getClass();
boolean concept = false;
concept = o instanceof Concept;
structure_ClassInfo info = d.infoByClass.get(c);
if (info == null) {
d.infoByClass.put(c, info = new structure_ClassInfo());
if ((info.customSerializer = findMethodNamed(c, "_serialize")) != null)
info.special = true;
}
List lFields = info.fields;
if (lFields == null) {
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) {
int i = ((Integer) o).intValue();
out.print(i);
d.n += i < 0 ? 2 : 1;
return;
}
if (o instanceof Long) {
long l = ((Long) o).longValue();
out.print(l);
out.print("L");
d.n += l < 0 ? 2 : 1;
return;
}
if (o instanceof Short) {
short s = ((Short) o).shortValue();
d.append("sh ");
out.print(s);
d.n += s < 0 ? 2 : 1;
return;
}
if (o instanceof Float) {
d.append("fl ", 2);
quoteToPrintWriter(str(o), out);
return;
}
if (o instanceof Double) {
d.append("d(", 3);
quoteToPrintWriter(str(o), out);
d.append(")");
return;
}
if (o instanceof BigInteger) {
out.print("bigint(");
out.print(o);
out.print(")");
d.n += ((BigInteger) o).signum() < 0 ? 5 : 4;
return;
}
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f");
return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o));
return;
}
if (o instanceof File) {
d.append("File ").append(quote(((File) o).getPath()));
return;
}
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null)
ref = d.strings.get((String) o);
if (ref != null) {
d.append("t").app(ref);
return;
}
if (!(o instanceof String))
d.seen.put(o, d.n);
else {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out);
d.n++;
return;
}
if (o instanceof Set) {
if (((Set) o) instanceof TreeSet) {
d.append(isCISet_gen(((Set) o)) ? "ciset" : "treeset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
d.append(((Set) o) instanceof LinkedHashSet ? "lhs" : "hashset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
String name = c.getName();
if (o instanceof Collection && !isJavaXClassName(name)) {
if (name.equals("java.util.Collections$SynchronizedList") || name.equals("java.util.Collections$SynchronizedRandomAccessList")) {
d.append("sync ");
{
structure_1(unwrapSynchronizedList(((List) o)), d);
return;
}
} else if (name.equals("java.util.LinkedList"))
d.append("ll");
d.append("[");
final int l = d.n;
final Iterator it = ((Collection) o).iterator();
d.stack.add(new Runnable() {
public void run() {
try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l)
d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.sta...";
}
});
return;
}
if (o instanceof Map && !startsWith(name, "main$")) {
if (o instanceof LinkedHashMap)
d.append("lhm");
else if (o instanceof HashMap)
d.append("hm");
else if (o instanceof TreeMap)
d.append(isCIMap_gen(((TreeMap) o)) ? "cimap" : "tm");
else if (name.equals("java.util.Collections$SynchronizedMap") || name.equals("java.util.Collections$SynchronizedSortedMap") || name.equals("java.util.Collections$SynchronizedNavigableMap")) {
d.append("sync ");
{
structure_1(unwrapSynchronizedMap(((Map) o)), d);
return;
}
}
d.append("{");
final int l = d.n;
final Iterator it = ((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
public boolean v = false;
public Map.Entry e;
public void run() {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l)
d.append(", ");
structure_1(e.getKey(), d);
}
}
}
});
return;
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o)));
return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i - 1) == '0' && hex.charAt(i - 2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i)));
return;
}
String atype = "array";
if (o instanceof int[]) {
atype = "intarray";
} else if (o instanceof double[]) {
atype = "dblarray";
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
public int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0)
d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")");
return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")");
return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
if (d.n != l)
d.append(", ");
d.append(i);
}
d.append("}");
return;
}
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o)));
return;
}
if (info.special) {
if (info.customSerializer != null) {
Object o2 = invokeMethod(info.customSerializer, o);
d.append("cu ");
String shortName = dropPrefix("main$", name);
d.append(shortName);
d.out.append(' ');
structure_1(o2, d);
return;
} else if (info.nullInstances) {
d.append("null");
return;
} else
throw fail("unknown special type");
}
String dynName = shortDynamicClassName(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
String fieldName = field.getName();
if (fieldName.equals("_persistenceInfo"))
d.persistenceInfo.put(c, field);
if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
continue;
fields.add(field);
}
cc = cc.getSuperclass();
}
lFields = asList(fields);
int n = l(lFields);
for (int i = 0; i < n; i++) {
Field f = lFields.get(i);
if (f.getName().equals("this$1")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
info.fields = lFields;
} else {
Integer ref = d.seen.get(o);
if (ref != null) {
d.append("t").app(ref);
return;
}
d.seen.put(o, d.n);
}
Field persistenceInfoField = (Field) (d.persistenceInfo.get(c));
Map persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o);
LinkedHashMap fv = new LinkedHashMap();
for (Field f : lFields) {
Object value;
try {
value = f.get(o);
} catch (Exception e) {
value = "?";
}
if (value != null && (persistenceInfo == null || !Boolean.FALSE.equals(persistenceInfo.get(f.getName()))))
fv.put(f.getName(), value);
}
String name = c.getName();
String shortName = dropPrefix("main$", name);
if (startsWithDigit(shortName))
shortName = name;
if (concept && eq(fv.get("className"), shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
putAll(fv, (Map) fv.get("fieldValues"));
fv.remove("fieldValues");
shortName = shortDynamicClassName(o);
fv.remove("className");
}
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
d.append(shortName);
d.n += countDots(shortName) * 2;
final int l = d.n;
final Iterator it = fv.entrySet().iterator();
d.stack.add(new Runnable() {
public void run() {
try {
if (!it.hasNext()) {
if (d.n != l)
d.append(")");
} else {
Map.Entry e = (Map.Entry) it.next();
d.append(d.n == l ? "(" : ", ");
d.append((String) e.getKey()).append("=");
d.stack.add(this);
structure_1(e.getValue(), d);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
static public int toMS_int(double seconds) {
return toInt_checked((long) (seconds * 1000));
}
static public URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) {
con.setConnectTimeout(toInt(timeout));
con.setReadTimeout(toInt(timeout));
if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
print("Warning: Timeouts not set by JDK.");
return con;
}
static public 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));
}
volatile static public boolean conceptsAndBot_running = false;
static public boolean conceptsAndBot_thinOnStart = true;
static public void conceptsAndBot() {
conceptsAndBot(null);
}
static public void conceptsAndBot(Integer autoSaveInterval) {
if (conceptsAndBot_running)
return;
conceptsAndBot_running = true;
try {
ensureDBNotRunning(dbBotStandardName());
} catch (Throwable _e) {
db_mainConcepts().dontSave = true;
throw rethrow(_e);
}
db_mainConcepts().persist(autoSaveInterval);
dbBot();
if (conceptsAndBot_thinOnStart) {
try {
thinAProgramsBackups(getDBProgramID(), true);
} catch (Throwable __e) {
_handleException(__e);
}
}
}
static public void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
static public Object[] expandParams(Class c, Object[] params) {
if (l(params) == 1)
params = new Object[] { singleFieldName(c), params[0] };
else
warnIfOddCount(params);
return params;
}
static public boolean _csetField(Concept c, String field, Object value) {
try {
Field f = setOpt_findField(c.getClass(), field);
if (value instanceof RC)
value = c._concepts.getConcept((RC) value);
value = deref(value);
if (value instanceof String && l((String) value) >= concepts_internStringsLongerThan)
value = intern((String) value);
if (f == null) {
c.fieldValues = syncMapPut2_createLinkedHashMap(c.fieldValues, assertIdentifier(field), value instanceof Concept ? c.new Ref((Concept) value) : value);
c.change();
} else if (isSubtypeOf(f.getType(), Concept.Ref.class)) {
((Concept.Ref) f.get(c)).set((Concept) derefRef(value));
c.change();
return true;
} else if (isSubtypeOf(f.getType(), Concept.RefL.class)) {
((Concept.RefL) f.get(c)).replaceWithList(lmap(__72 -> derefRef(__72), (List) value));
c.change();
return true;
} else {
Object old = f.get(c);
if (neq(value, old)) {
f.set(c, value);
if (!isTransient(f))
c.change();
return true;
}
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
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 boolean match3(String pat, String s) {
return match3(pat, s, null);
}
static public boolean match3(String pat, String s, Matches matches) {
if (pat == null || s == null)
return false;
return match3(pat, parse3_cachedInput(s), matches);
}
static public boolean match3(String pat, List toks, Matches matches) {
List tokpat = parse3_cachedPattern(pat);
return match3(tokpat, toks, matches);
}
static public boolean match3(List tokpat, List toks, Matches matches) {
String[] m = match2(tokpat, toks);
if (m == null)
return false;
if (matches != null)
matches.m = m;
return true;
}
static public Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
static public Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
static public List javaTokPlusPeriod(String s) {
List tok = new ArrayList();
if (s == null)
return tok;
int l = s.length();
int i = 0;
while (i < l) {
int j = i;
char c;
String cc;
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j + 2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
cc = s.substring(i, Math.min(i + 2, l));
if (c == (char) 0x201C || c == (char) 0x201D)
c = '"';
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
char _c = s.charAt(j);
if (_c == (char) 0x201C || _c == (char) 0x201D)
_c = '"';
if (_c == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
if (j - 1 >= i + 1) {
tok.add(opener + s.substring(i + 1, j - 1) + opener);
i = j;
continue;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
else if (Character.isDigit(c))
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else if (cc.equals("[[")) {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (cc.equals("[=") && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else if (s.substring(j, Math.min(j + 3, l)).equals("..."))
j += 3;
else if (c == '$' || c == '#')
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
return tok;
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public boolean isNonNegativeInteger(String s) {
int n = l(s);
if (n == 0)
return false;
int i = 0;
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 Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static public Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static public Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static public Map syncHashMap() {
return synchroHashMap();
}
static public Map newWeakMap() {
return newWeakHashMap();
}
static public boolean networkAllowanceTest(String url) {
return isAllowed("networkAllowanceTest", url);
}
static final public boolean loadPageThroughProxy_enabled = false;
static public String loadPageThroughProxy(String url) {
return null;
}
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 void sleepSeconds(double s) {
if (s > 0)
sleep(round(s * 1000));
}
static public String tb_mainServer_default = "http://code.botcompany.de:8081";
static public Object tb_mainServer_override;
static public String tb_mainServer() {
if (tb_mainServer_override != null)
return (String) callF(tb_mainServer_override);
return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default));
}
static public File tb_mainServer_file() {
return getProgramFile("#1001638", "mainserver.txt");
}
static public boolean tb_mainServer_isDefault() {
return eq(tb_mainServer(), tb_mainServer_default);
}
static public A printWithTime(A a) {
return printWithTime("", a);
}
static public A printWithTime(String s, A a) {
print(hmsWithColons() + ": " + s, a);
return a;
}
static public A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
static public A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
static public A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
static public Object optPar(Object[] params, String name) {
return optParam(params, name);
}
static public Object optPar(String name, Object[] params) {
return optParam(params, name);
}
static public Object optPar(String name, Map params) {
return optParam(name, params);
}
static public A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public void setHeaders(URLConnection con) throws IOException {
String computerID = getComputerID_quick();
if (computerID != null)
try {
con.setRequestProperty("X-ComputerID", computerID);
con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
} catch (Throwable e) {
}
}
static public Map vm_generalSubMap(Object name) {
synchronized (get(javax(), "generalMap")) {
Map map = (Map) (vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = synchroMap());
return map;
}
}
static public Thread currentThread() {
return Thread.currentThread();
}
static public InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
UnknownHostException lastException = null;
for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) {
try {
if (con instanceof HttpURLConnection)
if (((HttpURLConnection) con).getResponseCode() == 500)
throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con))));
return con.getInputStream();
} catch (UnknownHostException e) {
lastException = e;
print("Retrying because of: " + e);
continue;
}
}
throw lastException;
}
static public GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
static public GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
static public String unquote(String s) {
if (s == null)
return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i + 1, s.length() - i - 1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
StringBuilder sb = new StringBuilder(l - 1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\'':
ch = '\'';
break;
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s;
}
static public String toHex(byte[] bytes) {
return bytesToHex(bytes);
}
static public String toHex(byte[] bytes, int ofs, int len) {
return bytesToHex(bytes, ofs, len);
}
static public byte[] utf8(String s) {
return toUtf8(s);
}
static public Matcher regexpMatcher(String pat, String s) {
return compileRegexp(pat).matcher(unnull(s));
}
static public URLConnection openConnection(String url) {
try {
return openConnection(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public URLConnection openConnection(URL url) {
try {
ping();
callOpt(javax(), "recordOpenURLConnection", str(url));
return url.openConnection();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
if (con.getConnectTimeout() == 0) {
con.setConnectTimeout(toInt(timeout));
if (con.getConnectTimeout() != timeout)
print("Warning: URL connect timeout not set by JDK.");
}
if (con.getReadTimeout() == 0) {
con.setReadTimeout(toInt(timeout));
if (con.getReadTimeout() != timeout)
print("Warning: URL read timeout not set by JDK.");
}
return con;
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
static public boolean isLocalSnippetID(String snippetID) {
return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID));
}
static public boolean isLocalSnippetID(long snippetID) {
return snippetID >= 1000 && snippetID <= 9999;
}
static public String loadLocalSnippet(String snippetID) {
return loadLocalSnippet(psI(snippetID));
}
static public String loadLocalSnippet(long snippetID) {
return loadTextFile(localSnippetFile(snippetID));
}
static public IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
static public String fsI(String id) {
return formatSnippetID(id);
}
static public String fsI(long id) {
return formatSnippetID(id);
}
static public String md5(String text) {
try {
if (text == null)
return "-";
return bytesToHex(md5_impl(toUtf8(text)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String md5(byte[] data) {
if (data == null)
return "-";
return bytesToHex(md5_impl(data));
}
static public byte[] md5_impl(byte[] data) {
try {
return MessageDigest.getInstance("MD5").digest(data);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String md5(File file) {
return md5OfFile(file);
}
static public String standardCredentials() {
String user = standardCredentialsUser();
String pass = standardCredentialsPass();
if (nempty(user) && nempty(pass))
return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
return "";
}
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 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 File getGlobalCache() {
File file = new File(javaxCachesDir(), "Binary Snippets");
file.mkdirs();
return file;
}
static public A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
static public DialogIO talkTo(int port) {
return talkTo("localhost", port);
}
static public int talkTo_defaultTimeout = 10000;
static public int talkTo_timeoutForReads = 0;
static public ThreadLocal> talkTo_byThread = new ThreadLocal();
static public DialogIO talkTo(String ip, int port) {
try {
String full = ip + ":" + port;
Map map = talkTo_byThread.get();
if (map != null && map.containsKey(full))
return map.get(full);
if (isLocalhost(ip) && port == vmPort())
return talkToThisVM();
return new talkTo_IO(ip, port);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public class talkTo_IO extends DialogIO {
public String ip;
public int port;
public Socket s;
public Writer w;
public BufferedReader in;
public talkTo_IO(String ip, int port) {
this.port = port;
this.ip = ip;
try {
s = new Socket();
try {
if (talkTo_timeoutForReads != 0)
s.setSoTimeout(talkTo_timeoutForReads);
s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout);
} catch (Throwable e) {
throw fail("Tried talking to " + ip + ":" + port, e);
}
w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public boolean isLocalConnection() {
return s.getInetAddress().isLoopbackAddress();
}
public boolean isStillConnected() {
return !(eos || s.isClosed());
}
public void sendLine(String line) {
try {
Lock __0 = lock;
lock(__0);
try {
w.write(line + "\n");
w.flush();
} finally {
unlock(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String readLineImpl() {
try {
return in.readLine();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void close() {
try {
if (!noClose)
s.close();
} catch (IOException e) {
}
}
public Socket getSocket() {
return s;
}
}
static public String format(String pat, Object... args) {
return format3(pat, args);
}
static public Map newFindBot2_cache = synchroHashMap();
static public boolean newFindBot2_verbose = false;
static public DialogIO newFindBot2(String name) {
Integer port = newFindBot2_cache.get(name);
if (port != null) {
if (newFindBot2_verbose)
print("newFindBot2: testing " + name + " => " + port);
DialogIO io = talkTo(port);
String q = format("has bot *", name);
String s = io.ask(q);
if (match("yes", s)) {
io = talkToSubBot(name, io);
call(io, "pushback", "?");
return io;
}
newFindBot2_cache.remove(name);
if (newFindBot2_verbose)
print("newFindBot2: dropping " + name + " => " + port);
}
DialogIO io = findBot(name);
if (io != null) {
newFindBot2_cache.put(name, io.getPort());
if (newFindBot2_verbose)
print("newFindBot2: remembering " + name + " => " + port);
}
return io;
}
static public TableWithTooltips tableWithToolTips() {
return tableWithTooltips();
}
static public WeakReference weakRef(A a) {
return newWeakReference(a);
}
static public List getTableLine(JTable tbl, int row) {
if (row >= 0 && row < tbl.getModel().getRowCount()) {
List l = new ArrayList();
for (int i = 0; i < tbl.getModel().getColumnCount(); i++) l.add(String.valueOf(tbl.getModel().getValueAt(row, i)));
return l;
}
return null;
}
static public void copyImageToClipboard(Image img) {
TransferableImage trans = new TransferableImage(img);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
vmBus_send("newClipboardContents", img);
print("Copied image to clipboard (" + img.getWidth(null) + "*" + img.getHeight(null) + " px)");
}
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 JComponent showTitledForm(String title, Object... _parts) {
return showFormTitled(title, _parts);
}
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 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 int convertTableRowToModel(final JTable t, final int viewRow) {
return t == null || viewRow < 0 ? -1 : swing(new F0() {
public Integer get() {
try {
return t.convertRowIndexToModel(viewRow);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret t.convertRowIndexToModel(viewRow);";
}
});
}
static public Object findComponentPopupMenuListener_gen(final JComponent c) {
return c == null ? null : swing(new F0() {
public Object get() {
try {
return firstWithClassShortNamed("componentPopupMenu_Adapter", c.getMouseListeners());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret firstWithClassShortNamed('componentPopupMenu_Adapter, c.getMouseListeners...";
}
});
}
static public boolean internalFrameActive(Component c) {
final JInternalFrame f = getInternalFrame(c);
return f != null && swing(new F0() {
public Boolean get() {
try {
return f.isSelected();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret f.isSelected();";
}
});
}
static public A getWeakRef(Reference ref) {
return ref == null ? null : ref.get();
}
static public A firstInstanceOf(Iterable i, Class c) {
if (i == null)
return null;
c = primitiveToBoxedTypeOpt(c);
for (Object o : i) if (isInstance(c, o))
return (A) o;
return null;
}
static public A firstInstanceOf(Class c, Iterable i) {
return firstInstanceOf(i, c);
}
static public A firstInstanceOf(Object[] a, Class c) {
if (a == null)
return null;
c = primitiveToBoxedTypeOpt(c);
for (Object o : a) if (isInstance(c, o))
return (A) o;
return null;
}
static public List> paramsToPairs(A... params) {
List> l = emptyList(l(params) / 2);
for (int i = 0; i + 1 < l(params); i += 2) l.add(pair(params[i], params[i + 1]));
return l;
}
static public String javaxDefaultVMArgs() {
File fileNew, fileOld;
String text = loadTextFile(fileNew = javaxDataDir("default-vm-args"));
if (text == null) {
text = loadTextFile(fileOld = programFile("#1005850", "default-vm-args"));
if (text != null)
moveFile(fileOld, fileNew);
}
return trim(unnull(text));
}
static public void appendToLocalMechLog(String listName, String text) {
logMechListAppendLocally(listName, text);
}
static public List dropSecondIfEmpty(String a, String b) {
return empty(b) ? ll(a) : ll(a, b);
}
static public int parseFirstInt(String s) {
return parseInt(jextract("", s));
}
static public int parseFirstInt(Iterable l) {
return parseInt(firstIntegerString(l));
}
static public boolean usePreSpunVMs() {
return eq("1", trim(loadProgramTextFile("#1005457", "enable-prespun-vms")));
}
static public void usePreSpunVMs(boolean flag) {
saveProgramTextFile("#1005457", "enable-prespun-vms", flag ? "1" : null);
}
static public File classicNohupJavax(String javaxargs) {
return classicNohupJavax(javaxargs, "");
}
static public File classicNohupJavax(String javaxargs, String vmArgs) {
try {
File jar = pathToJavaxJar();
if (javaxargs.startsWith("#"))
javaxargs = javaxargs.substring(1);
String tempPrefix = takeFirst(30, nohup_sanitize(ymd_minus_hms() + "_" + javaxargs + "_"));
File outFile;
try {
outFile = File.createTempFile(tempPrefix, "");
} catch (Throwable e) {
_handleException(e);
print("Temp file creation failed for " + tempPrefix + ", trying again.");
outFile = File.createTempFile("", "");
}
String cmd = joinWithSpace((platformParseArgs(_javaCommand() + " " + vmArgs))) + " -jar " + (isWindows() ? winQuote(jar) : bashQuote(jar)) + " " + javaxargs;
nohup(cmd, outFile, false);
return outFile;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
int n = s.length();
if (y < x)
y = x;
if (y > n)
y = n;
if (x >= y)
return "";
return s.substring(x, y);
}
static public String substring(String s, IntRange r) {
return r == null ? null : substring(s, r.start, r.end);
}
static public String substring(String s, CharSequence l) {
return substring(s, l(l));
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean isEmpty(Object[] a) {
return a == null || a.length == 0;
}
static public boolean isEmpty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static public boolean 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 setSCPComponent(SingleComponentPanel scp, Component c) {
if (scp != null)
scp.setComponent(c);
}
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 void addToContainer(Container a, Component... b) {
if (a == null)
return;
{
swing(new Runnable() {
public void run() {
try {
for (Component c : unnull(b)) if (c != null)
a.add(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "for (Component c : unnull(b))\r\n if (c != null) \r\n a.add(c);";
}
});
}
}
static public