Warning : session_start(): open(/var/lib/php/sessions/sess_4afv8n8rebphq622oof49q1ro8, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.match;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_mouseEvent;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.rethrow;
import static loadableUtils.utils.realMC_tl;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.IVF2;
import loadableUtils.utils.Matches;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.IterableIterator;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import static loadableUtils.utils.getExceptionCause;
import static loadableUtils.utils.joinWithSpace;
import static loadableUtils.utils.callF;
import static loadableUtils.utils.javaTok;
import static loadableUtils.utils.jlabel;
import static loadableUtils.utils.multiMapPut;
import static loadableUtils.utils.join;
import static loadableUtils.utils.isAWTThread;
import static loadableUtils.utils.set;
import static loadableUtils.utils.call;
import static loadableUtils.utils.fail;
import static loadableUtils.utils.print;
import static loadableUtils.utils.printAlsoToSystemOut;
import static loadableUtils.utils.doLater;
import static loadableUtils.utils.call_checkArgs;
import static loadableUtils.utils.cget;
import static loadableUtils.utils.db;
import loadableUtils.utils.IntRange;
import loadableUtils.utils.FixedRateTimer;
import loadableUtils.utils.MultiMap;
import loadableUtils.utils.Meta;
import loadableUtils.utils.JE_RepElement;
import loadableUtils.utils.ICachedJavaXExpr;
import loadableUtils.utils.ITokCondition;
import loadableUtils.utils.PingSource;
import loadableUtils.utils.ThreadPool;
import loadableUtils.utils.SimpleLiveValue;
import loadableUtils.utils.Matrix;
import loadableUtils.utils.IRef;
import loadableUtils.utils.F2;
import loadableUtils.utils.IProbabilisticScheduler;
import loadableUtils.utils.IBWIntegralImage;
import loadableUtils.utils.Producer;
import loadableUtils.utils.IntBuffer;
import loadableUtils.utils.DynPrintLogAndEnabled;
import loadableUtils.utils.OKOrError;
import loadableUtils.utils.WithTimestamp;
import loadableUtils.utils.AbstractJavaXExpr;
import loadableUtils.utils.Timestamp;
import loadableUtils.utils.DoubleRect;
import loadableUtils.utils.Complex;
import loadableUtils.utils.JavaCodec;
import loadableUtils.utils.JECompressionSearch;
import loadableUtils.utils.CompressionSearch_AnyType;
import loadableUtils.utils.RestartableCountdown;
import loadableUtils.utils.Either;
import loadableUtils.utils.FunctionCall;
import loadableUtils.utils.T3;
import loadableUtils.utils.Swingable;
import loadableUtils.utils.AbstractCompressor_AnyType;
import loadableUtils.utils.Average;
import loadableUtils.utils.BWIntegralImage;
import loadableUtils.utils.DoubleRange;
import loadableUtils.utils.CompressionRegime_AnyType;
import loadableUtils.utils.Seconds;
import static loadableUtils.utils.withTimestamp;
import static loadableUtils.utils.javaObjectToIJavaExpr;
import static loadableUtils.utils.lambdaMapMethod;
import static loadableUtils.utils.score;
import static loadableUtils.utils.withBorder;
import static loadableUtils.utils.quickSubstring;
import static loadableUtils.utils.childrenOfType;
import static loadableUtils.utils.nanoTime;
import static loadableUtils.utils.activateFrame_v3;
import static loadableUtils.utils.b;
import static loadableUtils.utils.ewicOneOf;
import static loadableUtils.utils.doEvery_daemon;
import static loadableUtils.utils.jCenteredSection;
import static loadableUtils.utils.n;
import static loadableUtils.utils.ivf1WithToString;
import static loadableUtils.utils.abs;
import static loadableUtils.utils.intMatrixToImage;
import static loadableUtils.utils.caseInsensitiveComparator;
import static loadableUtils.utils.getComponents;
import static loadableUtils.utils.area;
import static loadableUtils.utils.add;
import static loadableUtils.utils.singleComponentPanel;
import static loadableUtils.utils.withMargin;
import static loadableUtils.utils.addActionListener;
import static loadableUtils.utils.imageToMatrix;
import static loadableUtils.utils.hasMethod;
import static loadableUtils.utils.countIteratorToList;
import static loadableUtils.utils.containsOneOf;
import static loadableUtils.utils.dm_registerAs_direct;
import static loadableUtils.utils.setSCPComponent;
import static loadableUtils.utils.hideWindow;
import static loadableUtils.utils.ymdMinusHMS;
import static loadableUtils.utils.pingSource_tl;
import static loadableUtils.utils.jPopDownButton_noText;
import static loadableUtils.utils.swingLater;
import static loadableUtils.utils.matrixToList;
import static loadableUtils.utils._defaultClassFinder;
import static loadableUtils.utils.setImage;
import static loadableUtils.utils.isJavaIdentifier;
import static loadableUtils.utils.gridLOLToImage;
import static loadableUtils.utils.alwaysOnTop;
import static loadableUtils.utils.getScreenWidth;
import static loadableUtils.utils.tsNow;
import static loadableUtils.utils.jfind_preprocess;
import static loadableUtils.utils.dm_reload;
import static loadableUtils.utils.getDBProgramID;
import static loadableUtils.utils.setFrameIcon;
import static loadableUtils.utils.isIdentifier;
import static loadableUtils.utils.getSnippetTitle;
import static loadableUtils.utils.quickEval;
import static loadableUtils.utils.dm_fieldCheckBox;
import static loadableUtils.utils.isAlwaysOnTop;
import static loadableUtils.utils.infoBox;
import static loadableUtils.utils.toSeconds;
import static loadableUtils.utils.rect;
import static loadableUtils.utils.cleanUp;
import static loadableUtils.utils.forEach;
import static loadableUtils.utils.disposeWindow;
import static loadableUtils.utils.textFieldFromComboBox;
import static loadableUtils.utils.formatColonProperties_noNulls;
import static loadableUtils.utils.centerAndEast;
import static loadableUtils.utils.makeFrame;
import static loadableUtils.utils.okOrError;
import static loadableUtils.utils.setDoubleBuffered;
import static loadableUtils.utils.javaTokForJFind_array;
import static loadableUtils.utils.dm_doEvery;
import static loadableUtils.utils.mergeBufferedImagesHorizontally;
import static loadableUtils.utils.partialSums_firstIs0;
import static loadableUtils.utils.hgrid;
import static loadableUtils.utils.screenshot;
import static loadableUtils.utils.ping_v3;
import static loadableUtils.utils.flattenArray2;
import static loadableUtils.utils.formatDouble;
import static loadableUtils.utils.getParent;
import static loadableUtils.utils.strOrEmpty;
import static loadableUtils.utils.pqO;
import static loadableUtils.utils.javaExpr;
import static loadableUtils.utils.shorten_str;
import static loadableUtils.utils.run;
import static loadableUtils.utils.indexAsSideValue;
import static loadableUtils.utils.has;
import static loadableUtils.utils.last;
import static loadableUtils.utils.caseInsensitiveSet;
import static loadableUtils.utils.warn;
import static loadableUtils.utils.dm_moduleIsPoppedOut;
import static loadableUtils.utils.toRect;
import static loadableUtils.utils.installWindowDragger;
import static loadableUtils.utils.addIfNotNull;
import static loadableUtils.utils.jeCompressionSearch;
import static loadableUtils.utils.clipBufferedImage;
import static loadableUtils.utils.setText;
import static loadableUtils.utils.findButton;
import static loadableUtils.utils.splitAtSpace;
import static loadableUtils.utils.toJava;
import static loadableUtils.utils.getBounds;
import static loadableUtils.utils.northAndCenterWithMargin;
import static loadableUtils.utils.getAndClearList;
import static loadableUtils.utils.renderUserThreadsWithStackTraces;
import static loadableUtils.utils.newConceptsWithClassFinder;
import static loadableUtils.utils.replaceSublist;
import static loadableUtils.utils.selectedItem;
import static loadableUtils.utils.joinSubList;
import static loadableUtils.utils.defaultScreenshot;
import static loadableUtils.utils.activateFrame;
import static loadableUtils.utils.awtLater;
import static loadableUtils.utils.replace;
import static loadableUtils.utils.functionCall_list;
import static loadableUtils.utils.profileToConsole;
import static loadableUtils.utils.myLibraryFiles;
import static loadableUtils.utils.findCodeTokens;
import static loadableUtils.utils.printWithMS;
import static loadableUtils.utils.format;
import static loadableUtils.utils.heightForWidth;
import static loadableUtils.utils.onEnter;
import static loadableUtils.utils.hsplit;
import static loadableUtils.utils.mcDollar;
import static loadableUtils.utils.centerAndEastWithMargin;
import static loadableUtils.utils.getFrame;
import static loadableUtils.utils.jscroll_center;
import static loadableUtils.utils.dm_fieldLiveValue;
import static loadableUtils.utils.percentRatioStrOneDigit;
import static loadableUtils.utils.toObjectArray;
import static loadableUtils.utils.rectFromPoints;
import static loadableUtils.utils.runnableThread;
import static loadableUtils.utils.allScreenBounds;
import static loadableUtils.utils.findClass_fullName;
import static loadableUtils.utils.copyLocalLog;
import static loadableUtils.utils.jscroll_centered;
import static loadableUtils.utils.parentFile;
import static loadableUtils.utils.listSet;
import static loadableUtils.utils.gazelle_wavySpacer;
import static loadableUtils.utils.callOnLoadMethods;
import static loadableUtils.utils.toString;
import static loadableUtils.utils.colToList;
import static loadableUtils.utils.div;
import static loadableUtils.utils.removeFromParent;
import static loadableUtils.utils.renameFile;
import static loadableUtils.utils.isDigit;
import static loadableUtils.utils.mapQuickEval_javaExpr;
import static loadableUtils.utils.regionMatches;
import static loadableUtils.utils.warnIfOddCount;
import static loadableUtils.utils.printFileInfo;
import static loadableUtils.utils.interruptThread;
import static loadableUtils.utils.bindLiveValueListenerToComponent;
import static loadableUtils.utils.screenBounds;
import static loadableUtils.utils.metaSet;
import static loadableUtils.utils.calculateLengthOfFunctionCall;
import static loadableUtils.utils.toRectangle;
import static loadableUtils.utils.widthForHeight;
import static loadableUtils.utils.javaxCodeDir;
import static loadableUtils.utils.shortClassName_dropNumberPrefix;
import static loadableUtils.utils.minimizeWindow;
import static loadableUtils.utils.synchroLinkedHashSet;
import static loadableUtils.utils.jbutton;
import static loadableUtils.utils.setEnabled;
import static loadableUtils.utils.functionCall;
import static loadableUtils.utils.northAndCenter;
import static loadableUtils.utils.matrixToMNGrid_rows;
import static loadableUtils.utils.jline;
import static loadableUtils.utils.toMS;
import static loadableUtils.utils.isLongConstant;
import static loadableUtils.utils.forward;
import static loadableUtils.utils.vmBus_query;
import static loadableUtils.utils.change;
import static loadableUtils.utils.assertEquals;
import static loadableUtils.utils.getPreferredSize;
import static loadableUtils.utils.onClick;
import static loadableUtils.utils.rowToList;
import static loadableUtils.utils.jCheckBoxMenuItem;
import static loadableUtils.utils.jenableUndoRedo;
import static loadableUtils.utils.setChecked;
import static loadableUtils.utils.setFont;
import static loadableUtils.utils.syncList;
import static loadableUtils.utils.isEditableComboBox;
import static loadableUtils.utils.numberOfCores;
import static loadableUtils.utils.showWindow;
import static loadableUtils.utils.plus;
import static loadableUtils.utils.dm_watchField;
import static loadableUtils.utils.codeTokensAsStringArray;
import static loadableUtils.utils.ifloor;
import static loadableUtils.utils.hmsWithColonsAndMS;
import static loadableUtils.utils.dm_calculatedCenteredLabel;
import static loadableUtils.utils.repeat;
import static loadableUtils.utils.nohup;
import static loadableUtils.utils.onWindowClosing;
import static loadableUtils.utils.asArray;
import static loadableUtils.utils.showText;
import static loadableUtils.utils.setDefaultClassFinder;
import static loadableUtils.utils.getBytecodePathForClass;
import static loadableUtils.utils.smartAdd;
import static loadableUtils.utils.rCallF;
import static loadableUtils.utils.installWindowResizeDraggerOnBorder;
import static loadableUtils.utils.stepForNSeconds;
import static loadableUtils.utils.singular;
import static loadableUtils.utils.minus;
import static loadableUtils.utils.syncAddOrCreate;
import static loadableUtils.utils.getScreenHeight;
import static loadableUtils.utils.ratio;
import static loadableUtils.utils.boolPar;
import static loadableUtils.utils.fillRect;
import static loadableUtils.utils.westCenterAndEastWithMargin;
import static loadableUtils.utils.getSelectedItem;
import static loadableUtils.utils.loadAllClassesInByteCodePath;
import static loadableUtils.utils.dm_centeredFieldLabel;
import static loadableUtils.utils.similarEmptyMap;
import static loadableUtils.utils.toFile;
import static loadableUtils.utils.drop;
import static loadableUtils.utils.tempAdd;
import static loadableUtils.utils.pixelCount;
import static loadableUtils.utils.appendToBaseName;
import static loadableUtils.utils.dropFirst;
import static loadableUtils.utils.nClasses;
import static loadableUtils.utils.mod;
import static loadableUtils.utils.makeUndecoratedFrame;
import static loadableUtils.utils.seconds;
import static loadableUtils.utils.nanosToSeconds;
import static loadableUtils.utils.dm_toggleAlwaysOnTop;
import static loadableUtils.utils.humanizeFormLabel;
import static loadableUtils.utils.countPred;
import static loadableUtils.utils.wrapForSmartAdd;
import static loadableUtils.utils.asSet;
import static loadableUtils.utils.autoFrameTitle;
import static loadableUtils.utils.autoFrameTitle_value;
import static loadableUtils.utils.scaffoldCalled;
import static loadableUtils.utils.restart;
import static loadableUtils.utils.installTrayIcon;
import static loadableUtils.utils.filter;
import static loadableUtils.utils.onChange;
import static loadableUtils.utils.pingSource;
import static loadableUtils.utils.dm_popInModule;
import static loadableUtils.utils.isNonEmptySingleZip_byMagicHeader;
import static loadableUtils.utils.dm_vis;
import static loadableUtils.utils.probabilisticForEach;
import static loadableUtils.utils.setBackground;
import static loadableUtils.utils.renderVars;
import static loadableUtils.utils.elapsedSeconds;
import static loadableUtils.utils.hotwire;
import static loadableUtils.utils.matrixOfMatricesToListOfLists;
import static loadableUtils.utils.metaGet;
import static loadableUtils.utils.heldInstance;
import static loadableUtils.utils.getProgramName;
import static loadableUtils.utils.trayIcon_imageAutoSize;
import loadableUtils.utils.Pair;
import loadableUtils.utils.BetterThreadLocal;
import loadableUtils.utils.ISleeper_v2;
import loadableUtils.utils.Sleeping;
import loadableUtils.utils.IBWImage;
import java.awt.geom.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
class main {
static public void standaloneInit() {
__javax = x30.class;
x30.__javax = x30.class;
x30_pkg.x30_util.__setJavaX(x30.class);
x30.cleanKillMsg = "";
callOnLoadMethods(mc());
}
static public class Stem extends Concept {
static final public String _fieldOrder = "module frameRect alwaysOnTop autoUpdate window";
public DynModule module;
public Rect frameRect;
public boolean alwaysOnTop, autoUpdate;
transient public JFrame window;
public Rect getFrameRect() {
return toRect(getBounds(window));
}
public void saveFrameRect() {
setField("frameRect", getFrameRect());
}
public void setAlwaysOnTop(boolean alwaysOnTop) {
this.alwaysOnTop = alwaysOnTop;
change();
alwaysOnTop(window, alwaysOnTop);
}
public void setWindow(JFrame window) {
this.window = window;
if (frameRect != null)
setBounds(window, frameRect);
onWindowClosing(window, new Runnable() {
public void run() {
try {
cleanExit();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cleanExit();";
}
});
onBoundsChange(window, new Runnable() {
public void run() {
try {
saveFrameRect();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "saveFrameRect();";
}
});
alwaysOnTop(window, alwaysOnTop);
}
}
static public class GazelleHost {
public boolean _isTransient() {
return true;
}
public Stem stem;
public DynModule gazelle;
transient public String windowTitle = "November Gazelle v1";
transient public String downloadURL = "https://botcompany.de/jar/" + psI(programID()) + "?withLibs=1&noCompiler=1";
transient public String trayIconImageID = "#1103047";
transient public int borderSize = 5;
transient public Color color1 = awtColor("ADD8E6");
transient public Color color2 = awtColor("EEEEEE");
transient public Color color3 = awtColor("A3C0AA");
transient public IF0 moduleMaker;
transient public ThreadPool threadPool;
transient public TrayIcon trayIcon;
transient public JFrame mainWindow;
transient public Set argsSet;
transient public Concepts concepts;
public GazelleHost(ThreadPool threadPool, IF0 moduleMaker) {
this.moduleMaker = moduleMaker;
this.threadPool = threadPool;
}
public void trayIconLeftClick() {
activateFrame_v3(mainWindow);
}
public void makeTrayIcon() {
try {
trayIcon_imageAutoSize = false;
trayIcon = installTrayIcon(trayIconImageID, windowTitle, new Runnable() {
public void run() {
try {
trayIconLeftClick();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "trayIconLeftClick();";
}
}, "Show Gazelle", new Runnable() {
public void run() {
try {
activateFrame(mainWindow);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "activateFrame(mainWindow)";
}
}, "Exit Gazelle", new Runnable() {
public void run() {
try {
cleanExit();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cleanExit();";
}
});
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
public void run(String[] args) {
argsSet = asSet(args);
if (!argsSet.contains("noflatlaf"))
com.formdev.flatlaf.FlatLightLaf.setup();
if (contains(args, "profile"))
profileToConsole(() -> actualMain(args));
else
actualMain(args);
if (argsSet.contains("brexit"))
System.exit(0);
}
public void actualMain(String... args) {
vm_generalMap_put("stefansOS", this);
System.out.println(hmsWithColonsAndMS() + ": Init");
if (containsOneOf(argsSet, "upgrade", "update")) {
upgradeGazelle();
return;
}
makeTrayIcon();
initAutoUpdate();
assertEquals(callF(_defaultClassFinder(), "main$Stem"), Stem.class);
concepts = newConceptsWithClassFinder(programID);
concepts.fileLock().lockOrFail();
concepts.fileLock().deleteOnExit();
concepts.persist();
print("Concepts loaded: " + map(__31 -> className(__31), allConcepts(concepts)));
var stems = findConcepts(concepts, Stem.class);
print("Stems in DB: " + l(stems));
stem = first(stems);
if (stem == null) {
print("Starting new module");
stem = registerConcept(concepts, new Stem());
makeModule();
cset(stem, "module", gazelle);
} else {
gazelle = stem.module;
print("Depersisted module " + gazelle);
}
gazelle._host = stem;
setOpt(gazelle, "threadPool", threadPool);
copyLocalLog(gazelle, mc());
JComponent vis;
{
AutoCloseable __8 = gazelle.enter();
try {
gazelle.start();
printWithMS("Visualize");
vis = swing(() -> {
AutoCloseable __9 = gazelle.enter();
try {
return gazelle.visualize();
} finally {
_close(__9);
}
});
} finally {
_close(__8);
}
}
vis = makeWindowBorderAndTitle(vis, windowTitle);
printWithMS("Show frame");
JFrame frame = makeUndecoratedFrame(windowTitle, vis);
setFrameIcon(frame, trayIconImageID);
stem.setWindow(mainWindow = frame);
showWindow(stem.window);
printWithMS("Dudadoneski");
}
public void minimize() {
if (trayIcon == null)
minimizeWindow(mainWindow);
else
hideWindow(mainWindow);
}
public JComponent makeWindowBorderAndTitle(JComponent contents, String title) {
var icons = jline();
icons.add(jbutton("Minimize", new Runnable() {
public void run() {
try {
minimize();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "minimize();";
}
}));
icons.add(jbutton("Close", new Runnable() {
public void run() {
try {
cleanExit();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cleanExit();";
}
}));
icons.add(jPopDownButton_noText("Update Gazelle", runnableThread(new Runnable() {
public void run() {
try {
upgradeGazelle();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "upgradeGazelle();";
}
}), "Restart Gazelle", runnableThread(new Runnable() {
public void run() {
try {
restart();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "restart();";
}
}), jCheckBoxMenuItem_dyn("Auto-Update", () -> stem.autoUpdate, b -> cset(stem, "autoUpdate", b)), "Dump threads", runnableThread(new Runnable() {
public void run() {
try {
showText("User threads", renderUserThreadsWithStackTraces());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "showText(\"User threads\", renderUserThreadsWithStackTraces());";
}
}), jCheckBoxMenuItem_dyn("Always on top", () -> stem.alwaysOnTop, alwaysOnTop -> stem.setAlwaysOnTop(alwaysOnTop))));
var actualTitle = fontSizePlus(7, jCenteredLabel(title));
var spacer = gazelle_wavySpacer();
var titleBarMain = setOpaqueBackground(color1, westCenterAndEastWithMargin(jImage_scaledToHeight(24, trayIconImageID), actualTitle, setOpaqueBackground(color2, spacer)));
installWindowDragger(actualTitle);
installWindowDragger(spacer);
var titleBar = setBackground(color2, centerAndEast(titleBarMain, icons));
var border = BorderFactory.createLineBorder(color1, borderSize);
var outerPanel = withBorder(border, northAndCenter(titleBar, contents));
installWindowResizeDraggerOnBorder(outerPanel);
return outerPanel;
}
public Object dm_getStem(Object moduleOrID) {
return stem;
}
public Object resolveModule(Object moduleOrID) {
return moduleOrID == stem ? gazelle : moduleOrID;
}
public void cleanExit() {
{
startThread(new Runnable() {
public void run() {
try {
print("Saving DB for exit");
{
cleanUp(concepts);
concepts = null;
}
System.exit(0);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "print(\"Saving DB for exit\");\r\n { cleanUp(concepts); concepts = null; }\r\n...";
}
});
}
}
public File myJar() {
return getBytecodePathForClass(this);
}
public void upgradeGazelle() {
File myJar = myJar();
print("myJar", myJar);
String date = ymdMinusHMS();
File f = javaxCodeDir("Downloaded Updates/" + "gazelle-" + date + ".jar");
infoBox("Downloading Update...");
loadBinaryPageToFile(downloadURL, f);
printFileInfo(f);
if (!isNonEmptySingleZip_byMagicHeader(f)) {
infoBox("Bad file downloaded... :(");
return;
}
boolean replaced = false;
if (isFile(myJar)) {
print("Loaded " + nClasses(loadAllClassesInByteCodePath(myJar)));
print("Replacing with new version: " + myJar);
renameFile(myJar, appendToBaseName(myJar, ".bak." + date));
copyFile(f, myJar);
printFileInfo(myJar);
replaced = true;
}
infoBox(replaced ? "Installed update, replaced " + f2s(myJar) + " - now starting" : "Starting update, but could not replace originally downloaded jar");
restart(replaced ? myJar : f);
}
public void restart() {
restart(myJar());
}
public void restart(File jar) {
String javaCmd = or2(currentProcessCommand(), "java");
String cmd = pqO(javaCmd) + " -jar " + pqO(jar);
print(cmd);
nohup(cmd);
cleanExit();
}
public void makeModule() {
if (gazelle == null)
gazelle = callF(moduleMaker);
}
public void reloadModuleInBackground(Stem mod) {
restart();
}
public void initAutoUpdate() {
print("Making SnippetUpdateConnector.");
snippetUpdateConnector("verbose", true);
vmBus_onMessage("snippetUpdate", new VF1() {
public void get(List l) {
try {
String uri = getString(l, 1);
Matches m = new Matches();
if (swic(uri, "/transpileOK/", m))
if (sameSnippetID(programID(), firstIntAsString(m.rest()))) {
if (stem.autoUpdate)
upgradeGazelle();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S uri = getString(l, 1);\r\n new Matches m;\r\n if (swic(uri, \"/transpi...";
}
});
}
}
static public String programID;
static public void _onLoad_initUtils() {
utils.__javax = javax();
}
static public void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
name = replacePrefix("loadableUtils.utils$", "main$", name);
print("_onLoad_defaultClassFinder " + name);
Class c = findClass_fullName(name);
if (c != null)
return c;
if (name.startsWith("main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
return null;
}
});
}
static public ThreadLocal dynamicObjectIsLoading_threadLocal() {
return DynamicObject_loading;
}
static public class GazelleV extends DynPrintLogAndEnabled {
static public boolean _switchableField_maxFPS = true;
public double maxFPS = 10;
static public boolean _switchableField_previewWidth = true;
public int previewWidth = 200;
static public boolean _switchableField_statsEvery = true;
public double statsEvery = 5;
static public boolean _switchableField_brokenMethod = true;
volatile public boolean brokenMethod = false;
public int lookAtScreen;
public String previewMode;
public int gridRows = 20;
public boolean scaleDownPreviewImage = false;
public int previewPosterization = 256;
public String uiURL = "Home";
public PersistableThrowable lastProcessingError;
transient public WithTimestamp> lastScreen;
transient public Average screenShotTime = new Average();
transient public Average iiTime = new Average();
transient public Timestamp loopStarted;
transient public Sleeping screenShotCountdown;
transient public long screenShotCountdownTotalSleepTime;
transient public IIImageSurface imageSurface;
transient public Throwable currentProcessingError;
transient public JButton popDownButton;
transient public JComponent topControls;
transient public long screenShotsTaken;
transient public double fps;
transient public Compression ongoingCompression, completedCompression;
transient public String longTermCompressionProbability;
transient public String longTermCompressionScore;
transient public JComponent topControls2;
transient public JTabbedPane tabs;
transient public ThreadPool threadPool;
transient public SingleComponentPanel mainArea;
transient public Map> uiMap = syncCIMap();
transient public PingSource backgroundPingSource;
transient public OnOffOscillator onOffOscillator;
public Rect area() {
return screenBounds(min(lookAtScreen, screenCount() - 1));
}
public class Compression {
final public Compression setImage(BufferedImage image) {
return image(image);
}
public Compression image(BufferedImage image) {
this.image = image;
return this;
}
final public BufferedImage getImage() {
return image();
}
public BufferedImage image() {
return image;
}
public BufferedImage image;
final public Compression setIi(BWIntegralImage ii) {
return ii(ii);
}
public Compression ii(BWIntegralImage ii) {
this.ii = ii;
return this;
}
final public BWIntegralImage getIi() {
return ii();
}
public BWIntegralImage ii() {
return ii;
}
public BWIntegralImage ii;
public CompressionSearch_AnyType search;
public int baseLineLength;
public GridCodec1 codec;
public double compressionPercentage;
public String score() {
var submission = search == null ? null : search.bestSubmission();
Integer compressedSize = or(submission.compressedSize(), baseLineLength);
compressionPercentage = 100 - doubleRatio(compressedSize, baseLineLength) * 100;
return iround(compressionPercentage) + "%";
}
public IProbabilisticScheduler scheduler() {
return search == null ? null : search.scheduler();
}
public String probability() {
var scheduler = scheduler();
if (scheduler == null)
return "-";
var prob = scheduler.lastExecutedProbability();
return formatDouble(prob, 3);
}
transient public List onCompressionDone;
public Compression onCompressionDone(Runnable r) {
onCompressionDone = syncAddOrCreate(onCompressionDone, r);
return this;
}
public void compressionDone() {
pcallFAll(onCompressionDone);
}
public void run() {
try {
int lHex = pixelCount(image) * 8;
baseLineLength = calculateLengthOfFunctionCall("imageFromHex", lHex + 2);
print("baseLineLength", baseLineLength);
codec = new GridCodec1(image);
codec.rows = gridRows;
search = codec.forward();
for (int _repeat_6 = 0; _repeat_6 < 60; _repeat_6++) {
stepForNSeconds(1, search);
setFields("longTermCompressionProbability", probability(), "longTermCompressionScore", score());
}
try {
compressionDone();
List cellCompressions = codec.strat.codeForElements();
} catch (Throwable e) {
printStackTrace(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void drawOverlay(ImageSurface is, Graphics2D g) {
try {
codec.drawOverlay(is, g);
} catch (Throwable __e) {
printStackTrace(__e);
}
}
public int gridCols() {
return widthForHeight(ii.getWidth(), ii.getHeight(), gridRows);
}
}
public int gridCols(MakesBufferedImage ii) {
return widthForHeight(ii.getWidth(), ii.getHeight(), gridRows);
}
public void start() {
try {
super.start();
if (threadPool == null)
threadPool = maxThreadPool();
backgroundPingSource = new PingSource(threadPool, "Background");
onOffOscillator = new OnOffOscillator(backgroundPingSource);
ownResource(onOffOscillator);
onOffOscillator.start();
componentFieldsToKeep = litset("tabs");
dm_registerAs_direct("gazelleV");
dm_watchField("enabled", new Runnable() {
public void run() {
try {
if (enabled)
dm_reload();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (enabled) dm_reload();";
}
});
dm_doEvery(1.0, new Runnable() {
public void run() {
try {
if (dm_moduleIsPoppedOut())
adjustUIForPoppedOutWindow();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (dm_moduleIsPoppedOut()) adjustUIForPoppedOutWindow();";
}
});
print("Screen bounds: " + allScreenBounds());
initUIMap();
tabs = jtabs("Log", super.visualize(), "Local Data", jcenteredlabel("TODO"));
dm_doEvery(min(statsEvery, 10.0), statsEvery, new Runnable() {
public void run() {
try {
if (enabled)
printStats();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (enabled) printStats();";
}
});
loopStarted = tsNow();
shootAndAnalyze();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void shootAndAnalyze() {
backgroundPingSource.dO(new Runnable() {
public void run() {
try {
shootAndAnalyze_impl();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "shootAndAnalyze_impl();";
}
});
}
public void shootAndAnalyze_impl() {
AutoCloseable __10 = enter();
try {
if (!enabled)
return;
var targetTime = tsNow().plus(1.0 / maxFPS);
long time = nanoTime();
try {
lastScreen = withTimestamp(okOrError(() -> screenshot(area())));
++screenShotsTaken;
setField("fps", doubleRatio(screenShotsTaken, elapsedSeconds(loopStarted)));
screenShotTime.add(nanosToSeconds(nanoTime() - time));
time = nanoTime();
ping();
if (lastScreen.get().isOK()) {
var img = lastScreen.get().get();
var ii = new BWIntegralImage(img);
iiTime.add(nanosToSeconds(nanoTime() - time));
if (!deepCompression())
showPreview(ii, null);
else
startCompression(ii);
}
cpuTotal();
currentProcessingError = null;
} catch (Throwable e) {
printStackTrace(e);
setField("lastProcessingError", currentProcessingError = e);
}
screenShotCountdown = sleeper().doLater(targetTime, new Runnable() {
public void run() {
try {
shootAndAnalyze();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "shootAndAnalyze();";
}
});
screenShotCountdownTotalSleepTime += screenShotCountdown.remainingMS();
} finally {
_close(__10);
}
}
public boolean deepCompression() {
return !scaleDownPreviewImage;
}
public void showPreview(BWIntegralImage ii, Compression completedCompression) {
IBWIntegralImage ii2 = ii;
if (scaleDownPreviewImage) {
ii2 = new ScaledIBWIntegralImage(gridCols(ii2), gridRows, ii2);
ii2 = new TruncatedIBWIntegralImage(ii2);
if (previewPosterization < 256) {
if (imageSurface != null)
imageSurface.setImage(posterizeIBWImage(previewPosterization, ii2));
} else {
if (imageSurface != null)
imageSurface.setImage(ii2);
}
imageSurface.setOverlay(null);
} else {
{
if (imageSurface != null)
imageSurface.setImage(completedCompression.ii, completedCompression.image);
}
if (completedCompression != null)
imageSurface.setOverlay(g -> completedCompression.drawOverlay(imageSurface, g));
}
}
public void startCompression(BWIntegralImage ii) {
if (ongoingCompression == null) {
ping();
ongoingCompression = new Compression().image(lastScreen.get().get()).ii(ii);
ongoingCompression.onCompressionDone(() -> {
completedCompression = ongoingCompression;
ongoingCompression = null;
showPreview(ii, completedCompression);
});
ongoingCompression.run();
}
}
public void printStats() {
print(stats());
}
public String stats() {
var screen = lastScreen == null ? null : lastScreen.get();
return formatColonProperties_noNulls("Monitored area", area(), "Error", screen == null ? null : screen.getError(), "Last screenshot taken", lastScreen == null ? null : lastScreen.timeStamp(), "Average time to take a screenshot", screenShotTime, "Average time to make integral image", iiTime, "Capacity left in first core", percentRatioStrOneDigit(freeInCore()), "Total CPU used", cpuTotal());
}
public String cpuTotal() {
return setFieldAndReturn("cpuTotal", percentRatioStrOneDigit((1 - freeInCore()) / numberOfCores()));
}
public double freeInCore() {
return ratio(toSeconds(screenShotCountdownTotalSleepTime), elapsedSeconds(loopStarted));
}
{
}
public JComponent visualize() {
imageSurface = new IIImageSurface();
setDoubleBuffered(imageSurface, true);
imageSurface.setPixelated(true);
imageSurface.noAlpha = true;
return northAndCenterWithMargin(withMargin(withLabel("Show", comboBoxAndButton(onSelectedItem(bindComboBoxToLiveValue(centerComboBox(autoComboBox(uiURL, cloneKeys(uiMap))), dm_fieldLiveValue("uiURL")), url -> showUIURL(url)), "Go", url -> showUIURL(url)))), mainArea = singleComponentPanel(renderUIUrl(uiURL)));
}
public BufferedImage lastScreenImage() {
return getVar(getVar(lastScreen));
}
public void adjustUIForPoppedOutWindow() {
swing(new Runnable() {
public void run() {
try {
if (popDownButton == null) {
Window window = (Window) (getWindow(dm_vis()));
var popBackInButton = findButton(window, "Pop Back In");
var parent = getParent(popBackInButton);
print("parent", parent);
removeFromParent(parent);
popDownButton = jPopDownButton_noText("Pop Back In", new Runnable() {
public void run() {
try {
dm_popInModule(me());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_popInModule(me())";
}
}, jCheckBoxMenuItem("Always On Top", isAlwaysOnTop(window), new Runnable() {
public void run() {
try {
AutoCloseable __13 = enter();
try {
dm_toggleAlwaysOnTop();
} finally {
_close(__13);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); dm_toggleAlwaysOnTop();";
}
}));
addControl(popDownButton);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (popDownButton == null) {\r\n Window window = (Window) (getWindow(dm_v...";
}
});
}
public boolean useErrorHandling() {
return false;
}
final public JComponent renderUIURL(String url) {
return renderUIUrl(url);
}
final public JComponent uiGet(String url) {
return renderUIUrl(url);
}
public JComponent renderUIUrl(String url) {
var maker = uiMap.get(url);
var component = callF(maker);
if (component != null)
return component;
return jCenteredLabel("URL not found: " + url);
}
public void showUIURL(String url) {
AutoCloseable __11 = enter();
try {
url = trim(url);
setComponent(mainArea, renderUIUrl(url));
} finally {
_close(__11);
}
}
public A uiMapPut(String url, IF0 maker) {
uiMap.put(url, () -> maker.get());
return maker.get();
}
public void uiPut(String url, IF0 maker) {
uiMap.put(url, maker);
}
public void initUIMap() {
uiPut("FPS", () -> jCenteredSection("FPS", dm_calculatedCenteredLabel(() -> iround(fps))));
uiPut("Screen Selector", () -> {
var screenSelectors = jRadioButtons(countIteratorAsList(screenCount(), i -> "Screen " + (i + 1)));
selectRadioButton(screenSelectors, lookAtScreen);
onRadioButtonChange(screenSelectors, i -> {
setField("lookAtScreen", i);
});
return jline(buttonsInGroup(screenSelectors));
});
uiPut("Screenshot with controls", () -> northAndCenterWithMargin(topControls2 = jPanel(new WrapLayout(), flattenList2(dm_checkBox("enabled"), getChildren(renderUIURL("Screen Selector")), dm_spinnerWithLabel("gridRows", "Rows", 1, 500), dm_checkBox("Scale down", "scaleDownPreviewImage"), dm_spinnerWithLabel("previewPosterization", "Posterize", 2, 256))), jscroll_center(imageSurface)));
uiPut("Enabled", () -> dm_checkBox("enabled"));
uiPut("Home", () -> hsplit(northAndCenterWithMargin(topControls = hgrid(renderUIUrl("FPS"), jCenteredSection("Compression", dm_centeredFieldLabel("longTermCompressionScore")), jCenteredSection("CPU (" + numberOfCores() + ")", dm_centeredFieldLabel("cpuTotal"))), tabs), renderUIUrl("Screenshot with controls")));
}
}
static public boolean _moduleClass_GazelleV = true;
static public String windowTitle = "November Gazelle";
static public String progIDForDBAndAutoUpdate = "#1033525";
static public boolean pingSourceStrictMode = false;
static public GazelleHost host;
static public GazelleV client;
static public ThreadPool threadPool;
public static void main(final String[] args) throws Exception {
loadableUtils.utils.__setJavaX(x30.class);
standaloneInit();
ping_v3_setPingSourceMaker(() -> {
System.out.println("pingSourceMaker");
if (pingSourceStrictMode)
throw fail("Strict mode - make a ping source first!!");
return new PingSource(threadPool, "legacy");
});
threadPool = new ThreadPool(findIntArg("cores", args, numberOfCores()));
print(threadPool);
PingSource ps = new PingSource(threadPool, print("Starting Gazelle"));
ps.dO(() -> {
System.out.println("Pinging");
ping();
print("Pinged");
programID = progIDForDBAndAutoUpdate;
host = new GazelleHost(threadPool, () -> {
return client = new GazelleV();
});
host.windowTitle = windowTitle;
host.run(args);
if (!cic(args, "console")) {
print("Stopping System.out");
printAlsoToSystemOut = false;
}
});
print("aha.");
}
static volatile public Concepts mainConcepts;
static public Concepts db_mainConcepts() {
if (mainConcepts == null)
mainConcepts = newConceptsWithClassFinder(getDBProgramID());
return mainConcepts;
}
static public void cleanMeUp_concepts() {
if (db_mainConcepts() != null)
db_mainConcepts().cleanMeUp();
}
static public Class mc() {
return main.class;
}
static public A setBounds(final int x, final int y, final int w, final int h, final A a) {
if (a != null) {
swing(new Runnable() {
public void run() {
try {
a.setBounds(x, y, w, h);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.setBounds(x, y, w, h);";
}
});
}
return a;
}
static public A setBounds(A a, Rect r) {
if (a != null && r != null) {
swing(new Runnable() {
public void run() {
try {
a.setBounds(toRectangle(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.setBounds(toRectangle(r));";
}
});
}
return a;
}
static public A setBounds(Rect r, A a) {
return setBounds(a, r);
}
static public A setBounds(A a, int x, int y, int w, int h) {
return setBounds(x, y, w, h, a);
}
static public CleanExit cleanExit(String msg) {
throw new CleanExit(msg);
}
static public CleanExit cleanExit() {
throw new CleanExit();
}
static public A onBoundsChange(A c, final Object r) {
if (c != null && r != null) {
swing(new Runnable() {
public void run() {
try {
c.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
pcallF(r);
}
public void componentMoved(ComponentEvent e) {
pcallF(r);
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.addComponentListener(new ComponentAdapter {\r\n public void componentRes...";
}
});
}
return c;
}
static public A onBoundsChange(Object r, A c) {
return onBoundsChange(c, r);
}
static public long psI(String snippetID) {
return parseSnippetID(snippetID);
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public java.awt.Color awtColor(String hex) {
byte[] b = bytesFromHex(dropPrefix("#", hex));
return new Color(ubyteToInt(b[0]), ubyteToInt(b[1]), ubyteToInt(b[2]));
}
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 boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Iterable it, Object a) {
if (it != null)
for (Object o : it) if (eq(a, o))
return true;
return false;
}
static public boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
static public boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static public boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static public boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static public boolean contains(Producer p, A a) {
if (p != null && a != null)
while (true) {
A x = p.next();
if (x == null)
break;
if (eq(x, a))
return true;
}
return false;
}
static public Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static public List map(Iterable l, Object f) {
return map(f, l);
}
static public List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) {
ping();
x.add(callF(f, o));
}
return x;
}
static public List map(Iterable l, F1 f) {
return map(f, l);
}
static public List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) {
ping();
x.add(callF(f, o));
}
return x;
}
static public List map(IF1 f, Iterable l) {
return map(l, f);
}
static public List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) {
ping();
x.add(f.get(o));
}
return x;
}
static public List map(IF1 f, A[] l) {
return map(l, f);
}
static public List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) {
ping();
x.add(f.get(o));
}
return x;
}
static public List map(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
ping();
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static public List map(IF1 f, A data1, A... moreData) {
List x = emptyList(l(moreData) + 1);
x.add(f.get(data1));
if (moreData != null)
for (A o : moreData) {
ping();
x.add(f.get(o));
}
return x;
}
static public String className(Object o) {
return getClassName(o);
}
static public Collection allConcepts() {
return db_mainConcepts().allConcepts();
}
static public Collection allConcepts(Concepts concepts) {
return concepts.allConcepts();
}
static public Collection findConcepts(Class c, Object... params) {
return findConceptsWhere(c, params);
}
static public Collection findConcepts(String c, Object... params) {
return findConceptsWhere(c, params);
}
static public Collection findConcepts(Concepts concepts, Class c, Object... params) {
return findConceptsWhere(concepts, c, params);
}
static public Collection findConcepts(Concepts concepts, String c, Object... params) {
return findConceptsWhere(concepts, c, params);
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public Pair first(Map map) {
return mapEntryToPair(first(entrySet(map)));
}
static public Pair first(MultiMap mm) {
if (mm == null)
return null;
var e = first(mm.data.entrySet());
if (e == null)
return null;
return pair(e.getKey(), first(e.getValue()));
}
static public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public Character first(CharSequence s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public A first(T3 t) {
return t == null ? null : t.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public int first(IntBuffer buf) {
return buf.get(0);
}
static public A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static public A first(AppendableChain a) {
return a == null ? null : a.element;
}
static public A registerConcept(A c) {
return registerConcept(db_mainConcepts(), c);
}
static public A registerConcept(Concepts cc, A c) {
{
if (cc != null)
cc.register(c);
}
return 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 _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 JCheckBoxMenuItem jCheckBoxMenuItem_dyn(String text, IF0 checked, Object r) {
JCheckBoxMenuItem mi = jCheckBoxMenuItem(text, false, r);
if (checked != null)
bindToComponent(mi, new Runnable() {
public void run() {
try {
boolean b = isTrue(checked.get());
setChecked(mi, b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "boolean b = isTrue(checked!);\r\n ifdef jCheckBoxMenuItem_dyn_debug\r\n p...";
}
}, new Runnable() {
public void run() {
try {
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef jCheckBoxMenuItem_dyn_debug\r\n print(\"jCheckBoxMenuItem_dyn: hiding...";
}
});
return mi;
}
static public JCheckBoxMenuItem jCheckBoxMenuItem_dyn(String text, IF0 checked, IVF1 r) {
return jCheckBoxMenuItem_dyn(text, checked, (Object) r);
}
static public A fontSizePlus(final int delta, final A c) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
Font font = c.getFont();
c.setFont(font.deriveFont(font.getSize2D() + delta));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Font font = c.getFont();\r\n c.setFont(font.deriveFont(font.getSize2D()+delt...";
}
});
}
return c;
}
static public JLabel jCenteredLabel(String text) {
return jcenteredLabel(text);
}
static public JLabel jCenteredLabel() {
return jcenteredLabel();
}
static public A setOpaqueBackground(final Color color, final A a) {
if (a != null) {
swing(new Runnable() {
public void run() {
try {
a.setBackground(color);
a.setOpaque(true);
a.putClientProperty("substancelaf.colorizationFactor", 1.0);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.setBackground(color);\r\n a.setOpaque(true);\r\n a.putClientProperty(\"sub...";
}
});
}
return a;
}
static public JLabel jImage_scaledToHeight(String imageID, int height) {
return jImage(resizeImageToHeight_bilinear(loadImage2(imageID), height));
}
static public JLabel jImage_scaledToHeight(int height, String imageID) {
return jImage_scaledToHeight(imageID, height);
}
static public Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static public Thread startThread(String name, Runnable runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(runnable, name));
}
static public Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static public Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static public File myJar() {
return first(myLibraryFiles());
}
static public void loadBinaryPageToFile(String url, File file) {
try {
print("Loading " + url);
loadBinaryPageToFile(openConnection(new URL(url)), file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void loadBinaryPageToFile(URLConnection con, File file) {
try {
setHeaders(con);
loadBinaryPageToFile_noHeaders(con, file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void loadBinaryPageToFile_noHeaders(URLConnection con, File file) {
try {
File ftemp = new File(f2s(file) + "_temp");
FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
try {
InputStream inputStream = con.getInputStream();
long len = 0;
try {
len = con.getContentLength();
} catch (Throwable e) {
printStackTrace(e);
}
String pat = " {*}" + (len != 0 ? "/" + len : "") + " bytes loaded.";
copyStreamWithPrints(inputStream, buf, pat);
inputStream.close();
buf.close();
file.delete();
renameFile_assertTrue(ftemp, file);
} finally {
if (buf != null)
buf.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isFile(File f) {
return f != null && f.isFile();
}
static public boolean isFile(String path) {
return isFile(newFile(path));
}
static public File copyFile(File src, File dest) {
try {
FileInputStream inputStream = new FileInputStream(src.getPath());
FileOutputStream outputStream = newFileOutputStream(dest.getPath());
try {
copyStream(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
return dest;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static public String f2s(String s) {
return f2s(newFile(s));
}
static public String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static public String or2(String a, String b) {
return nempty(a) ? a : b;
}
static public String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
static public String currentProcessCommand() {
ProcessHandle processHandle = ProcessHandle.current();
return getVar(processHandle.info().command());
}
static public StefansOS_ConnectToServer snippetUpdateConnector(Object... __) {
boolean verbose = boolPar("verbose", __);
StefansOS_ConnectToServer connector = new StefansOS_ConnectToServer();
connector.onLine = new VF1() {
public void get(String line) {
try {
Matches m = new Matches();
if (startsWith(line, "snippetUpdates:", m)) {
if (verbose)
print(line);
String msg = m.rest();
vmBus_send("snippetUpdate", safeUnstruct(msg));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new Matches m;\r\n if (startsWith(line, \"snippetUpdates:\", m)) {\r\n if (...";
}
};
connector.startWithSubs("snippetUpdates");
return connector;
}
static public AutoCloseable vmBus_onMessage(String msg, IVF1 onMessage) {
return vmBus_onMessage(msg, ivf1ToVF1(onMessage));
}
static public AutoCloseable vmBus_onMessage(final String msg, final VF1 onMessage) {
Map map = vm_busListenersByMessage_live();
synchronized (map) {
Set listeners = map.get(msg);
if (listeners == null)
map.put(msg, listeners = syncIdentityHashSet());
return tempAdd(listeners, new VF2() {
public void get(String _msg, Object arg) {
try {
callF(onMessage, arg);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, arg)";
}
});
}
}
static public AutoCloseable vmBus_onMessage(String msg, final VF2 onMessage) {
return vmBus_onMessage(msg, new VF1() {
public void get(Object[] o) {
try {
callF(onMessage, first(o), second(o));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, first(o), second(o));";
}
});
}
static public AutoCloseable vmBus_onMessage(String msg, final IVF2 onMessage) {
return vmBus_onMessage(msg, new VF1() {
public void get(Object[] o) {
try {
callF(onMessage, first(o), second(o));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, first(o), second(o));";
}
});
}
static public AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) {
return vmBus_onMessage(msg, runnableToVF1(onMessage));
}
static public String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
static public String getString(List l, int idx) {
return (String) get(l, idx);
}
static public String getString(Object o, Object key) {
if (o instanceof Map)
return getString((Map) o, key);
if (key instanceof String)
return (String) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
static public String getString(String key, Object o) {
return getString(o, (Object) key);
}
static public boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static public boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
static public boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b))
return false;
return parseSnippetID(a) == parseSnippetID(b);
}
static public String firstIntAsString(String s) {
return jextract("", s);
}
static public Class javax() {
return getJavaX();
}
static public String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix))
return s;
return replacement + substring(s, l(prefix));
}
static public Map syncCIMap() {
return (Map) synchroMap(caseInsensitiveMap());
}
static public int min(int a, int b) {
return Math.min(a, b);
}
static public long min(long a, long b) {
return Math.min(a, b);
}
static public float min(float a, float b) {
return Math.min(a, b);
}
static public float min(float a, float b, float c) {
return min(min(a, b), c);
}
static public double min(double a, double b) {
return Math.min(a, b);
}
static public double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static public float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static public byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
static public short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
static public int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
static public int screenCount() {
return l(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices());
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static public double doubleRatio(double x, double y) {
return y == 0 ? 0 : x / y;
}
static public double doubleRatio(Seconds x, Seconds y) {
return doubleRatio(x.get(), y.get());
}
static public int iround(double d) {
return (int) Math.round(d);
}
static public int iround(Number n) {
return iround(toDouble(n));
}
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 A printStackTrace(A e) {
if (e != null)
print(getStackTrace(e));
return e;
}
static public void printStackTrace() {
printStackTrace(new Throwable());
}
static public void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static public void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static public ThreadPool maxThreadPool() {
return new ThreadPool(numberOfCores());
}
static public void ownResource(AutoCloseable c) {
_registerAutoCloseable(c);
}
static public HashSet litset(A... items) {
return lithashset(items);
}
static public JTabbedPane jtabs(Object... x) {
return fillJTabs(swingNu(JTabbedPane.class), x);
}
static public JLabel jcenteredlabel(String text) {
return jcenteredLabel(text);
}
static public JLabel jcenteredlabel() {
return jcenteredLabel();
}
static public boolean ping() {
return ping(pingSource());
}
static public boolean ping(PingSource source) {
ping_v3(source);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
return ping();
}
static volatile public boolean ping_pauseAll = false;
static public ISleeper_v2 sleeper() {
var ps = pingSource();
return ps == null ? new MultiSleeper() : ps.sleeper();
}
static public IBWImage posterizeIBWImage(int brightnessLevels, IBWImage img) {
if (brightnessLevels >= 256 || img == null)
return img;
int w = img.getWidth(), h = img.getHeight();
return new IBWImage() {
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
public float getFloatPixel(int x, int y) {
return (float) quantizeToNLevelsBetweenZeroAndOne_stretch(brightnessLevels, img.getFloatPixel(x, y));
}
};
}
static public JComponent withLabel(String label, JComponent component) {
return westAndCenter(jlabel(label + " "), component);
}
static public JComponent withLabel(JComponent label, JComponent component) {
return westAndCenterWithMargin(label, component);
}
static public JPanel comboBoxAndButton(JComboBox cb, String buttonText, IVF1 onEnter) {
Runnable r = new Runnable() {
public void run() {
try {
callF(onEnter, getText(cb));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onEnter, getText(cb))";
}
};
return centerAndEastWithMargin(onEnter(cb, r), jbutton(buttonText, r));
}
static public JComboBox onSelectedItem(final JComboBox cb, final VF1 f) {
addActionListener(cb, new Runnable() {
public void run() {
try {
pcallF(f, selectedItem(cb));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcallF(f, selectedItem(cb))";
}
});
return cb;
}
static public JComboBox onSelectedItem(final JComboBox cb, IVF1 f) {
addActionListener(cb, new Runnable() {
public void run() {
try {
pcallF(f, selectedItem(cb));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcallF(f, selectedItem(cb))";
}
});
return cb;
}
static public ThreadLocal bindComboBoxToLiveValue_debug = new ThreadLocal();
static public A bindComboBoxToLiveValue(final A cb, final SimpleLiveValue lv) {
final boolean debug = isTrue(bindComboBoxToLiveValue_debug.get());
bindLiveValueListenerToComponent(cb, lv, new Runnable() {
public void run() {
try {
selectItem(cb, lv.get());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "selectItem(cb, lv!)";
}
});
onChange(cb, new Runnable() {
public void run() {
try {
String s = getText(cb);
if (debug)
print("ComboBox: " + s);
lv.set(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "String s = getText(cb); // also works on editable combo boxes\r\n if (debug)...";
}
});
return cb;
}
static public JComboBox centerComboBox(JComboBox cb) {
centerTextField(textFieldFromComboBox(cb));
return cb;
}
static public AutoComboBox autoComboBox() {
return autoComboBox(new ArrayList());
}
static public AutoComboBox autoComboBox(final Collection items) {
return swing(new F0() {
public AutoComboBox get() {
try {
AutoComboBox cb = new AutoComboBox();
cb.setKeyWord(items);
return cb;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new AutoComboBox cb;\r\n cb.setKeyWord(items);\r\n ret cb;";
}
});
}
static public AutoComboBox autoComboBox(String value, Collection items) {
return setText(autoComboBox(items), value);
}
static public List cloneKeys(Map map) {
return cloneList(keys(map));
}
static public A getVar(IF0 v) {
return v == null ? null : v.get();
}
static public A getVar(Optional v) {
return v == null ? null : v.orElse(null);
}
static public Window getWindow(Object o) {
if (!(o instanceof Component))
return null;
return swing(() -> {
Component c = (Component) o;
while (c != null) {
if (c instanceof Window)
return ((Window) c);
c = c.getParent();
}
return null;
});
}
static public String trim(String s) {
return s == null ? null : s.trim();
}
static public String trim(StringBuilder buf) {
return buf.toString().trim();
}
static public String trim(StringBuffer buf) {
return buf.toString().trim();
}
static public void 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 ButtonGroup jRadioButtons(Collection strings) {
return jradiobuttons(strings);
}
static public ButtonGroup jRadioButtons(String... strings) {
return jradiobuttons(strings);
}
static public List countIteratorAsList(int b) {
return countIteratorAsList(0, b);
}
static public List countIteratorAsList(int a, int b) {
return countIteratorToList(a, b);
}
static public List countIteratorAsList(int b, IF1 f) {
return countIteratorAsList(0, b, f);
}
static public List countIteratorAsList(int a, int b, IF1 f) {
return countIteratorToList(a, b, f);
}
static public List countIteratorAsList(int a, int b, int step) {
return countIteratorToList(a, b, step);
}
static public List countIteratorAsList(double a, double b, double step, IF1 f) {
return countIteratorToList(a, b, step, f);
}
static public List countIteratorAsList(double a, double b, double step) {
return countIteratorToList(a, b, step);
}
static public List countIteratorAsList(IF1 f, double a, double b, double step) {
return countIteratorToList(f, a, b, step);
}
static public List countIteratorAsList(IF1 f, int b) {
return countIteratorAsList(f, 0, b);
}
static public List countIteratorAsList(IF1 f, int a, int b) {
return countIteratorToList(f, a, b);
}
static public void selectRadioButton(final AbstractButton rb) {
if (rb == null)
return;
{
swing(new Runnable() {
public void run() {
try {
rb.setSelected(true);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "rb.setSelected(true);";
}
});
}
}
static public void selectRadioButton(ButtonGroup group, int index) {
selectRadioButton(get(buttonsInGroup(group), index));
}
static public void onRadioButtonChange(final ButtonGroup group, final Object f) {
final Var idx = new Var(selectedButtonIdx(group));
Runnable r = new Runnable() {
public void run() {
try {
int idx2 = selectedButtonIdx(group);
if (idx2 >= 0 && idx2 != idx.get()) {
idx.set(idx2);
pcallF(f, idx2);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "int idx2 = selectedButtonIdx(group);\r\n if (idx2 >= 0 && idx2 != idx.get())...";
}
};
for (AbstractButton b : buttonsInGroup(group)) onChange(b, r);
}
static public void onRadioButtonChange(ButtonGroup group, IVF1 f) {
onRadioButtonChange(group, (Object) f);
}
static public List buttonsInGroup(ButtonGroup g) {
if (g == null)
return ll();
return asList(g.getElements());
}
static public JPanel jPanel(LayoutManager layout, Object... components) {
return jPanel(layout, asList(components));
}
static public JPanel jPanel(LayoutManager layout, List components) {
return smartAdd(jpanel(layout), components);
}
static public JPanel jPanel() {
return jpanel();
}
static public List flattenList2(Object... a) {
List l = new ArrayList();
if (a != null)
for (Object x : a) if (x instanceof Collection)
for (Object sub : (Collection) x) l.addAll(flattenList2(sub));
else if (x != null)
l.add(x);
return l;
}
static public JCheckBox dm_checkBox(String field) {
return dm_fieldCheckBox(field);
}
static public JCheckBox dm_checkBox(String text, String field) {
return dm_fieldCheckBox(text, field);
}
static public List getChildren(final Container c) {
return c == null ? emptyList() : swing(new F0>() {
public List get() {
try {
return asList(c.getComponents());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret asList(c.getComponents());";
}
});
}
static public JComponent dm_spinnerWithLabel(String field, int min, int max) {
return dm_spinnerWithLabel(field, humanizeLabel(field), min, max);
}
static public JComponent dm_spinnerWithLabel(String field, String label, int min, int max) {
return withLabel(label, dm_spinner(field, min, max));
}
static public void ping_v3_setPingSourceMaker(IF0 pingMaker) {
vm_generalMap_set("ping_v3_pingSourceMaker", pingMaker);
}
static public int findIntArg(String name, String[] args, int defaultValue) {
int i = indexOfIC(args, name);
return i >= 0 && i + 1 < l(args) ? parseInt(args[i + 1]) : defaultValue;
}
static public int cores() {
return numberOfCores();
}
static public boolean cic(Collection l, String s) {
return containsIgnoreCase(l, s);
}
static public boolean cic(String[] l, String s) {
return containsIgnoreCase(l, s);
}
static public boolean cic(String s, char c) {
return containsIgnoreCase(s, c);
}
static public boolean cic(String a, String b) {
return containsIgnoreCase(a, b);
}
static public Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public void pcallF(VF1 f, A a) {
try {
{
if (f != null)
f.get(a);
}
} catch (Throwable __e) {
printStackTrace(__e);
}
}
static public Object pcallF(Runnable r) {
try {
{
if (r != null)
r.run();
}
return null;
} catch (Throwable __e) {
return null;
}
}
static public A pcallF(IF0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(IF1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
static public String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
static public String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static public String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static public byte[] bytesFromHex(String s) {
return hexToBytes(s);
}
static public String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static public int ubyteToInt(byte b) {
return b & 0x0FF;
}
static public int ubyteToInt(char c) {
return c & 0x0FF;
}
static volatile public PersistableThrowable lastException_lastException;
static public PersistableThrowable lastException() {
return lastException_lastException;
}
static public void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static public Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
static public Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
static public String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
static public String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=");
}
static public String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static public 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 int unnull(Integer i) {
return i == null ? 0 : i;
}
static public long unnull(Long l) {
return l == null ? 0L : l;
}
static public double unnull(Double l) {
return l == null ? 0.0 : l;
}
static public String baseClassName(String className) {
return substring(className, className.lastIndexOf('.') + 1);
}
static public String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
static public String prependIfNempty(String prefix, String s) {
return empty(s) ? unnull(s) : prefix + s;
}
static public boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public B mapPutOrRemove(Map map, A key, B value) {
if (map != null && key != null)
if (value != null)
return map.put(key, value);
else
return map.remove(key);
return null;
}
static public Map vm_generalMap_map;
static public Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static public ArrayList emptyList() {
return new ArrayList();
}
static public ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
static public ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static public ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
static public ArrayList emptyList(Class c) {
return new ArrayList();
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(long[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(double[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static public ArrayList asList(short[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (short i : a) l.add(i);
return l;
}
static public ArrayList asList(Iterator it) {
ArrayList l = new ArrayList();
if (it != null)
while (it.hasNext()) l.add(it.next());
return l;
}
static public ArrayList asList(IterableIterator s) {
return asList((Iterator) s);
}
static public ArrayList asList(Iterable s) {
if (s instanceof ArrayList)
return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s) l.add(a);
return l;
}
static public ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null)
while ((a = p.next()) != null) l.add(a);
return l;
}
static public ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public Collection findConceptsWhere(Class c, Object... params) {
return findConceptsWhere(db_mainConcepts(), c, params);
}
static public Collection findConceptsWhere(String c, Object... params) {
return findConceptsWhere(db_mainConcepts(), c, params);
}
static public Collection findConceptsWhere(Concepts concepts, Class c, Object... params) {
ping();
params = expandParams(c, params);
if (concepts.fieldIndices != null)
for (int i = 0; i < l(params); i += 2) {
IFieldIndex index = concepts.getFieldIndex(c, (String) params[i]);
if (index != null) {
Collection rawList = index.getAll(params[i + 1]);
params = dropEntryFromParams(params, i);
if (params == null)
return rawList;
List l = new ArrayList();
for (A x : rawList) if (checkConceptFields(x, params))
l.add(x);
return l;
}
}
return filterConcepts(concepts.list(c), params);
}
static public Collection findConceptsWhere(Concepts concepts, String c, Object... params) {
return filterConcepts(concepts.list(c), params);
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean empty(Iterable c) {
return c == null || !c.iterator().hasNext();
}
static public boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean empty(Map map) {
return map == null || map.isEmpty();
}
static public boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static public boolean empty(BitSet bs) {
return bs == null || bs.isEmpty();
}
static public boolean empty(Object o) {
if (o instanceof Collection)
return empty((Collection) o);
if (o instanceof String)
return empty((String) o);
if (o instanceof Map)
return empty((Map) o);
if (o instanceof Object[])
return empty((Object[]) o);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static public boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
static public boolean empty(double[] a) {
return a == null || a.length == 0;
}
static public boolean empty(float[] a) {
return a == null || a.length == 0;
}
static public boolean empty(int[] a) {
return a == null || a.length == 0;
}
static public boolean empty(long[] a) {
return a == null || a.length == 0;
}
static public boolean empty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean empty(short[] a) {
return a == null || a.length == 0;
}
static public boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
static public boolean empty(MultiMap mm) {
return mm == null || mm.isEmpty();
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public boolean empty(IntRange r) {
return r == null || r.empty();
}
static public boolean empty(DoubleRange r) {
return r == null || r.isEmpty();
}
static public boolean empty(IntBuffer b) {
return b == null || b.isEmpty();
}
static public boolean empty(Rect r) {
return !(r != null && r.w != 0 && r.h != 0);
}
static public boolean empty(AppendableChain c) {
return c == null;
}
static public Pair mapEntryToPair(Map.Entry e) {
return e == null ? null : pair(e.getKey(), e.getValue());
}
static public Set> entrySet(Map map) {
return _entrySet(map);
}
static public Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
static public A firstThat(Iterable l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(A[] l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public A firstThat(IF1 pred, A[] l) {
return firstThat(l, pred);
}
static public 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 JLabel jcenteredLabel(String text) {
return setHorizontalAlignment(JLabel.CENTER, jLabel(text));
}
static public JLabel jcenteredLabel() {
return jcenteredLabel(" ");
}
static public JLabel jImage(Image img) {
return jimage(img);
}
static public JLabel jImage(String imageID) {
return jimage(imageID);
}
static public BufferedImage resizeImageToHeight_bilinear(BufferedImage img, int newH) {
return scaleImage_bilinear(doubleRatio(newH, img.getHeight()), img);
}
static public BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static public BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
static public String defaultThreadName_name;
static public String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static public Runnable wrapAsActivity(Object r) {
if (r == null)
return null;
Runnable r2 = toRunnable(r);
Object mod = dm_current_generic();
if (mod == null)
return r2;
return new Runnable() {
public void run() {
try {
AutoCloseable c = (AutoCloseable) (rcall("enter", mod));
AutoCloseable __1 = c;
try {
r2.run();
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable c = (AutoCloseable) (rcall enter(mod));\r\n temp c;\r\n r2.r...";
}
};
}
static public Thread newThread(Object runnable) {
return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)));
}
static public Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static public Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
static public Runnable toRunnable(final Object o) {
if (o instanceof Runnable)
return (Runnable) o;
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
static public Map _registerThread_threads;
static public Object _onRegisterThread;
static public Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static public void _registerThread() {
_registerThread(Thread.currentThread());
}
static public 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 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 FileOutputStream newFileOutputStream(File path) throws IOException {
return newFileOutputStream(path.getPath());
}
static public FileOutputStream newFileOutputStream(String path) throws IOException {
return newFileOutputStream(path, false);
}
static public FileOutputStream newFileOutputStream(File path, boolean append) throws IOException {
return newFileOutputStream(path.getPath(), append);
}
static public FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
mkdirsForFile(path);
FileOutputStream f = new FileOutputStream(path, append);
_registerIO(f, path, true);
return f;
}
public static File mkdirsFor(File file) {
return mkdirsForFile(file);
}
static public void copyStreamWithPrints(InputStream in, OutputStream out, String pat) {
try {
byte[] buf = new byte[65536];
int total = 0;
while (true) {
int n = in.read(buf);
if (n <= 0)
return;
out.write(buf, 0, n);
if ((total + n) / 100000 > total / 100000)
print(pat.replace("{*}", str(roundDownTo(100000, total))));
total += n;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File renameFile_assertTrue(File a, File b) {
try {
if (a.equals(b))
return b;
if (!a.exists())
throw fail("Source file not found: " + f2s(a));
if (b.exists())
throw fail("Target file exists: " + f2s(b));
mkdirsForFile(b);
if (!a.renameTo(b))
throw fail("Can't rename " + f2s(a) + " to " + f2s(b));
return b;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static public File newFile(String name) {
return name == null ? null : new File(name);
}
static public File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static public void copyStream(InputStream in, OutputStream out) {
try {
byte[] buf = new byte[65536];
while (true) {
int n = in.read(buf);
if (n <= 0)
return;
out.write(buf, 0, n);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(BitSet bs) {
return !empty(bs);
}
static public boolean nempty(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(MultiMap mm) {
return mm != null && !mm.isEmpty();
}
static public boolean nempty(Object o) {
return !empty(o);
}
static public boolean nempty(IntRange r) {
return !empty(r);
}
static public boolean nempty(IntBuffer b) {
return b != null && !b.isEmpty();
}
static public boolean nempty(Rect r) {
return r != null && r.w != 0 && r.h != 0;
}
static public boolean nempty(MultiSet ms) {
return ms != null && !ms.isEmpty();
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
if (m != null)
m.m = new String[] { substring(a, strL(b)) };
return true;
}
static public boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static public void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg);
pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static public Object safeUnstruct(String s) {
return unstructure(s, true);
}
static public VF1 ivf1ToVF1(IVF1 f) {
return f == null ? null : new VF1 () {
public void get(A a) {
try {
f.get(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "f.get(a)";
}
};
}
static public Map vm_busListenersByMessage_live_cache;
static public Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
static public Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static public A second(List l) {
return get(l, 1);
}
static public A second(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
if (!it.hasNext())
return null;
it.next();
return it.hasNext() ? it.next() : null;
}
static public A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static public B second(Pair p) {
return p == null ? null : p.b;
}
static public B second(T3 t) {
return t == null ? null : t.b;
}
static public A second(Producer p) {
if (p == null)
return null;
if (p.next() == null)
return null;
return p.next();
}
static public char second(String s) {
return charAt(s, 1);
}
static public B second(Either e) {
return e == null ? null : e.bOpt();
}
static public A third(List l) {
return _get(l, 2);
}
static public A third(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) {
if (!it.hasNext())
return null;
it.next();
}
return it.hasNext() ? it.next() : null;
}
static public A third(Producer p) {
if (p == null)
return null;
for (int _repeat_1 = 0; _repeat_1 < 2; _repeat_1++) {
if (p.next() == null)
return null;
}
return p.next();
}
static public A third(A[] bla) {
return bla == null || bla.length <= 2 ? null : bla[2];
}
static public C third(T3 t) {
return t == null ? null : t.c;
}
static public VF1 runnableToVF1(final Runnable r) {
return r == null ? null : new VF1 () {
public void get(A a) {
try {
r.run();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "r.run()";
}
};
}
static public boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
int n = s.length();
if (y < x)
y = x;
if (y > n)
y = n;
if (x >= y)
return "";
return s.substring(x, y);
}
static public String substring(String s, IntRange r) {
return r == null ? null : substring(s, r.start, r.end);
}
static public String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static public String jextract(String pat, String s) {
return jextract(pat, javaTok(s));
}
static public String jextract(String pat, List tok) {
List tokpat = javaTok(pat);
jfind_preprocess(tokpat);
int i = jfind(tok, tokpat);
if (i < 0)
return null;
int j = i + l(tokpat) - 2;
return joinSubList(tok, i, j);
}
static public Class __javax;
static public Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void __setJavaX(Class j) {
__javax = j;
_onJavaXSet();
}
static public Map synchroMap() {
return synchroHashMap();
}
static public Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static public TreeMap caseInsensitiveMap() {
return new TreeMap(caseInsensitiveComparator());
}
static public double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o instanceof String)
return parseDouble((String) o);
if (o == null)
return 0.0;
throw fail(o);
}
static public ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static public ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
static public String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static public String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static public String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static public String getStackTrace(String msg) {
return getStackTrace_noRecord(new Throwable(msg));
}
static public Set _registerAutoCloseable_set = synchroHashSet();
static public void _registerAutoCloseable(AutoCloseable c) {
addIfNotNull(_registerAutoCloseable_set, c);
}
static public void cleanMeUp__registerAutoCloseable() {
closeAutoCloseables(getAndClearList(_registerAutoCloseable_set));
}
static public HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
static public JTabbedPane fillJTabs(final JTabbedPane tabs, final Object... _x) {
if (tabs == null)
return null;
clearTabs(tabs);
Object[] x = flattenArray2(_x);
int idx = 0;
if (get(x, 0) instanceof Integer) {
idx = asInt(get(x, 0));
x = dropFirst(x);
if (empty(x)) {
x = arrayrep(null, idx);
idx = 0;
}
}
int n = 0;
for (int i = 0; i < l(x); i++) {
++n;
if (isComponentOrSwingable(x[i]))
addTab(tabs, "Tab " + n, wrap(x[i]));
else {
String name = str(or(x[i], "Tab " + n));
Component c;
if (isComponentOrSwingable(get(x, i + 1)))
c = wrap(get(x, ++i));
else
c = new JPanel();
addTab(tabs, name, wrap(c));
}
}
if (idx != 0)
tabs.setSelectedIndex(min(tabs.getTabCount() - 1, idx));
return tabs;
}
static public A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static public double quantizeToNLevelsBetweenZeroAndOne_stretch(int n, double x) {
x = clampZeroToOne(x);
return doubleRatio(min(n - 1, floor(x * n)), n - 1);
}
static public JPanel westAndCenter(final Component w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.WEST, wrap(w));
panel.add(BorderLayout.CENTER, wrap(c));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST...";
}
});
}
static public JPanel westAndCenterWithMargin(Component w, Component c) {
return westAndCenter(withRightMargin(w), c);
}
static public JPanel westAndCenterWithMargin(int margin, Component w, Component c) {
return westAndCenter(withRightMargin(margin, w), c);
}
static public String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
static public String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
static public String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return l.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret l.getText();";
}
});
}
static public String getText(final JComboBox cb) {
if (cb == null)
return null;
if (isEditableComboBox(cb))
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
static public JComboBox selectItem(A item, 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(JComboBox cb, A 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 A centerTextField(A tf) {
tf.setHorizontalAlignment(JTextField.CENTER);
return tf;
}
static public Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keys(Object map) {
return keys((Map) map);
}
static public Set keys(MultiSet ms) {
return ms.keySet();
}
static public Set keys(MultiMap mm) {
return mm.keySet();
}
static public ButtonGroup jradiobuttons(Collection strings) {
return selectFirstRadioButton(jUnselectedRadioButtons(strings));
}
static public ButtonGroup jradiobuttons(String... strings) {
return jradiobuttons(asList(strings));
}
static public int selectedButtonIdx(ButtonGroup g) {
List l = buttonsInGroup(g);
for (int i = 0; i < l(l); i++) if (l.get(i).isSelected())
return i;
return -1;
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static public JPanel jpanel(LayoutManager layout) {
return swingNu(JPanel.class, layout);
}
static public JPanel jpanel() {
return swingNu(JPanel.class);
}
static public String humanizeLabel(String s) {
return humanizeFormLabel(s);
}
static public JSpinner dm_spinner(String field, int min, int max) {
return liveValueSpinner(dm_fieldLiveValue(field), min, max);
}
static public Object vm_generalMap_set(Object key, Object value) {
return vm_generalMap_put(key, value);
}
static public int indexOfIC(List a, String b) {
return indexOfIgnoreCase(a, b);
}
static public int indexOfIC(List a, String b, int i) {
return indexOfIgnoreCase(a, b, i);
}
static public int indexOfIC(String[] a, String b) {
return indexOfIC(a, b, 0);
}
static public int indexOfIC(String[] a, String b, int i) {
return indexOfIgnoreCase(a, b, i);
}
static public int indexOfIC(String a, String b) {
return indexOfIgnoreCase(a, b);
}
static public int indexOfIC(String a, String b, int i) {
return indexOfIgnoreCase(a, b, i);
}
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 boolean containsIgnoreCase(Collection l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
static public boolean containsIgnoreCase(String[] l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
static public boolean containsIgnoreCase(String s, char c) {
return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}
static public boolean containsIgnoreCase(String a, String b) {
return indexOfIgnoreCase(a, b) >= 0;
}
static public Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
static public String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
static public String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static public String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static public String formatSnippetID(long id) {
return "#" + id;
}
static public Class getMainClass() {
return mc();
}
static public Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
ClassLoader cl = (o instanceof Class ? (Class) o : o.getClass()).getClassLoader();
if (cl == null)
return null;
String name = mainClassNameForClassLoader(cl);
return loadClassFromClassLoader_orNull(cl, name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] hexToBytes(String s) {
if (odd(l(s)))
throw fail("Hex string has odd length: " + quote(shorten(10, s)));
int n = l(s) / 2;
byte[] bytes = new byte[n];
for (int i = 0; i < n; i++) {
int a = parseHexChar(s.charAt(i * 2));
int b = parseHexChar(s.charAt(i * 2 + 1));
if (a < 0 || b < 0)
throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s));
bytes[i] = (byte) ((a << 4) | b);
}
return bytes;
}
static public PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static public Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x))
return true;
return false;
}
static public boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m))
return true;
return false;
}
static public boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static public String hostNameFromURL(String url) {
try {
return empty(url) ? null : new URL(url).getHost();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public int[] emptyIntArray_a = new int[0];
static public int[] emptyIntArray() {
return emptyIntArray_a;
}
static public char[] emptyCharArray = new char[0];
static public char[] emptyCharArray() {
return emptyCharArray;
}
static public double[] emptyDoubleArray = new double[0];
static public double[] emptyDoubleArray() {
return emptyDoubleArray;
}
static public Map emptyMap() {
return new HashMap();
}
static public Object[] emptyObjectArray_a = new Object[0];
static public Object[] emptyObjectArray() {
return emptyObjectArray_a;
}
static public int max(int a, int b) {
return Math.max(a, b);
}
static public int max(int a, int b, int c) {
return max(max(a, b), c);
}
static public long max(int a, long b) {
return Math.max((long) a, b);
}
static public long max(long a, long b) {
return Math.max(a, b);
}
static public double max(int a, double b) {
return Math.max((double) a, b);
}
static public float max(float a, float b) {
return Math.max(a, b);
}
static public double max(double a, double b) {
return Math.max(a, b);
}
static public int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static public double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
static public short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
static public int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
static public > A max(A a, A b) {
return cmp(a, b) >= 0 ? a : b;
}
static public Object[] expandParams(Class c, Object[] params) {
if (l(params) == 1)
params = new Object[] { singleFieldName(c), params[0] };
else
warnIfOddCount(params);
return params;
}
static public Object[] dropEntryFromParams(Object[] params, int i) {
int n = l(params);
if (i < 0 || i >= n)
return params;
if (n == 2)
return null;
Object[] p = new Object[n - 2];
System.arraycopy(params, 0, p, 0, i);
System.arraycopy(params, i + 2, p, i, n - i - 2);
return p;
}
static public boolean checkConceptFields(Concept x, Object... data) {
for (int i = 0; i < l(data); i += 2) if (neq(cget(x, (String) data[i]), deref(data[i + 1])))
return false;
return true;
}
static public List filterConcepts(List list, Object... params) {
if (empty(params))
return list;
List l = new ArrayList();
for (A x : list) if (checkConceptFields(x, params))
l.add(x);
return l;
}
static public String getType(Object o) {
return getClassName(o);
}
static public long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static public long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static public Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
static public String unnullForIteration(String s) {
return s == null ? "" : s;
}
static public Collection unnullForIteration(Collection l) {
return l == null ? immutableEmptyList() : l;
}
static public List unnullForIteration(List l) {
return l == null ? immutableEmptyList() : l;
}
static public int[] unnullForIteration(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnullForIteration(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnullForIteration(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public short[] unnullForIteration(short[] l) {
return l == null ? emptyShortArray() : l;
}
static public Map unnullForIteration(Map l) {
return l == null ? immutableEmptyMap() : l;
}
static public Iterable unnullForIteration(Iterable i) {
return i == null ? immutableEmptyList() : i;
}
static public A[] unnullForIteration(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnullForIteration(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnullForIteration(Pt p) {
return p == null ? new Pt() : p;
}
static public Pair unnullForIteration(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public long unnullForIteration(Long l) {
return l == null ? 0L : l;
}
static public Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() {
public void run() {
try {
_inheritThreadInfo(info);
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_inheritThreadInfo(info); callF(r);";
}
};
}
static public A setHorizontalAlignment(final int pos, final A a) {
swingCall(a, "setHorizontalAlignment", pos);
return a;
}
static public A setHorizontalAlignment(final int pos, final A a) {
swingCall(a, "setHorizontalAlignment", pos);
return a;
}
static public A setHorizontalAlignment(final int pos, final A a) {
swingCall(a, "setHorizontalAlignment", pos);
return a;
}
static public JLabel jLabel(String text) {
return jlabel(text);
}
static public JLabel jLabel() {
return jlabel();
}
static public JLabel jimage(Image img) {
return jImageLabel(img);
}
static public JLabel jimage(String imageID) {
return jImageLabel(imageID);
}
static public BufferedImage scaleImage_bilinear(BufferedImage before, double scaleX) {
return scaleImage_bilinear(before, scaleX, scaleX);
}
static public BufferedImage scaleImage_bilinear(BufferedImage before, double scaleX, double scaleY) {
return scaleImageWithOp(before, scaleX, scaleY, AffineTransformOp.TYPE_BILINEAR);
}
static public BufferedImage scaleImage_bilinear(double scale, BufferedImage before) {
return scaleImage_bilinear(before, scale);
}
static public boolean loadBufferedImage_useImageCache = true;
static public BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) {
try {
ping();
if (snippetIDOrURLOrFile == null)
return null;
if (isURL(snippetIDOrURLOrFile))
return imageIO_readURL(snippetIDOrURLOrFile);
if (isAbsolutePath(snippetIDOrURLOrFile))
return loadBufferedImage(new File(snippetIDOrURLOrFile));
if (!isSnippetID(snippetIDOrURLOrFile))
throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile);
String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return loadBufferedImage(rl.loadLibrary(snippetID));
File dir = imageSnippetsCacheDir();
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
try {
return ImageIO.read(file);
} catch (Throwable e) {
e.printStackTrace();
}
}
String imageURL = snippetImageURL_http(snippetID);
print("Loading image: " + imageURL);
BufferedImage image = imageIO_readURL(imageURL);
if (loadBufferedImage_useImageCache) {
File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
ImageIO.write(image, "png", tempFile);
tempFile.renameTo(new File(dir, snippetID + ".png"));
}
return image;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public BufferedImage loadBufferedImage(File file) {
return loadBufferedImageFile(file);
}
static public Object rcall(String method, Object o, Object... args) {
return call_withVarargs(o, method, args);
}
static public Runnable _topLevelErrorHandling(Runnable r) {
if (r == null)
return null;
Object info = _threadInfo();
Object mod = dm_current_generic();
if (info == null && mod == null)
return r;
return new Runnable() {
public void run() {
try {
AutoCloseable __1 = (AutoCloseable) (rcall("enter", mod));
try {
_threadInheritInfo(info);
r.run();
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp (AutoCloseable) rcall enter(mod);\r\n _threadInheritInfo(info);\r\n r....";
}
};
}
static public WeakReference weakRef(A a) {
return newWeakReference(a);
}
static public String getComputerID_quick() {
return computerID();
}
public static File mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) {
dir.mkdirs();
if (!dir.isDirectory())
if (dir.isFile())
throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
else
throw fail("Unknown IO exception during mkdirs of " + f2s(file));
}
return file;
}
public static String mkdirsForFile(String path) {
mkdirsForFile(new File(path));
return path;
}
static public void _registerIO(Object object, String path, boolean opened) {
}
static public int roundDownTo(int n, int x) {
return x / n * n;
}
static public long roundDownTo(long n, long x) {
return x / n * n;
}
static public boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static public int strL(String s) {
return s == null ? 0 : s.length();
}
static public int listL(Collection l) {
return l == null ? 0 : l.size();
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public void pcallFAll_minimalExceptionHandling(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
ping();
pcallF_minimalExceptionHandling(f, args);
}
}
static public void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) {
while (it.hasNext()) {
ping();
pcallF_minimalExceptionHandling(it.next(), args);
}
}
static public Set vm_busListeners_live_cache;
static public Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
static public Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static public Object unstructure(String text) {
return unstructure(text, false);
}
static public Object unstructure(String text, boolean allDynamic) {
return unstructure(text, allDynamic, null);
}
static public Object unstructure(String text, IF1 classFinder) {
return unstructure(text, false, classFinder);
}
static public int structure_internStringsLongerThan = 50;
static public int unstructure_unquoteBufSize = 100;
static public int unstructure_tokrefs;
abstract static public class unstructure_Receiver {
abstract public void set(Object o);
}
static public Object unstructure(String text, boolean allDynamic, Object classFinder) {
if (text == null)
return null;
return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
}
static public Object unstructure_reader(BufferedReader reader) {
return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
}
static public Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object _classFinder) {
final boolean debug = unstructure_debug;
final class X {
public int i = -1;
final public Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();
public String mcDollar = actualMCDollar();
public HashMap refs = new HashMap();
public HashMap tokrefs = new HashMap();
public HashSet concepts = new HashSet();
public HashMap classesMap = new HashMap();
public List stack = new ArrayList();
public Map baseClassMap = new HashMap();
public HashMap innerClassConstructors = new HashMap();
public String curT;
public char[] unquoteBuf = new char[unstructure_unquoteBufSize];
public X() {
try {
Class mc = (Class) (callF(_classFinder, ""));
if (mc != null)
mcDollar = mc.getName() + "$";
} catch (Throwable __e) {
printStackTrace(__e);
}
}
public Class findAClass(String fullClassName) {
try {
return classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
} catch (Throwable __e) {
return null;
}
}
public String unquote(String s) {
return unquoteUsingCharArray(s, unquoteBuf);
}
public String t() {
return curT;
}
public String tpp() {
String t = curT;
consume();
return t;
}
public void parse(final unstructure_Receiver out) {
String t = t();
int refID;
if (structure_isMarker(t, 0, l(t))) {
refID = parseInt(t.substring(1));
consume();
} else
refID = -1;
final int tokIndex = i;
parse_inner(refID, tokIndex, new unstructure_Receiver() {
public void set(Object o) {
if (refID >= 0)
refs.put(refID, o);
if (o != null)
tokrefs.put(tokIndex, o);
out.set(o);
}
});
}
public void parse_inner(int refID, int tokIndex, unstructure_Receiver out) {
String t = t();
String cname = t;
Class c = classesMap.get(cname);
if (c == null) {
if (t.startsWith("\"")) {
String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
out.set(s);
return;
}
if (t.startsWith("'")) {
out.set(unquoteCharacter(tpp()));
return;
}
if (t.equals("bigint")) {
out.set(parseBigInt());
return;
}
if (t.equals("d")) {
out.set(parseDouble());
return;
}
if (t.equals("fl")) {
out.set(parseFloat());
return;
}
if (t.equals("sh")) {
consume();
t = tpp();
if (t.equals("-")) {
t = tpp();
out.set((short) (-parseInt(t)));
return;
}
out.set((short) parseInt(t));
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("false") || t.equals("f")) {
consume();
out.set(false);
return;
}
if (t.equals("true") || t.equals("t")) {
consume();
out.set(true);
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("File")) {
consume();
File f = new File(unquote(tpp()));
out.set(f);
return;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
warn("unsatisfied back reference " + ref);
out.set(o);
return;
}
if (t.startsWith("t") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = tokrefs.get(ref);
if (o == null)
warn("unsatisfied token reference " + ref + " at " + tokIndex);
out.set(o);
return;
}
if (t.equals("hashset")) {
parseHashSet(out);
return;
}
if (t.equals("lhs")) {
parseLinkedHashSet(out);
return;
}
if (t.equals("treeset")) {
parseTreeSet(out);
return;
}
if (t.equals("ciset")) {
parseCISet(out);
return;
}
if (eqOneOf(t, "hashmap", "hm")) {
consume();
parseMap(new HashMap(), out);
return;
}
if (t.equals("lhm")) {
consume();
parseMap(new LinkedHashMap(), out);
return;
}
if (t.equals("tm")) {
consume();
parseMap(new TreeMap(), out);
return;
}
if (t.equals("cimap")) {
consume();
parseMap(ciMap(), out);
return;
}
if (t.equals("ll")) {
consume();
LinkedList l = new LinkedList();
if (refID >= 0)
refs.put(refID, l);
{
parseList(l, out);
return;
}
}
if (t.equals("syncLL")) {
consume();
{
parseList(synchroLinkedList(), out);
return;
}
}
if (t.equals("sync")) {
consume();
{
parse(new unstructure_Receiver() {
public void set(Object value) {
if (value instanceof Map) {
if (value instanceof NavigableMap) {
out.set(synchroNavigableMap((NavigableMap) value));
return;
}
if (value instanceof SortedMap) {
out.set(synchroSortedMap((SortedMap) value));
return;
}
{
out.set(synchroMap((Map) value));
return;
}
} else {
out.set(synchroList((List) value));
return;
}
}
});
return;
}
}
if (t.equals("{")) {
parseMap(out);
return;
}
if (t.equals("[")) {
ArrayList l = new ArrayList();
if (refID >= 0)
refs.put(refID, l);
this.parseList(l, out);
return;
}
if (t.equals("bitset")) {
parseBitSet(out);
return;
}
if (t.equals("array") || t.equals("intarray") || t.equals("dblarray")) {
parseArray(out);
return;
}
if (t.equals("ba")) {
consume();
String hex = unquote(tpp());
out.set(hexToBytes(hex));
return;
}
if (t.equals("boolarray")) {
consume();
int n = parseInt(tpp());
String hex = unquote(tpp());
out.set(boolArrayFromBytes(hexToBytes(hex), n));
return;
}
if (t.equals("class")) {
out.set(parseClass());
return;
}
if (t.equals("l")) {
parseLisp(out);
return;
}
if (t.equals("null")) {
consume();
out.set(null);
return;
}
if (eq(t, "c")) {
consume();
t = t();
assertTrue(isJavaIdentifier(t));
concepts.add(t);
}
if (eq(t, "cu")) {
consume();
t = tpp();
assertTrue(isJavaIdentifier(t));
String fullClassName = mcDollar + t;
Class _c = findAClass(fullClassName);
if (_c == null)
throw fail("Class not found: " + fullClassName);
parse(new unstructure_Receiver() {
public void set(Object value) {
out.set(call(_c, "_deserialize", value));
}
});
return;
}
}
if (eq(t, "j")) {
consume();
out.set(parseJava());
return;
}
if (eq(t, "bc")) {
consume();
String c1 = tpp();
String c2 = tpp();
baseClassMap.put(c1, c2);
{
parse_inner(refID, i, out);
return;
}
}
if (c == null && !isJavaIdentifier(t))
throw new RuntimeException("Unknown token " + (i + 1) + ": " + quote(t));
consume();
String className, fullClassName;
if (eq(t(), ".")) {
consume();
className = fullClassName = t + "." + assertIdentifier(tpp());
} else {
className = t;
fullClassName = mcDollar + t;
}
if (c == null && !allDynamic) {
c = findAClass(fullClassName);
classesMap.put(className, c);
}
if (c == null && !allDynamic) {
Set seen = new HashSet();
String parent = className;
while (true) {
String baseName = baseClassMap.get(parent);
if (baseName == null)
break;
if (!seen.add(baseName))
throw fail("Cyclic superclass info: " + baseName);
c = findAClass(mcDollar + baseName);
if (c == null)
print("Base class " + baseName + " of " + parent + " doesn't exist either");
else if (isAbstract(c))
print("Can't instantiate abstract base class: " + c);
else {
printVars_str("Reverting to base class", "className", className, "baseName", baseName, "c", c);
classesMap.put(className, c);
break;
}
parent = baseName;
}
}
boolean hasBracket = eq(t(), "(");
if (hasBracket)
consume();
boolean hasOuter = hasBracket && startsWith(t(), "this$");
DynamicObject dO = null;
Object o = null;
final String thingName = t;
if (c != null) {
if (hasOuter)
try {
Constructor ctor = innerClassConstructors.get(c);
if (ctor == null)
innerClassConstructors.put(c, ctor = nuStubInnerObject_findConstructor(c, classFinder));
o = ctor.newInstance(new Object[] { null });
} catch (Exception e) {
print("Error deserializing " + c + ": " + e);
o = nuEmptyObject(c);
}
else
o = nuEmptyObject(c);
if (o instanceof DynamicObject)
dO = (DynamicObject) o;
} else {
if (concepts.contains(t) && (c = findAClass(mcDollar + "Concept")) != null)
o = dO = (DynamicObject) nuEmptyObject(c);
else
dO = new DynamicObject();
dO.className = className;
}
if (refID >= 0)
refs.put(refID, o != null ? o : dO);
tokrefs.put(tokIndex, o != null ? o : dO);
HashMap fields = new HashMap();
Object _o = o;
DynamicObject _dO = dO;
if (hasBracket) {
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), ","))
consume();
if (eq(t(), ")")) {
consume(")");
objRead(_o, _dO, fields, hasOuter);
out.set(_o != null ? _o : _dO);
} else {
final String key = unquote(tpp());
String t = tpp();
if (!eq(t, "="))
throw fail("= expected, got " + t + " after " + quote(key) + " in object " + thingName);
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object value) {
fields.put(key, value);
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef unstructure_debug\r\n print(\"in object values, token: \" + t())...";
}
});
} else {
objRead(o, dO, fields, hasOuter);
out.set(o != null ? o : dO);
}
}
public void objRead(Object o, DynamicObject dO, Map fields, boolean hasOuter) {
Object outer = fields.get("this$0");
if (outer != null)
fields.put("this$1", outer);
else {
outer = fields.get("this$1");
if (outer != null)
fields.put("this$0", outer);
}
if (o != null) {
if (dO != null) {
setOptAllDyn_pcall(dO, fields);
} else {
setOptAll_pcall(o, fields);
}
if (hasOuter)
fixOuterRefs(o);
} else
for (Map.Entry e : fields.entrySet()) setDynObjectValue(dO, intern(e.getKey()), e.getValue());
if (o != null)
pcallOpt_noArgs(o, "_doneLoading");
}
public void parseSet(final Set set, final unstructure_Receiver out) {
this.parseList(new ArrayList(), new unstructure_Receiver() {
public void set(Object o) {
set.addAll((List) o);
out.set(set);
}
});
}
public void parseLisp(final unstructure_Receiver out) {
throw fail("class Lisp not included");
}
public void parseBitSet(final unstructure_Receiver out) {
consume("bitset");
consume("{");
final BitSet bs = new BitSet();
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
out.set(bs);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
bs.set((Integer) o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n ...";
}
});
}
public void parseList(final List list, final unstructure_Receiver out) {
tokrefs.put(i, list);
consume("[");
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "]")) {
consume();
out.set(list);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"]\")) {\r\n consume();\r\n ifdef unstructure_debug\r...";
}
});
}
public void parseArray(unstructure_Receiver out) {
String _type = tpp();
int dims;
if (eq(t(), "S")) {
_type = "S";
consume();
}
if (eq(t(), "/")) {
consume();
dims = parseInt(tpp());
} else
dims = 1;
consume("{");
List list = new ArrayList();
String type = _type;
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
if (dims > 1) {
Class atype;
if (type.equals("intarray"))
atype = int.class;
else if (type.equals("S"))
atype = String.class;
else
throw todo("multi-dimensional arrays of other types");
out.set(list.toArray((Object[]) newMultiDimensionalOuterArray(atype, dims, l(list))));
} else
out.set(type.equals("intarray") ? toIntArray(list) : type.equals("dblarray") ? toDoubleArray(list) : type.equals("S") ? toStringArray(list) : list.toArray());
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n if (dims > 1) {\r\n ...";
}
});
}
public Object parseClass() {
consume("class");
consume("(");
String name = unquote(tpp());
consume(")");
Class c = allDynamic ? null : findAClass(name);
if (c != null)
return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
name = dropPrefix(mcDollar, name);
dO.fieldValues.put("name", name);
return dO;
}
public Object parseBigInt() {
consume("bigint");
consume("(");
String val = tpp();
if (eq(val, "-"))
val = "-" + tpp();
consume(")");
return new BigInteger(val);
}
public Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tpp());
consume(")");
return Double.parseDouble(val);
}
public Object parseFloat() {
consume("fl");
String val;
if (eq(t(), "(")) {
consume("(");
val = unquote(tpp());
consume(")");
} else {
val = unquote(tpp());
}
return Float.parseFloat(val);
}
public void parseHashSet(unstructure_Receiver out) {
consume("hashset");
parseSet(new HashSet(), out);
}
public void parseLinkedHashSet(unstructure_Receiver out) {
consume("lhs");
parseSet(new LinkedHashSet(), out);
}
public void parseTreeSet(unstructure_Receiver out) {
consume("treeset");
parseSet(new TreeSet(), out);
}
public void parseCISet(unstructure_Receiver out) {
consume("ciset");
parseSet(ciSet(), out);
}
public void parseMap(unstructure_Receiver out) {
parseMap(new TreeMap(), out);
}
public Object parseJava() {
String j = unquote(tpp());
Matches m = new Matches();
if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
else {
warn("Unknown Java object: " + j);
return null;
}
}
public void parseMap(final Map map, final unstructure_Receiver out) {
consume("{");
stack.add(new Runnable() {
public boolean v = false;
public Object key;
public void run() {
if (v) {
v = false;
stack.add(this);
if (!eq(tpp(), "="))
throw fail("= expected, got " + t() + " in map of size " + l(map));
parse(new unstructure_Receiver() {
public void set(Object value) {
map.put(key, value);
if (eq(t(), ","))
consume();
}
});
} else {
if (eq(t(), "}")) {
consume("}");
out.set(map);
} else {
v = true;
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
key = o;
}
});
}
}
}
});
}
public void consume() {
curT = tok.next();
++i;
}
public void consume(String s) {
if (!eq(t(), s)) {
throw fail(quote(s) + " expected, got " + quote(t()));
}
consume();
}
public void parse_initial(unstructure_Receiver out) {
consume();
parse(out);
while (nempty(stack)) popLast(stack).run();
}
}
ThreadLocal tlLoading = dynamicObjectIsLoading_threadLocal();
Boolean b = tlLoading.get();
tlLoading.set(true);
try {
final Var v = new Var();
X x = new X();
x.parse_initial(new unstructure_Receiver() {
public void set(Object o) {
v.set(o);
}
});
unstructure_tokrefs = x.tokrefs.size();
return v.get();
} finally {
tlLoading.set(b);
}
}
static public boolean unstructure_debug = false;
static public Set synchronizedSet() {
return synchroHashSet();
}
static public Set synchronizedSet(Set set) {
return Collections.synchronizedSet(set);
}
static public Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public char charAt(String s, int i) {
return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
}
static public 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 boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static public int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
static public int jfind(String s, String in) {
return jfind(javaTok(s), in);
}
static public int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static public int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, null);
}
static public int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, String in, ITokCondition condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, int startIndex, String in, ITokCondition condition) {
return jfind(tok, startIndex, in, (Object) condition);
}
static public int jfind(List tok, int startIdx, String in, Object condition) {
return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
}
static public int jfind(List tok, List tokin) {
return jfind(tok, 1, tokin);
}
static public int jfind(List tok, int startIdx, List tokin) {
return jfind(tok, startIdx, tokin, null);
}
static public int jfind(List tok, int startIdx, String[] tokinC, Object condition) {
return findCodeTokens(tok, startIdx, false, tokinC, condition);
}
static public int jfind(List tok, int startIdx, List tokin, Object condition) {
return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
}
static public List jfind_preprocess(List tok) {
for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
return tok;
}
static public void _onJavaXSet() {
}
static public Map synchroHashMap() {
return synchronizedMap(new HashMap());
}
static public double parseDouble(String s) {
return empty(s) ? 0.0 : Double.parseDouble(s);
}
static public Object collectionMutex(List l) {
return l;
}
static public Object collectionMutex(Object o) {
if (o instanceof List)
return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
static public Set synchroHashSet() {
return synchronizedSet(new HashSet ());
}
static public void closeAutoCloseables(Collection l) {
if (l != null)
for (AutoCloseable c : l) {
try {
c.close();
} catch (Throwable __e) {
printStackTrace(__e);
}
}
}
static public void clearTabs(final JTabbedPane tabs) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
tabs.removeAll();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tabs.removeAll();";
}
});
}
}
static public int asInt(Object o) {
return toInt(o);
}
static public Object[] arrayrep(Object a, int n) {
return asArray(repeat(a, n));
}
static public boolean isComponentOrSwingable(Object o) {
if (o instanceof Swingable)
return true;
return o instanceof Component;
}
static public void addTab(JTabbedPane tabs, String title, Component c) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
tabs.add(title, wrap(c));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tabs.add(title, wrap(c));";
}
});
}
}
static public void addTab(JTabbedPane tabs, String title, Swingable c) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
tabs.add(title, wrap(c));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tabs.add(title, wrap(c));";
}
});
}
}
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 if (swingable instanceof Swingable)
c = componentToJComponent(((Swingable) swingable).visualize());
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 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 float clampZeroToOne(float x) {
return x < 0 ? 0 : x > 1 ? 1 : x;
}
static public double clampZeroToOne(double x) {
return x < 0 ? 0 : x > 1 ? 1 : x;
}
static public double floor(double d) {
return Math.floor(d);
}
static public int withRightMargin_defaultWidth = 6;
static public JPanel withRightMargin(Component c) {
return withRightMargin(withRightMargin_defaultWidth, c);
}
static public JPanel withRightMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = marginPanel();
p.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, w));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = marginPanel();\r\n p.setBorder(BorderFactory.createEmptyBorder(0,...";
}
});
}
static public 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 int jlist_indexOf(JList list, A item) {
return swing(new F0() {
public Integer get() {
try {
ListModel model = list.getModel();
int n = model.getSize();
for (int i = 0; i < n; i++) if (eq(model.getElementAt(i), item))
return i;
return -1;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ListModel model = list.getModel();\r\n int n = model.getSize();\r\n for ...";
}
});
}
static public ButtonGroup selectFirstRadioButton(ButtonGroup g) {
selectRadioButton(first(buttonsInGroup(g)));
return g;
}
static public ButtonGroup jUnselectedRadioButtons(Collection strings) {
final ButtonGroup g = new ButtonGroup();
for (String s : unnull(strings)) jradiobutton(s, g);
return g;
}
static public JSpinner liveValueSpinner(final SimpleLiveValue lv, int min, int max) {
final JSpinner spinner = jSpinner(lv.get(), min, max);
onChange(spinner, new Runnable() {
public void run() {
try {
lv.set(intFromSpinner(spinner));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "lv.set(intFromSpinner(spinner))";
}
});
lv.onChange(new Runnable() {
public void run() {
try {
setSpinnerValue(spinner, lv.get());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "setSpinnerValue(spinner, lv!)";
}
});
return spinner;
}
static public int indexOfIgnoreCase(List a, String b) {
return indexOfIgnoreCase(a, b, 0);
}
static public int indexOfIgnoreCase(List a, String b, int i) {
int n = a == null ? 0 : a.size();
for (; i < n; i++) if (eqic(a.get(i), b))
return i;
return -1;
}
static public int indexOfIgnoreCase(String[] a, String b) {
return indexOfIgnoreCase(a, b, 0);
}
static public int indexOfIgnoreCase(String[] a, String b, int i) {
int n = a == null ? 0 : a.length;
for (; i < n; i++) if (eqic(a[i], b))
return i;
return -1;
}
static public int indexOfIgnoreCase(String a, String b) {
return indexOfIgnoreCase_manual(a, b);
}
static public int indexOfIgnoreCase(String a, String b, int i) {
return indexOfIgnoreCase_manual(a, b, i);
}
static public boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static public long parseLong(String s) {
if (empty(s))
return 0;
return Long.parseLong(dropSuffix("L", s));
}
static public long parseLong(Object s) {
return Long.parseLong((String) s);
}
static public String mainClassNameForClassLoader(ClassLoader cl) {
return or((String) callOpt(cl, "mainClassName"), "main");
}
static public Class loadClassFromClassLoader_orNull(ClassLoader cl, String name) {
try {
return cl == null ? null : cl.loadClass(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public boolean odd(int i) {
return (i & 1) != 0;
}
static public boolean odd(long i) {
return (i & 1) != 0;
}
static public boolean odd(BigInteger i) {
return odd(toInt(i));
}
static public 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 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 int parseHexChar(char c) {
if (c >= '0' && c <= '9')
return charDiff(c, '0');
if (c >= 'a' && c <= 'f')
return charDiff(c, 'a') + 10;
if (c >= 'A' && c <= 'F')
return charDiff(c, 'A') + 10;
return -1;
}
static public boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
static public String theAGIBlueDomain() {
return "agi.blue";
}
static public int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static public int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(int a, int b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(long a, long b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(Object a, Object b) {
if (a == null)
return b == null ? 0 : -1;
if (b == null)
return 1;
return ((Comparable) a).compareTo(b);
}
static public String singleFieldName(Class c) {
Set l = listFields(c);
if (l(l) != 1)
throw fail("No single field found in " + c + " (have " + n(l(l), "fields") + ")");
return first(l);
}
static public Object deref(Object o) {
if (o instanceof IRef)
return ((IRef) o).get();
return o;
}
static public List immutableEmptyList() {
return Collections.emptyList();
}
static public short[] emptyShortArray = new short[0];
static public short[] emptyShortArray() {
return emptyShortArray;
}
static public Map immutableEmptyMap() {
return Collections.emptyMap();
}
static public Runnable asRunnable(Object o) {
return toRunnable(o);
}
static public void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static public Object swingCall(final Object o, final String method, final Object... args) {
return swing(new F0() {
public Object get() {
try {
return call(o, method, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret call(o, method, args);";
}
});
}
static public JLabel jImageLabel(Image img) {
return swingNu(JLabel.class, imageIcon(img));
}
static public JLabel jImageLabel(javax.swing.Icon icon) {
return swingNu(JLabel.class, icon);
}
static public JLabel jImageLabel(String imageID) {
return jImageLabel(imageIcon(imageID));
}
static public JLabel jImageLabel(String text, String imageID) {
final JLabel l = swingNu(JLabel.class, text, imageIcon(imageID), JLabel.CENTER);
{
swing(new Runnable() {
public void run() {
try {
l.setVerticalTextPosition(SwingConstants.BOTTOM);
l.setHorizontalTextPosition(SwingConstants.CENTER);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "l.setVerticalTextPosition(SwingConstants.BOTTOM);\r\n l.setHorizontalTextPos...";
}
});
}
return l;
}
static public BufferedImage scaleImageWithOp(BufferedImage before, double scaleX, int affineTransformOpType) {
return scaleImageWithOp(before, scaleX, scaleX, affineTransformOpType);
}
static public BufferedImage scaleImageWithOp(BufferedImage before, double scaleX, double scaleY, int affineTransformOpType) {
if (scaleX == 1 && scaleY == 1)
return before;
int w = before.getWidth();
int h = before.getHeight();
int neww = max(1, iround(w * scaleX)), newh = max(1, iround(h * scaleY));
BufferedImage after = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(scaleX, scaleY);
AffineTransformOp scaleOp = new AffineTransformOp(at, affineTransformOpType);
return scaleOp.filter(before, after);
}
static public boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
static public BufferedImage imageIO_readURL(String url) {
try {
return ImageIO.read(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isAbsolutePath(String s) {
return s != null && new File(s).isAbsolute();
}
static public boolean isAbsolutePath(File f) {
return f != null && f.isAbsolute();
}
static public IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
static public File imageSnippetsCacheDir() {
return javaxCachesDir("Image-Snippets");
}
static public String snippetImageURL_http(String snippetID) {
return snippetImageURL_http(snippetID, "png");
}
static public String snippetImageURL_http(String snippetID, String contentType) {
return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080");
}
static public BufferedImage loadBufferedImageFile(File file) {
try {
return isFile(file) ? ImageIO.read(file) : null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
static public String _computerID;
static public Lock computerID_lock = lock();
public static String computerID() {
if (_computerID == null) {
Lock __0 = computerID_lock;
lock(__0);
try {
if (_computerID != null)
return _computerID;
File file = computerIDFile();
_computerID = loadTextFile(file.getPath());
if (_computerID == null) {
_computerID = loadTextFile(userDir(".tinybrain/computer-id"));
if (_computerID == null)
_computerID = makeRandomID(12, new SecureRandom());
saveTextFile(file, _computerID);
}
} finally {
unlock(__0);
}
}
return _computerID;
}
static public Object pcallF_minimalExceptionHandling(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable e) {
System.out.println(getStackTrace(e));
_storeException(e);
}
return null;
}
static public Producer javaTokC_noMLS_iterator(final String s) {
return javaTokC_noMLS_iterator(s, 0);
}
static public Producer javaTokC_noMLS_iterator(final String s, final int startIndex) {
return new Producer() {
final public int l = s.length();
public int i = startIndex;
public String next() {
if (i >= l)
return null;
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;
}
i = j;
if (i >= l)
return null;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') {
++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)));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else
++j;
String t = quickSubstring(s, i, j);
i = j;
return t;
}
};
}
static public Producer javaTokC_noMLS_onReader(final BufferedReader r) {
final class X implements Producer {
public StringBuilder buf = new StringBuilder();
public char c, d, e = 'x';
public X() {
nc();
nc();
nc();
}
public void nc() {
try {
c = d;
d = e;
if (e == '\0')
return;
int i = r.read();
e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void ncSave() {
if (c != '\0') {
buf.append(c);
nc();
}
}
public String next() {
while (c != '\0') {
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
nc();
else if (c == '/' && d == '*') {
do nc(); while (c != '\0' && !(c == '*' && d == '/'));
nc();
nc();
} else if (c == '/' && d == '/') {
do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
} else
break;
}
if (c == '\0')
return null;
if (c == '\'' || c == '"') {
char opener = c;
ncSave();
while (c != '\0') {
if (c == opener || c == '\n') {
ncSave();
break;
} else if (c == '\\') {
ncSave();
ncSave();
} else
ncSave();
}
} else if (Character.isJavaIdentifierStart(c))
do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\'');
else if (Character.isDigit(c)) {
do ncSave(); while (Character.isDigit(c));
if (c == 'L')
ncSave();
} else
ncSave();
String t = buf.toString();
buf.setLength(0);
return t;
}
}
return new X();
}
static public String actualMCDollar() {
return actualMC().getName() + "$";
}
static public String unquoteUsingCharArray(String s, char[] buf) {
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();
if (l > buf.length)
return unquote(s);
int n = 0;
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++;
}
}
buf[n++] = (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);
char[] x = Character.toChars(code);
int lx = x.length;
for (int j = 0; j < lx; j++) buf[n++] = x[j];
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
buf[n++] = ch;
}
return new String(buf, 0, n);
}
}
return s;
}
static public boolean structure_isMarker(String s, int i, int j) {
if (i >= j)
return false;
if (s.charAt(i) != 'm')
return false;
++i;
while (i < j) {
char c = s.charAt(i);
if (c < '0' || c > '9')
return false;
++i;
}
return true;
}
static public String internIfLongerThan(String s, int l) {
return s == null ? null : l(s) >= l ? intern(s) : s;
}
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 char unquoteCharacter(String s) {
assertTrue(s.startsWith("'") && s.length() > 1);
return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length() - 1 : s.length()) + "\"").charAt(0);
}
static public BigInteger parseBigInt(String s) {
return new BigInteger(s);
}
static public float parseFloat(String s) {
return Float.parseFloat(s);
}
static public boolean isInteger(String s) {
int n = l(s);
if (n == 0)
return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n)
return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9')
return false;
++i;
}
return true;
}
static public boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
static public TreeMap ciMap() {
return caseInsensitiveMap();
}
static public List parseList(String s) {
return (List) safeUnstructure(s);
}
static public List synchroLinkedList() {
return Collections.synchronizedList(new LinkedList ());
}
static public NavigableMap synchroNavigableMap(NavigableMap map) {
return (NavigableMap) call(Collections.class, "synchronizedNavigableMap", map);
}
static public SortedMap synchroSortedMap(SortedMap map) {
return Collections.synchronizedSortedMap(map);
}
static public List synchroList() {
return synchroList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public boolean[] boolArrayFromBytes(byte[] a, int n) {
boolean[] b = new boolean[n];
int m = min(n, l(a) * 8);
for (int i = 0; i < m; i++) b[i] = (a[i / 8] & 1 << (i & 7)) != 0;
return b;
}
static public String assertIdentifier(String s) {
return assertIsIdentifier(s);
}
static public String assertIdentifier(String msg, String s) {
return assertIsIdentifier(msg, s);
}
static public boolean isAbstract(Class c) {
return (c.getModifiers() & Modifier.ABSTRACT) != 0;
}
static public boolean isAbstract(Method m) {
return (m.getModifiers() & Modifier.ABSTRACT) != 0;
}
static public void printVars_str(Object... params) {
print(renderVars_str(params));
}
static public Constructor nuStubInnerObject_findConstructor(Class c) {
return nuStubInnerObject_findConstructor(c, null);
}
static public Constructor nuStubInnerObject_findConstructor(Class c, Object classFinder) {
try {
Class outerType = getOuterClass(c, classFinder);
Constructor m = c.getDeclaredConstructor(outerType);
makeAccessible(m);
return m;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map nuEmptyObject_cache = newDangerousWeakHashMap();
static public A nuEmptyObject(Class c) {
try {
Constructor ctr;
synchronized (nuEmptyObject_cache) {
ctr = nuEmptyObject_cache.get(c);
if (ctr == null) {
nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
makeAccessible(ctr);
}
}
try {
return (A) ctr.newInstance();
} catch (InstantiationException e) {
if (empty(e.getMessage()))
if ((c.getModifiers() & Modifier.ABSTRACT) != 0)
throw fail("Can't instantiate abstract class " + className(c), e);
else
throw fail("Can't instantiate " + className(c), e);
else
throw rethrow(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuEmptyObject_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (m.getParameterTypes().length == 0)
return m;
throw fail("No default constructor declared in " + c.getName());
}
static public void setOptAllDyn_pcall(DynamicObject o, Map fields) {
if (fields == null || o == null)
return;
HashMap fieldMap = instanceFieldsMap(o);
for (Map.Entry e : fields.entrySet()) {
try {
String field = e.getKey();
Object val = e.getValue();
Field f = fieldMap.get(field);
if (f != null)
smartSet(f, o, val);
else {
dynamicObject_setRawFieldValue(o, intern(field), val);
}
} catch (Throwable __e) {
printStackTrace(__e);
}
}
}
static public void setOptAll_pcall(Object o, Map fields) {
if (fields == null)
return;
for (String field : keys(fields)) try {
setOpt(o, field, fields.get(field));
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
static public void setOptAll_pcall(Object o, Object... values) {
warnIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
try {
setOpt(o, field, value);
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
}
static public void fixOuterRefs(Object o) {
try {
if (o == null)
return;
Field[] l = thisDollarOneFields(o.getClass());
if (l.length <= 1)
return;
Object father = null;
for (Field f : l) {
father = f.get(o);
if (father != null)
break;
}
if (father == null)
return;
for (Field f : l) f.set(o, father);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void setDynObjectValue(DynamicObject o, String field, Object value) {
dynamicObject_setRawFieldValue(o, field, value);
}
static public String intern(String s) {
return fastIntern(s);
}
static public void pcallOpt_noArgs(Object o, String method) {
try {
callOpt_noArgs(o, method);
} catch (Throwable __e) {
printStackTrace(__e);
}
}
static public List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static public List subList(int startIndex, List l) {
return subList(l, startIndex);
}
static public List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static public List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex > endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return l.subList(startIndex, endIndex);
}
static public List subList(List l, IntRange r) {
return subList(l, r.start, r.end);
}
static public RuntimeException todo() {
throw new RuntimeException("TODO");
}
static public RuntimeException todo(Object msg) {
throw new RuntimeException("TODO: " + msg);
}
static public Object newMultiDimensionalOuterArray(Class elementType, int dimensions, int length) {
int[] dims = new int[dimensions];
dims[0] = length;
return Array.newInstance(elementType, dims);
}
static public int[] toIntArray(Collection l) {
int[] a = new int[l(l)];
int i = 0;
if (a.length != 0)
for (int x : l) a[i++] = x;
return a;
}
static public double[] toDoubleArray(Collection l) {
double[] a = new double[l(l)];
int i = 0;
if (a.length != 0)
for (double x : l) a[i++] = x;
return a;
}
static public double[] toDoubleArray(IntBuffer b) {
int n = l(b);
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = b.get(i);
return a;
}
static public String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++) a[i] = it.next();
return a;
}
static public String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
static public TreeSet ciSet() {
return caseInsensitiveSet();
}
static public boolean jmatch(String pat, String s) {
return jmatch(pat, s, null);
}
static public boolean jmatch(String pat, String s, Matches matches) {
if (s == null)
return false;
return jmatch(pat, javaTok(s), matches);
}
static public boolean jmatch(String pat, List toks) {
return jmatch(pat, toks, null);
}
static public boolean jmatch(String pat, List toks, Matches matches) {
List tokpat = javaTok(pat);
String[] m = match2(tokpat, toks);
if (m == null)
return false;
else {
if (matches != null)
matches.m = m;
return true;
}
}
static public Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static public boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static public A popLast(List l) {
return liftLast(l);
}
static public List popLast(int n, List l) {
return liftLast(n, l);
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
static public ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
static public Map synchronizedMap() {
return synchroMap();
}
static public Map synchronizedMap(Map map) {
return synchroMap(map);
}
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 _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
return c;
}
static public JComponent componentToJComponent(Component c) {
if (c instanceof JComponent)
return (JComponent) c;
if (c instanceof JFrame)
return ((JFrame) c).getRootPane();
if (c == null)
return null;
throw fail("boohoo " + getClassName(c));
}
static public JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JScrollPane(c);";
}
});
}
static public JPanel marginPanel() {
return jtransparent(borderLayoutPanel());
}
static public void scrollRowToVisible(JTable t, int rowIndex) {
int colIndex = 0;
if (!(t.getParent() instanceof JViewport))
return;
JViewport viewport = (JViewport) t.getParent();
Rectangle rect = t.getCellRect(rowIndex, colIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)) {
} else if (rect.x < viewRect.x) {
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)) {
} else if (rect.y < viewRect.y) {
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)) {
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x, y));
}
static public int listRowCount(JList list) {
return list == null ? 0 : swing(new F0() {
public Integer get() {
try {
return list.getModel().getSize();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret list.getModel().getSize();";
}
});
}
static public JRadioButton jradiobutton(String text, ButtonGroup group) {
return swing(new F0() {
public JRadioButton get() {
try {
JRadioButton rb = new JRadioButton(text);
if (group != null)
group.add(rb);
return rb;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JRadioButton rb = new JRadioButton(text);\r\n if (group != null) group.add(r...";
}
});
}
static public JRadioButton jradiobutton(ButtonGroup group, String text) {
return jradiobutton(text, group);
}
static public JRadioButton jradiobutton(ButtonGroup group, String text, boolean selected) {
var rb = jradiobutton(group, text);
if (selected)
selectRadioButton(rb);
return rb;
}
static public JSpinner jSpinner(final int value) {
return swing(new F0() {
public JSpinner get() {
try {
JSpinner s = new JSpinner();
s.setValue(value);
return jSpinnerCommitOnValidEdit(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new JSpinner s;\r\n s.setValue(value);\r\n ret jSpinnerCommitOnValidEdit(s);";
}
});
}
static public JSpinner jSpinner(final int value, final int min, final int max) {
return swing(new F0() {
public JSpinner get() {
try {
return jSpinnerCommitOnValidEdit(new JSpinner(new SpinnerNumberModel(value, min, max, 1)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret jSpinnerCommitOnValidEdit(new JSpinner(new SpinnerNumberModel(value, min,...";
}
});
}
static public int intFromSpinner(JSpinner s) {
return toInt(s.getValue());
}
static public void setSpinnerValue(final JSpinner s, final int value) {
if (s != null) {
swing(new Runnable() {
public void run() {
try {
s.setValue(value);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "s.setValue(value);";
}
});
}
}
static public int indexOfIgnoreCase_manual(String a, String b) {
return indexOfIgnoreCase_manual(a, b, 0);
}
static public int indexOfIgnoreCase_manual(String a, String b, int i) {
int la = strL(a), lb = strL(b);
if (la < lb)
return -1;
int n = la - lb;
loop: for (; i <= n; i++) {
for (int j = 0; j < lb; j++) {
char c1 = a.charAt(i + j), c2 = b.charAt(j);
if (!eqic(c1, c2))
continue loop;
}
return i;
}
return -1;
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
static public String dropSuffix(String suffix, String s) {
return nempty(suffix) && endsWith(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public CharSequence subCharSequence(CharSequence s, int x) {
return subCharSequence(s, x, s == null ? 0 : s.length());
}
static public CharSequence subCharSequence(CharSequence s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.subSequence(x, y);
}
static public int charDiff(char a, char b) {
return (int) a - (int) b;
}
static public int charDiff(String a, char b) {
return charDiff(stringToChar(a), b);
}
static public boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static public boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static public Set listFields(Object c) {
TreeSet fields = new TreeSet();
for (Field f : _getClass(c).getDeclaredFields()) fields.add(f.getName());
return fields;
}
static public int imageIcon_cacheSize = 10;
static public boolean imageIcon_verbose = false;
static public Map imageIcon_cache;
static public Lock imageIcon_lock = lock();
static public ThreadLocal imageIcon_fixGIF = new ThreadLocal();
static public ImageIcon imageIcon(String imageID) {
try {
if (imageID == null)
return null;
Lock __0 = imageIcon_lock;
lock(__0);
try {
if (imageIcon_cache == null)
imageIcon_cache = new MRUCache(imageIcon_cacheSize);
imageID = fsI(imageID);
ImageIcon ii = imageIcon_cache.get(imageID);
if (ii == null) {
if (imageIcon_verbose)
print("Loading image icon: " + imageID);
File f = loadBinarySnippet(imageID);
Boolean b = imageIcon_fixGIF.get();
if (!isFalse(b))
ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
else
ii = new ImageIcon(f.toURI().toURL());
} else
imageIcon_cache.remove(imageID);
imageIcon_cache.put(imageID, ii);
return ii;
} finally {
unlock(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ImageIcon imageIcon(File f) {
try {
return new ImageIcon(f.toURI().toURL());
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ImageIcon imageIcon(Image img) {
return new ImageIcon(img);
}
static public ImageIcon imageIcon(RGBImage img) {
return imageIcon(img.getBufferedImage());
}
static public A proxy(Class intrface, final Object target) {
if (target == null)
return null;
if (isInstance(intrface, target))
return (A) target;
return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new proxy_InvocationHandler(target));
}
static public A proxy(Object target, Class intrface) {
return proxy(intrface, target);
}
static public Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static public File javaxCachesDir_dir;
static public File javaxCachesDir() {
return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
static public File javaxCachesDir(String sub) {
return newFile(javaxCachesDir(), sub);
}
static public String snippetImageURL(long snippetID) {
return snippetImageURL(fsI(snippetID));
}
static public String snippetImageURL(String snippetID) {
return snippetImageURL(snippetID, "png");
}
static public String snippetImageURL(String snippetID, String contentType) {
if (snippetID == null || isURL(snippetID))
return snippetID;
long id = parseSnippetID(snippetID);
String url;
if (isImageServerSnippet(id))
url = imageServerLink(id);
else
url = "https://botcompany.de/img/" + id;
return url;
}
static final public Map callOpt_cache = newDangerousWeakHashMap();
static public Object callOpt_cached(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null)
return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public _MethodCache callOpt_getCache(Class c) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
static public Object invokeMethod(Method m, Object o, Object... args) {
try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static public Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = args.length;
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs - n);
arraycopy(args, n, varArgs, 0, nArgs - n);
newArgs[n] = varArgs;
return newArgs;
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(Object... c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public List classNames(Collection l) {
return getClassNames(l);
}
static public List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static public void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
vmBus_send("locking", lock, "thread", currentThread());
lock.lockInterruptibly();
vmBus_send("locked", lock, "thread", currentThread());
} catch (InterruptedException e) {
Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
printStackTrace(e);
rethrow(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static public void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static public ReentrantLock lock() {
return fairLock();
}
static public File computerIDFile() {
return javaxDataDir("Basic Info/computer-id.txt");
}
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 userDir() {
return new File(userHome());
}
static public File userDir(String path) {
return new File(userHome(), path);
}
static public String makeRandomID(int length) {
return makeRandomID(length, defaultRandomGenerator());
}
static public String makeRandomID(int length, Random random) {
char[] id = new char[length];
for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
static public String makeRandomID(Random r, int length) {
return makeRandomID(length, r);
}
static public 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 void unlock(Lock lock, String msg) {
if (lock == null)
return;
lock.unlock();
vmBus_send("unlocked", lock, "thread", currentThread());
print("Unlocked: " + msg);
}
static public void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
vmBus_send("unlocked", lock, "thread", currentThread());
}
static public Throwable _storeException_value;
static public void _storeException(Throwable e) {
_storeException_value = e;
}
static public Class actualMC() {
return or((Class) realMC(), mc());
}
static public boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static public boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
static public boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b))
return false;
m.m = new String[] { dropLast(l(b), a) };
return true;
}
static public Object safeUnstructure(String s) {
return unstructure(s, true);
}
static public Object safeUnstructure(File f) {
return safeUnstructureGZFile(f);
}
static public String assertIsIdentifier(String s) {
if (!isIdentifier(s))
throw fail("Not an identifier: " + quote(s));
return s;
}
static public String assertIsIdentifier(String msg, String s) {
if (!isIdentifier(s))
throw fail(msg + " - Not an identifier: " + quote(s));
return s;
}
static public String renderVars_str(Object... params) {
List l = new ArrayList();
int i = 0;
if (odd(l(params))) {
l.add(strOrNull(first(params)));
++i;
}
for (; i + 1 < l(params); i += 2) l.add(params[i] + "=" + params[i + 1]);
return trim(joinWithComma(l));
}
static public Class getOuterClass(Class c) {
return getOuterClass(c, null);
}
static public Class getOuterClass(Class c, Object classFinder) {
try {
String s = c.getName();
int i = s.lastIndexOf('$');
String name = substring(s, 0, i);
return classForName(name, classFinder);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Class getOuterClass(Object o) {
return getOuterClass(o, null);
}
static public Class getOuterClass(Object o, Object classFinder) {
return getOuterClass(_getClass(o), classFinder);
}
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 HashMap instanceFieldsMap(Object o) {
return (HashMap) getOpt_getFieldMap(o);
}
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) {
f.set(o, ((Long) value).intValue());
return;
}
if (type == boolean.class && value instanceof String) {
f.set(o, isTrueOrYes(((String) value)));
return;
}
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 void dynamicObject_setRawFieldValue(DynamicObject o, Object key, Object value) {
if (o == null)
return;
synchronized (o) {
o.fieldValues = syncMapPut2_createLinkedHashMap((LinkedHashMap) o.fieldValues, key, value);
}
}
static public Map thisDollarOneFields_cache = newDangerousWeakHashMap();
static public Field[] thisDollarOneFields(Class c) {
synchronized (thisDollarOneFields_cache) {
Field[] l = thisDollarOneFields_cache.get(c);
if (l == null)
thisDollarOneFields_cache.put(c, l = thisDollarOneFields_uncached(c));
return l;
}
}
static public Field[] thisDollarOneFields_uncached(Class c) {
List fields = new ArrayList();
do {
for (Field f : c.getDeclaredFields()) if (f.getName().startsWith("this$"))
fields.add(makeAccessible(f));
c = c.getSuperclass();
} while (c != null);
return toArray(new Field[l(fields)], fields);
}
static public Method fastIntern_method;
static public String fastIntern(String s) {
try {
if (s == null)
return null;
if (fastIntern_method == null) {
fastIntern_method = findMethodNamed(javax(), "internPerProgram");
if (fastIntern_method == null)
upgradeJavaXAndRestart();
}
return (String) fastIntern_method.invoke(null, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map> callOpt_noArgs_cache = newDangerousWeakHashMap();
static public Object callOpt_noArgs(Object o, String method) {
try {
if (o == null)
return null;
if (o instanceof Class)
return callOpt(o, method);
Class c = o.getClass();
HashMap map;
synchronized (callOpt_noArgs_cache) {
map = callOpt_noArgs_cache.get(c);
if (map == null)
map = callOpt_noArgs_makeCache(c);
}
Method m = map.get(method);
return m != null ? m.invoke(o) : null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public HashMap callOpt_noArgs_makeCache(Class c) {
HashMap map = new HashMap();
Class _c = c;
do {
for (Method m : c.getDeclaredMethods()) if (m.getParameterTypes().length == 0 && !reflection_isForbiddenMethod(m)) {
makeAccessible(m);
String name = m.getName();
if (!map.containsKey(name))
map.put(name, m);
}
_c = _c.getSuperclass();
} while (_c != null);
callOpt_noArgs_cache.put(c, map);
return map;
}
static public String[] match2(List pat, List tok) {
int i = pat.indexOf("...");
if (i < 0)
return match2_match(pat, tok);
pat = new ArrayList(pat);
pat.set(i, "*");
while (pat.size() < tok.size()) {
pat.add(i, "*");
pat.add(i + 1, "");
}
return match2_match(pat, tok);
}
static public String[] match2_match(List pat, List tok) {
List result = new ArrayList();
if (pat.size() != tok.size()) {
return null;
}
for (int i = 1; i < pat.size(); i += 2) {
String p = pat.get(i), t = tok.get(i);
if (eq(p, "*"))
result.add(t);
else if (!equalsIgnoreCase(unquote(p), unquote(t)))
return null;
}
return result.toArray(new String[result.size()]);
}
static public Map classForName_cache = synchroHashMap();
static public Class classForName(String name) {
return classForName(name, null);
}
static public Class classForName(String name, Object classFinder) {
if (classForName_cache == null || classFinder != null)
return classForName_uncached(name, classFinder);
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = classForName_uncached(name, null));
return c;
}
static public Class classForName_uncached(String name, Object classFinder) {
try {
if (classFinder != null)
return (Class) callF(classFinder, name);
return Class.forName(name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static public Object nuObjectWithoutArguments(String className) {
try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObjectWithoutArguments(Class c) {
try {
if (nuObjectWithoutArguments_cache == null)
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
static public List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static public boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class)
return arg instanceof Boolean;
if (type == int.class)
return arg instanceof Integer;
if (type == long.class)
return arg instanceof Long;
if (type == float.class)
return arg instanceof Float;
if (type == short.class)
return arg instanceof Short;
if (type == char.class)
return arg instanceof Character;
if (type == byte.class)
return arg instanceof Byte;
if (type == double.class)
return arg instanceof Double;
return type.isInstance(arg);
}
static public A liftLast(List l) {
if (empty(l))
return null;
int i = l(l) - 1;
A a = l.get(i);
l.remove(i);
return a;
}
static public List liftLast(int n, List l) {
int i = l(l) - n;
List part = cloneSubList(l, i);
removeSubList(l, i);
return part;
}
static public int boolToInt(boolean b) {
return b ? 1 : 0;
}
static public A jtransparent(final A a) {
{
swing(new Runnable() {
public void run() {
try {
a.setOpaque(false);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.setOpaque(false);";
}
});
}
return a;
}
static public JPanel borderLayoutPanel() {
return jpanel(new BorderLayout());
}
static public JSpinner jSpinnerCommitOnValidEdit(JSpinner spinner) {
var tf = getTextFieldFromSpinner(spinner);
if (tf != null) {
swing(new Runnable() {
public void run() {
try {
DefaultFormatter formatter = (DefaultFormatter) (tf.getFormatter());
if (formatter != null)
formatter.setCommitsOnValidEdit(true);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "DefaultFormatter formatter = (DefaultFormatter) (tf.getFormatter());\r\n if...";
}
});
}
return spinner;
}
static public char stringToChar(String s) {
if (l(s) != 1)
throw fail("bad stringToChar: " + s);
return firstChar(s);
}
static public boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
}
static public boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b))
return false;
if (m != null)
m.m = new String[] { substring(a, 0, l(a) - l(b)) };
return true;
}
static public Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
static public Class _getClass(Object realm, String name) {
try {
return classLoaderForObject(realm).loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
static public String fsI(String id) {
return formatSnippetID(id);
}
static public String fsI(long id) {
return formatSnippetID(id);
}
static public File loadBinarySnippet(String snippetID) {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
return loadBinarySnippet_noResourceLoader(snippetID);
}
static public File loadBinarySnippet_noResourceLoader(String snippetID) {
try {
long id = parseSnippetID(snippetID);
if (isImageServerSnippet(id))
return loadImageAsFile(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile_noResourceLoader(snippetID);
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
static public boolean loadBufferedImageFixingGIFs_debug = false;
static public ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal();
static public Image loadBufferedImageFixingGIFs(File file) {
try {
if (!file.exists())
return null;
if (!isGIF(file))
return ImageIO.read(file);
if (loadBufferedImageFixingGIFs_debug)
print("loadBufferedImageFixingGIFs" + ": checking gif");
ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
reader.setInput(ImageIO.createImageInputStream(file));
int numImages = reader.getNumImages(true);
IIOMetadata imageMetaData = reader.getImageMetadata(0);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
boolean foundBug = false;
for (int i = 0; i < numImages && !foundBug; i++) {
IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
if (Integer.parseInt(delay) == 0) {
foundBug = true;
}
break;
}
}
}
if (loadBufferedImageFixingGIFs_debug)
print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
Image image;
if (!foundBug) {
image = Toolkit.getDefaultToolkit().createImage(f2s(file));
} else {
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
{
ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
try {
ImageWriter writer = ImageIO.getImageWriter(reader);
writer.setOutput(ios);
writer.prepareWriteSequence(null);
for (int i = 0; i < numImages; i++) {
BufferedImage frameIn = reader.read(i);
IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
if (Integer.parseInt(delay) == 0) {
((IIOMetadataNode) node).setAttribute("delayTime", "10");
}
break;
}
}
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
IIOImage frameOut = new IIOImage(frameIn, null, metadata);
writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
}
writer.endWriteSequence();
} finally {
_close(ios);
}
}
byte[] data = baoStream.toByteArray();
setVar(loadBufferedImageFixingGIFs_output.get(), data);
if (loadBufferedImageFixingGIFs_debug)
print("Data size: " + l(data));
image = Toolkit.getDefaultToolkit().createImage(data);
}
return image;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
static public String _userHome;
static public String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
static public File userHome(String path) {
return new File(userDir(), path);
}
static public boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static public String imageServerLink(String md5OrID) {
if (possibleMD5(md5OrID))
return "https://botcompany.de/images/md5/" + md5OrID;
return imageServerLink(parseSnippetID(md5OrID));
}
static public String imageServerLink(long id) {
return "https://botcompany.de/images/" + id;
}
static public boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static public boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
static public void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, Math.min(a.length, b.length));
}
static public void arraycopy(Object src, int srcPos, int destPos, int n) {
arraycopy(src, srcPos, src, destPos, n);
}
static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
static public A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
static public A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
static public List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
static public Thread currentThread() {
return Thread.currentThread();
}
static public Map vm_threadInterruptionReasonsMap() {
return vm_generalWeakSubMap("Thread interruption reasons");
}
static public String strOr(Object o, String ifNull) {
return o == null ? ifNull : str(o);
}
static public void lockOrFail(Lock lock, long timeout) {
try {
ping();
vmBus_send("locking", lock, "thread", currentThread());
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
vmBus_send("locked", lock, "thread", currentThread());
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static public 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 ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal();
static public void checkFileNotTooBigToRead(File f) {
callF(checkFileNotTooBigToRead_tl.get(), f);
}
static public Random defaultRandomGenerator() {
return ThreadLocalRandom.current();
}
static public List beginCriticalAction_inFlight = synchroList();
static public class CriticalAction {
public String description;
public CriticalAction() {
}
public CriticalAction(String description) {
this.description = description;
}
public void done() {
beginCriticalAction_inFlight.remove(this);
}
}
static public CriticalAction beginCriticalAction(String description) {
ping();
CriticalAction c = new CriticalAction(description);
beginCriticalAction_inFlight.add(c);
return c;
}
static public void cleanMeUp_beginCriticalAction() {
int n = 0;
while (nempty(beginCriticalAction_inFlight)) {
int m = l(beginCriticalAction_inFlight);
if (m != n) {
n = m;
try {
print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
} catch (Throwable __e) {
printStackTrace(__e);
}
}
sleepInCleanUp(10);
}
}
static public long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static public Object realMC() {
return getThreadLocal(realMC_tl());
}
static public char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s) - 1);
}
static public A[] dropLast(A[] a) {
return dropLast(a, 1);
}
static public A[] dropLast(A[] a, int n) {
if (a == null)
return null;
n = Math.min(n, a.length);
A[] b = arrayOfSameType(a, a.length - n);
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static public List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
static public List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
static public List dropLast(Iterable l) {
return dropLast(asList(l));
}
static public String dropLast(String s) {
return substring(s, 0, l(s) - 1);
}
static public String dropLast(String s, int n) {
return substring(s, 0, l(s) - n);
}
static public String dropLast(int n, String s) {
return dropLast(s, n);
}
static public Object safeUnstructureGZFile(File f) {
try {
if (!fileExists(f))
return null;
BufferedReader reader = utf8BufferedReader(gzInputStream(f));
return unstructure_tok(javaTokC_noMLS_onReader(reader), true, null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String strOrNull(Object o) {
return o == null ? null : str(o);
}
static public class getOpt_Map extends WeakHashMap {
public getOpt_Map() {
if (getOpt_special == null)
getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final public Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
static public HashMap getOpt_special;
static public Map getOpt_getFieldMap(Object o) {
Class c = _getClass(o);
HashMap map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
return map;
}
static public Object getOpt_cached(Object o, String field) {
try {
if (o == null)
return null;
Map