Warning : session_start(): open(/var/lib/php/sessions/sess_h0a7gtuajc6h7j8948k0ba2o63, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import java.util.function.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
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.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.setOpt_raw;
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.struct;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.rethrow;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.IVF2;
import loadableUtils.utils.Matches;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
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.DynPrintLog;
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.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.cget;
import static loadableUtils.utils.db;
import loadableUtils.utils.LongRange;
import loadableUtils.utils.IntRange;
import loadableUtils.utils.MultiMap;
import loadableUtils.utils.Meta;
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.RandomAccessAbstractList;
import loadableUtils.utils.IBWIntegralImage;
import loadableUtils.utils.Producer;
import loadableUtils.utils.IntBuffer;
import loadableUtils.utils.AbstractMatrix;
import loadableUtils.utils.WithTimestamp;
import loadableUtils.utils.IMeta;
import loadableUtils.utils.LiveValue;
import loadableUtils.utils.Timestamp;
import loadableUtils.utils.DoubleRect;
import loadableUtils.utils.Complex;
import loadableUtils.utils.Either;
import loadableUtils.utils.Steppable;
import loadableUtils.utils.T3;
import loadableUtils.utils.Swingable;
import loadableUtils.utils.Average;
import loadableUtils.utils.BWIntegralImage;
import loadableUtils.utils.DoubleRange;
import loadableUtils.utils.Seconds;
import static loadableUtils.utils.withTimestamp;
import static loadableUtils.utils.score;
import static loadableUtils.utils.stepAll;
import static loadableUtils.utils.infoMessage;
import static loadableUtils.utils.brightnessToRGBA;
import static loadableUtils.utils.withBorder;
import static loadableUtils.utils.rcallOpt;
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.n;
import static loadableUtils.utils.abs;
import static loadableUtils.utils.callMain;
import static loadableUtils.utils.caseInsensitiveComparator;
import static loadableUtils.utils.rep;
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.hasMethod;
import static loadableUtils.utils.countIteratorToList;
import static loadableUtils.utils.containsOneOf;
import static loadableUtils.utils.setSCPComponent;
import static loadableUtils.utils.hideWindow;
import static loadableUtils.utils.ymdMinusHMS;
import static loadableUtils.utils.jPopDownButton_noText;
import static loadableUtils.utils.swingLater;
import static loadableUtils.utils.currentImage;
import static loadableUtils.utils._defaultClassFinder;
import static loadableUtils.utils.setImage;
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.getSnippetTitle;
import static loadableUtils.utils.jFullCenter;
import static loadableUtils.utils.dm_fieldCheckBox;
import static loadableUtils.utils.indent;
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.centerAndEast;
import static loadableUtils.utils.metaMapPut;
import static loadableUtils.utils.makeFrame;
import static loadableUtils.utils.setDoubleBuffered;
import static loadableUtils.utils.asVirtualList;
import static loadableUtils.utils.javaTokForJFind_array;
import static loadableUtils.utils.withLeftAndRightMargin;
import static loadableUtils.utils.dm_doEvery;
import static loadableUtils.utils.ping_v3;
import static loadableUtils.utils.flattenArray2;
import static loadableUtils.utils.getParent;
import static loadableUtils.utils.strOrEmpty;
import static loadableUtils.utils.pqO;
import static loadableUtils.utils.run;
import static loadableUtils.utils.has;
import static loadableUtils.utils.last;
import static loadableUtils.utils.warn;
import static loadableUtils.utils.distance;
import static loadableUtils.utils.jrightAlignedLine;
import static loadableUtils.utils.toRect;
import static loadableUtils.utils.installWindowDragger;
import static loadableUtils.utils.installTimer;
import static loadableUtils.utils.clipBufferedImage;
import static loadableUtils.utils.setText;
import static loadableUtils.utils.splitAtSpace;
import static loadableUtils.utils.getBounds;
import static loadableUtils.utils.northAndCenterWithMargin;
import static loadableUtils.utils.renderUserThreadsWithStackTraces;
import static loadableUtils.utils.newConceptsWithClassFinder;
import static loadableUtils.utils.replaceSublist;
import static loadableUtils.utils.joinSubList;
import static loadableUtils.utils.onSelectedItem;
import static loadableUtils.utils.replace;
import static loadableUtils.utils.profileToConsole;
import static loadableUtils.utils.myLibraryFiles;
import static loadableUtils.utils.findCodeTokens;
import static loadableUtils.utils.withTypeWriterFont;
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.centerAndEastWithMargin;
import static loadableUtils.utils.getFrame;
import static loadableUtils.utils.centerAndSouth;
import static loadableUtils.utils.dm_fieldLiveValue;
import static loadableUtils.utils.toObjectArray;
import static loadableUtils.utils.rectFromPoints;
import static loadableUtils.utils.runnableThread;
import static loadableUtils.utils.toolTip;
import static loadableUtils.utils.firstToUpper;
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.gazelle_wavySpacer;
import static loadableUtils.utils.callOnLoadMethods;
import static loadableUtils.utils.dm_rEnter;
import static loadableUtils.utils.toString;
import static loadableUtils.utils.renameFile;
import static loadableUtils.utils.regionMatches;
import static loadableUtils.utils.warnIfOddCount;
import static loadableUtils.utils.printFileInfo;
import static loadableUtils.utils.bindLiveValueListenerToComponent;
import static loadableUtils.utils.screenBounds;
import static loadableUtils.utils.toRectangle;
import static loadableUtils.utils.widthForHeight;
import static loadableUtils.utils.javaxCodeDir;
import static loadableUtils.utils.jLiveValueLabel;
import static loadableUtils.utils.shortClassName_dropNumberPrefix;
import static loadableUtils.utils.minimizeWindow;
import static loadableUtils.utils.appendToFileBaseName;
import static loadableUtils.utils.jbutton;
import static loadableUtils.utils.setEnabled;
import static loadableUtils.utils.functionCall;
import static loadableUtils.utils.javaTokForStructure;
import static loadableUtils.utils.northAndCenter;
import static loadableUtils.utils.jline;
import static loadableUtils.utils.toMS;
import static loadableUtils.utils.creator;
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.renderFileInfo;
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.repeat;
import static loadableUtils.utils.structureForUser;
import static loadableUtils.utils.nohup;
import static loadableUtils.utils.onWindowClosing;
import static loadableUtils.utils.asArray;
import static loadableUtils.utils.pt;
import static loadableUtils.utils.showText;
import static loadableUtils.utils.setDefaultClassFinder;
import static loadableUtils.utils.getBytecodePathForClass;
import static loadableUtils.utils.installWindowResizeDraggerOnBorder;
import static loadableUtils.utils.singular;
import static loadableUtils.utils.minus;
import static loadableUtils.utils.syncAddOrCreate;
import static loadableUtils.utils.intRange;
import static loadableUtils.utils.getScreenHeight;
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.similarEmptyMap;
import static loadableUtils.utils.toFile;
import static loadableUtils.utils.tempAdd;
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.humanizeFormLabel;
import static loadableUtils.utils.wrapForSmartAdd;
import static loadableUtils.utils.asSet;
import static loadableUtils.utils.autoFrameTitle;
import static loadableUtils.utils.restart;
import static loadableUtils.utils.installTrayIcon;
import static loadableUtils.utils.shootScreen2;
import static loadableUtils.utils.filter;
import static loadableUtils.utils.onChange;
import static loadableUtils.utils.pingSource;
import static loadableUtils.utils.isNonEmptySingleZip_byMagicHeader;
import static loadableUtils.utils.withTopMargin;
import static loadableUtils.utils.error;
import static loadableUtils.utils.setBackground;
import static loadableUtils.utils.sysNow;
import static loadableUtils.utils.elapsedSeconds;
import static loadableUtils.utils.hotwire;
import static loadableUtils.utils.heldInstance;
import static loadableUtils.utils.trayIcon_imageAutoSize;
import loadableUtils.utils.Pair;
import loadableUtils.utils.IBWImage;
import loadableUtils.utils.WidthAndHeight;
import loadableUtils.utils.Enterable;
import loadableUtils.utils.G2Drawable;
import static loadableUtils.utils.getPrintLog;
import static loadableUtils.utils.unstructure;
import static loadableUtils.utils.StefansOS_ConnectToServer;
import static loadableUtils.utils._MethodCache;
import static loadableUtils.utils.defaultMargin;
import javax.swing.border.*;
import java.text.NumberFormat;
import java.awt.geom.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.datatransfer.StringSelection;
class main {
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 GazelleScreenCam extends DynModule {
volatile public boolean enabled = true;
transient public JPanel buttons;
public void setEnabled(boolean b) {
setField("enabled", b);
}
public JComponent visualize_enabled() {
return dm_checkBox("enabled");
}
public int screenNr;
public int pixelRows = 128, colors = 8;
public String script, testScreenScript;
public boolean animate = true;
public boolean horizontalLayout = false;
transient public ImageSurface isPosterized, isRegions, isTestScreen;
transient public ScreenCamStream images = new ScreenCamStream();
transient public BWIntegralImageStream integralImages = new BWIntegralImageStream();
transient public SourceTriggeredStream scaledAndPosterizedImages = new SourceTriggeredStream();
transient public DoubleFPSCounter fpsCounter = new DoubleFPSCounter();
transient public int fps;
transient public ScreenSelectorRadioButtons screenSelector;
transient public RollingAverage remainingMSPerFrame = new RollingAverage();
transient public int remainingMS;
transient public FunctionTimings functionTimings = new FunctionTimings();
transient public ReliableSingleThread rstRunScript = dm_rst(me(), new Runnable() {
public void run() {
try {
_runScript();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_runScript();";
}
});
transient public JGazelleVScriptRunner scriptRunner;
transient public JGazelleVScriptRunner testScreenScriptRunner;
transient public Animation animation;
transient public FastRegions_BWImage mainScreenRegions;
transient public ImageSurface_HighlightRegion regionHighlighter;
transient public UIURLSystem uiURLs;
public String uiURL;
public void start() {
try {
super.start();
dm_onFieldChange("horizontalLayout", new Runnable() {
public void run() {
try {
dm_reload();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_reload();";
}
});
uiURLs = new UIURLSystem(me(), dm_fieldLiveValue("uiURL"));
scriptRunner = new JGazelleVScriptRunner(dm_fieldLiveValue("script", me()));
testScreenScriptRunner = new JGazelleVScriptRunner(dm_fieldLiveValue("testScreenScript", me()));
images.directlyFeedInto(integralImages);
integralImages.onNewElement(ii -> scaledAndPosterizedImages.newElement(posterizeBWImage_withMeta(colors, scaledBWImageFromBWIntegralImage_withMeta_height(pixelRows, ii))));
integralImages.onNewElement(new Runnable() {
public void run() {
try {
if (shouldRunScript())
rstRunScript.go();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (shouldRunScript()) rstRunScript.go();";
}
});
scaledAndPosterizedImages.onNewElement(img -> {
fpsCounter.inc();
setField("fps", iround(fpsCounter.get()));
{
if (isPosterized != null)
isPosterized.setImage_thisThread(img);
}
floodFill(img);
});
dm_doEvery(1000 / 20, new Runnable() {
public void run() {
try {
if (enabled) {
{
if (screenSelector != null)
screenSelector.updateScreenCount();
}
Timestamp deadline = tsNowPlusMS(1000 / 20);
images.useScreen(screenNr);
images.step();
long remaining = deadline.minus(tsNow());
remainingMSPerFrame.add(remaining);
setField("remainingMS", iround(remainingMSPerFrame.get()));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (enabled) {\r\n screenSelector?.updateScreenCount();\r\n Timesta...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public ImageSurface stdImageSurface() {
return pixelatedImageSurface().setAutoZoomToDisplay(true).repaintInThread(false);
}
public JComponent visualize() {
screenSelector = new ScreenSelectorRadioButtons(dm_fieldLiveValue("screenNr"));
screenSelector.compactLayout(true);
screenSelector.hideIfOnlyOne(true);
screenSelector.screenLabel("");
isPosterized = stdImageSurface();
regionHighlighter = new ImageSurface_HighlightRegion(isPosterized);
regionHighlighter.regionPainter(new RegionFillPainter());
isRegions = stdImageSurface();
isTestScreen = stdImageSurface();
awtEvery(isTestScreen, 1000 / 20, new Runnable() {
public void run() {
try {
stepAnimation();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "stepAnimation();";
}
});
JTextArea taTimings = jTextArea_noUndo();
awtEveryAndNow(taTimings, .5, new Runnable() {
public void run() {
try {
setText(taTimings, renderFunctionTimings());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "setText(taTimings, renderFunctionTimings())";
}
});
var jSpeedInfo = dm_transientCalculatedToolTip(() -> speedInfo_long(), rightAlignLabel(dm_transientCalculatedLabel(() -> speedInfo())));
var tabs = scrollingTabs(jTopOrLeftTabs(horizontalLayout, "Posterized", withTools(isPosterized), "Regions", jscroll_centered_borderless(isRegions), "Script", scriptRunner.scriptAndResultPanel(), "Test Screen", testScreenPanel(), "Timings", withRightAlignedButtons(taTimings, "Reset", new Runnable() {
public void run() {
try {
resetTimings();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "resetTimings();";
}
})));
var vis = northAndCenter(withSideAndTopMargin(uiURLs.urlBar()), centerAndSouthOrEast(horizontalLayout, horizontalLayout ? withMargin(tabs) : withSideMargin(tabs), (borderlessScrollPane(jHigherScrollPane(jfullcenter(vstack(withLeftAndRightMargin(hstack(dm_rcheckBox("enabled", "Watch screen"), screenSelector.visualize(), jlabel(" in "), withLabelToTheRight("colors @ ", dm_spinner("colors", 2, 256)), withLabelToTheRight("p", dm_powersOfTwoSpinner("pixelRows", 512)))), verticalStrut(2), withRightMargin(jSpeedInfo))))))));
setHorizontalMarginForAllButtons(vis, 4);
return vis;
}
public String speedInfo() {
return "FPS " + fps + " idle " + remainingMS + " ms";
}
public String speedInfo_long() {
return "Screen cam running at " + nFrames(fps) + "/second. " + n2(remainingMS) + " ms remaining per frame in first core.";
}
public void floodFill(BWImage img) {
FastRegions_BWImage ff = new FastRegions_BWImage(img);
ff.collectBounds();
functionTimings.time("Regions", ff);
mainScreenRegions = ff;
{
if (regionHighlighter != null)
regionHighlighter.setRegions(ff);
}
if (isRegions != null && isRegions.isShowing_quick()) {
print("Showing regions image");
isRegions.setImage_thisThread(ff.regionsImage());
}
setEnclosingTabTitle(isRegions, nRegions(ff.regionCount()));
}
public boolean useErrorHandling() {
return false;
}
public String renderFunctionTimings() {
return lines(ciSorted(map(functionTimings.get(), (f, avg) -> firstToUpper(f) + ": " + n2(iround(nsToMicroseconds(avg.get()))) + " " + microSymbol() + "s (" + n2(iround(avg.n())) + ")")));
}
transient public long _runScript_idx;
public void _runScript() {
long n = integralImages.elementCount();
if (n > _runScript_idx) {
_runScript_idx = n;
scriptRunner.parseAndRunOn(integralImages.get());
}
}
public boolean shouldRunScript() {
return isShowing(scriptRunner.scpScriptResult);
}
public void stepAnimation() {
if (!animate)
return;
if (animation == null) {
animation = new AnimatedLine();
animation.start();
}
animation.nextFrame();
var img = whiteImage(animation.w, animation.h);
animation.setGraphics(createGraphics(img));
animation.paint();
{
if (isTestScreen != null)
isTestScreen.setImage(img);
}
var ii = bwIntegralImage_withMeta(img);
testScreenScriptRunner.parseAndRunOn(ii);
}
public JComponent testScreenPanel() {
return centerAndSouthWithMargin(hsplit(northAndCenterWithMargin(centerAndEastWithMargin(jlabel("Input"), dm_fieldCheckBox("animate")), jscroll_centered_borderless(isTestScreen)), northAndCenterWithMargin(centerAndEastWithMargin(jlabel("Output"), testScreenScriptRunner.lblScore), testScreenScriptRunner.scpScriptResult)), testScreenScriptRunner.scriptInputField());
}
public List popDownItems() {
return ll(jCheckBoxMenuItem_dyn("Horizontal Layout", () -> horizontalLayout, b -> setField("horizontalLayout", b)));
}
public void unvisualize() {
}
public void resetTimings() {
functionTimings.reset();
}
public JComponent withTools(ImageSurface is) {
new ImageSurface_PositionToolTip(is);
return centerAndEastWithMargin(jscroll_centered_borderless(is), vstackWithSpacing(5, jbutton("A"), jbutton("B"), jbutton("C")));
}
}
static public boolean _moduleClass_GazelleScreenCam = true;
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 PrintLogModule extends DynPrintLog {
public PrintLogModule() {
setModuleName("Print Log");
}
public String getPrintLog() {
return printLog();
}
public boolean useErrorHandling() {
return false;
}
}
static public class Stem extends Concept {
static final public String _fieldOrder = "host module frameRect maximized alwaysOnTop autoUpdate window btnMax";
transient public GazelleHost host;
public DynModule module;
public Rect frameRect;
public boolean maximized, alwaysOnTop, autoUpdate;
transient public JFrame window;
transient public JButton btnMax;
public Stem() {
}
public Stem(GazelleHost host) {
this.host = host;
}
public Stem(GazelleHost host, DynModule module) {
this.module = module;
this.host = host;
}
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);
onBoundsChange(window, new Runnable() {
public void run() {
try {
saveFrameRect();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "saveFrameRect();";
}
});
alwaysOnTop(window, alwaysOnTop);
}
public boolean isMain() {
return this == host.stem;
}
public void minimize() {
if (host.trayIcon == null || !isMain())
minimizeWindow(window);
else
hideWindow(window);
}
public void deleteMe() {
printAlsoToSystemOut = true;
print("deleteMe " + isMain());
if (isMain()) {
host.cleanExit();
} else {
disposeWindow(window);
{
cleanUp(module);
module = null;
}
cdelete(this);
}
}
public void grabWindowState() {
setField("maximized", !isExtendedStateNormal(window));
}
public void updateBtnMax() {
if (!isShowing(btnMax))
return;
grabWindowState();
setText(btnMax, maximized ? "NORM" : "MAX");
}
public JComponent makeWindowBorderAndTitle(JComponent contents, String title) {
var icons = jline();
if (host.allowFrameMaximization) {
icons.add(btnMax = jbutton("", runnableThread(new Runnable() {
public void run() {
try {
maximizeOrRestoreFrame(window);
updateBtnMax();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "maximizeOrRestoreFrame(window);\r\n updateBtnMax();";
}
})));
onFirstShowing(btnMax, new Runnable() {
public void run() {
try {
updateBtnMax();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "updateBtnMax();";
}
});
}
icons.add(jbutton("MIN", new Runnable() {
public void run() {
try {
minimize();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "minimize();";
}
}));
icons.add(jbutton("QUIT", runnableThread(new Runnable() {
public void run() {
try {
if (swingConfirm("Really quit Gazelle?"))
deleteMe();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (swingConfirm(\"Really quit Gazelle?\"))\r\n deleteMe();";
}
})));
setHorizontalMarginForAllButtons(icons, 4);
icons.add(jPopDownButton_noText(flattenToList(!isMain() ? null : ll("Restart", runnableThread(new Runnable() {
public void run() {
try {
host.restart();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "host.restart()";
}
}), "Update Gazelle", runnableThread(new Runnable() {
public void run() {
try {
host.upgradeGazelle();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "host.upgradeGazelle()";
}
}), jCheckBoxMenuItem_dyn("Auto-Update", () -> autoUpdate, b -> cset(Stem.this, "autoUpdate", b))), "---", jCheckBoxMenuItem_dyn("Always on top", () -> alwaysOnTop, alwaysOnTop -> setAlwaysOnTop(alwaysOnTop)), "---", !isMain() ? null : ll("Screenshoot this window", runnableThread(new Runnable() {
public void run() {
try {
shootWindow();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "shootWindow();";
}
}), "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());";
}
}), !isMain() ? null : "Print log", !isMain() ? null : runnableThread(new Runnable() {
public void run() {
try {
host.showPrintLog();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "host.showPrintLog()";
}
})), ccallOpt(module, "popDownItems"))));
var actualTitle = fontSizePlus(7, jCenteredLabel(title));
var spacer = gazelle_wavySpacer();
var titleBarMain = setOpaqueBackground(host.color1, westCenterAndEastWithMargin(jImage_scaledToHeight(24, host.trayIconImageID), actualTitle, setOpaqueBackground(host.color2, spacer)));
installWindowDragger(actualTitle);
installWindowDragger(spacer);
var titleBar = setBackground(host.color2, centerAndEast(titleBarMain, icons));
var border = BorderFactory.createLineBorder(host.color1, host.borderSize);
var outerPanel = withBorder(border, northAndCenter(titleBar, contents));
installWindowResizeDraggerOnBorder(outerPanel);
return outerPanel;
}
public void startAndShow() {
module._host = this;
setOpt_raw(module, "threadPool", threadPool);
setOpt_raw(module, "concepts", host.concepts);
copyLocalLog(module, mc());
var __9 = makeVisAndTitle();
var vis = __9.a;
var title = __9.b;
printWithMS("Show frame");
JFrame frame = makeUndecoratedFrame(title, vis);
setFrameIcon(frame, host.trayIconImageID);
setWindow(frame);
showWindow(window);
if (maximized && host.allowFrameMaximization)
maximizeFrame(window);
}
public Pair makeVisAndTitle() {
JComponent vis;
{
AutoCloseable __7 = module.enter();
try {
module.start();
printWithMS("Visualize");
vis = swing(() -> {
AutoCloseable __8 = module.enter();
try {
return module.visualize();
} finally {
_close(__8);
}
});
} finally {
_close(__7);
}
}
String title = host.windowTitle;
if (!isMain())
title += appendWithColon(module.moduleName());
vis = makeWindowBorderAndTitle(vis, title);
return pair(vis, title);
}
public void revisualize() {
if (window == null)
return;
try {
module.unvisualize();
} catch (Throwable __e) {
printStackTrace(__e);
}
var __10 = makeVisAndTitle();
var vis = __10.a;
var title = __10.b;
setFrameContents(window, vis);
}
public void shootWindow() {
var img = renderComponentToImage(window);
copyImageToClipboard(img);
saveInImageDirectoryWithCounter("Gazelle/Gazelle", img);
}
}
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 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 TrayIconLastPosition trayIconLastPosition;
transient public Set argsSet;
transient public Concepts concepts;
transient public boolean allowFrameMaximization = false;
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 {
trayIconLeftClick();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "trayIconLeftClick();";
}
}, "Exit Gazelle", new Runnable() {
public void run() {
try {
cleanExit();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cleanExit();";
}
});
trayIconLastPosition = new TrayIconLastPosition(trayIcon);
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
public void run(String[] args) {
try {
run2(args);
} catch (Throwable e) {
printStackTrace(e);
hideTrayIcon(trayIcon);
onWindowClosing(() -> systemExit(1), getWindow(showText_fast_noWrap("Gazelle Error", renderStackTrace(e))));
}
}
public void run2(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(__30 -> className(__30), allConcepts(concepts)));
var stems = findConcepts(concepts, Stem.class);
print("Stems in DB: " + l(stems));
stem = first(stems);
if (stem == null) {
print("Starting new module");
makeModule();
stem = registerConcept(concepts, new Stem(this, gazelle));
}
gazelle = stem.module;
for (var stem : list(Stem.class, concepts)) {
stem.host = this;
stem.startAndShow();
}
printWithMS("Dudadoneski");
}
public void showPrintLog() {
registerConcept(concepts, new Stem(this, new PrintLogModule())).startAndShow();
}
public JFrame mainWindow() {
return stem == null ? null : stem.window;
}
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...";
}
});
}
public String downloadURL() {
return "https://botcompany.de/jar/" + psI(programID()) + "?withLibs=1&noCompiler=1" + (downloadUncompressedJAR() ? "&uncompressed=1" : "");
}
public boolean downloadUncompressedJAR() {
return false;
}
public void revisualizeModule(Stem stem) {
stem.revisualize();
}
}
static public String windowTitle = "Gazelle 22";
static public String progIDForDBAndAutoUpdate = "#1033636";
static public boolean pingSourceStrictMode = false;
static public GazelleHost host;
static public GazelleScreenCam client;
static public ThreadPool threadPool;
public static void main(final String[] args) throws Exception {
loadableUtils.utils.__setJavaX(main.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;
if (cic(args, "delete-session")) {
print("Deleting session (" + programDir(programID) + ")");
clearConceptsOf(programID);
}
host = new GazelleHost(threadPool, () -> {
return client = new GazelleScreenCam();
});
host.windowTitle = windowTitle;
host.run(args);
if (!cic(args, "console")) {
print("Stopping System.out");
printAlsoToSystemOut = false;
}
});
print("aha.");
}
static public Map generalMap = syncMap();
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 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 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 ReliableSingleThread dm_rst(Runnable r) {
return dm_rst(dm_current_mandatory(), r);
}
static public ReliableSingleThread dm_rst(DynModule mod, Runnable r) {
return dm_rst(mod, new ReliableSingleThread(r));
}
static public ReliableSingleThread dm_rst(DynModule mod, ReliableSingleThread rst) {
rst.enter = dm_rEnter(mod);
return rst;
}
static public void dm_onFieldChange(String field, Runnable onChange) {
dm_watchField(field, onChange);
}
static public void dm_onFieldChange(Collection fields, Runnable onChange) {
dm_watchFields(fields, onChange);
}
static public BWImage posterizeBWImage_withMeta(int brightnessLevels, BWImage img) {
return setMetaSrcUnlessSame(img, posterizeBWImage(brightnessLevels, img), functionCall("posterizeBWImage", brightnessLevels, img));
}
static public BWImage scaledBWImageFromBWIntegralImage_withMeta(int w, BWIntegralImage img) {
return scaledBWImageFromBWIntegralImage(img, w);
}
static public BWImage scaledBWImageFromBWIntegralImage_withMeta_height(int h, BWIntegralImage img) {
return scaledBWImageFromBWIntegralImage(img, widthForHeight(img, h), h);
}
static public BWImage scaledBWImageFromBWIntegralImage_withMeta(BWIntegralImage img, int w) {
return scaledBWImageFromBWIntegralImage_withMeta(img, w, heightForWidth(img, w));
}
static public BWImage scaledBWImageFromBWIntegralImage_withMeta(BWIntegralImage img, int w, int h) {
return setMetaSrc(scaledBWImageFromBWIntegralImage(img, w, h), functionCall("scaledBWImageFromBWIntegralImage", img, w, h));
}
static public BWImage scaledBWImageFromBWIntegralImage_withMeta(int w, IBWIntegralImage img) {
return scaledBWImageFromBWIntegralImage(img, w);
}
static public BWImage scaledBWImageFromBWIntegralImage_withMeta_height(int h, IBWIntegralImage img) {
return scaledBWImageFromBWIntegralImage(img, widthForHeight(img, h), h);
}
static public BWImage scaledBWImageFromBWIntegralImage_withMeta(IBWIntegralImage img, int w) {
return scaledBWImageFromBWIntegralImage_withMeta(img, w, heightForWidth(img, w));
}
static public BWImage scaledBWImageFromBWIntegralImage_withMeta(IBWIntegralImage img, int w, int h) {
return setMetaSrc(scaledBWImageFromBWIntegralImage(img, w, h), functionCall("scaledBWImageFromBWIntegralImage", img, w, h));
}
static public int iround(double d) {
return (int) Math.round(d);
}
static public int iround(Number n) {
return iround(toDouble(n));
}
static public Timestamp tsNowPlusMS(long ms) {
return tsNow().plus(msToSeconds(ms));
}
static public ImageSurface pixelatedImageSurface() {
var is = imageSurface();
imageSurface_pixelated(is);
return is;
}
static public ImageSurface pixelatedImageSurface(MakesBufferedImage img) {
return pixelatedImageSurface(toBufferedImage(img));
}
static public ImageSurface pixelatedImageSurface(BufferedImage img) {
var is = pixelatedImageSurface();
is.setImage(img);
return is;
}
static public A awtEvery(A component, long delay, Object r) {
swingEvery(component, delay, r);
return component;
}
static public A awtEvery(A component, long delay, long firstDelay, Object r) {
swingEvery(component, delay, firstDelay, r);
return component;
}
static public void awtEvery(RootPaneContainer frame, long delay, Object r) {
swingEvery(frame, delay, r);
}
static public A awtEvery(A component, double delaySeconds, Object r) {
return awtEvery(component, toMS(delaySeconds), r);
}
static public JTextArea jTextArea_noUndo() {
return jTextArea_noUndo("");
}
static public JTextArea jTextArea_noUndo(final String text) {
return swingNu(JTextArea.class, text);
}
static public A awtEveryAndNow(A component, long delay, Object r) {
swingEvery(component, delay, 0, r);
return component;
}
static public A awtEveryAndNow(A component, double delaySeconds, Object r) {
return awtEveryAndNow(component, toMS(delaySeconds), r);
}
static public void awtEveryAndNow(RootPaneContainer frame, long delay, Object r) {
swingEvery(frame, delay, 0, r);
}
static public A dm_transientCalculatedToolTip(IF0 calc, A component) {
return toolTipFromLiveValue(dm_transientCalculatedLiveValue(Object.class, calc), component);
}
static public A rightAlignLabel(final A a) {
return setHorizontalAlignment(JLabel.RIGHT, a);
}
static public JLabel dm_transientCalculatedLabel(IF0 calc) {
return jLiveValueLabel(dm_transientCalculatedLiveValue(Object.class, calc));
}
static public JTabbedPane scrollingTabs(JTabbedPane pane) {
if (pane != null) {
swing(() -> {
pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
});
}
return pane;
}
static public JTabbedPane jTopOrLeftTabs(boolean horizontal, Object... x) {
return jLeftOrTopTabs(horizontal, x);
}
static public JTabbedPane jTopOrLeftTabs(boolean horizontal, Collection c) {
return jLeftOrTopTabs(horizontal, c);
}
static public JScrollPane jscroll_centered_borderless(Component c) {
return borderlessScrollPane(jscroll_centered(c));
}
static public JPanel withRightAlignedButtons(JComponent center, Object... params) {
return centerAndSouth(center, withMargin(jRightAlignedButtons(params)));
}
static public JPanel withRightAlignedButtons(Swingable center, Object... params) {
return withRightAlignedButtons(wrap(center), params);
}
static public JPanel withSideAndTopMargin(Component c) {
return withSideAndTopMargin(defaultMargin(), c);
}
static public JPanel withSideAndTopMargin(int w, Component c) {
return swing(() -> {
JPanel p = marginPanel();
p.setBorder(BorderFactory.createEmptyBorder(w, w, 0, w));
p.add(c);
return p;
});
}
static public JPanel centerAndSouthOrEast(boolean horizontal, Component c, Component s) {
return horizontal ? centerAndEast(c, s) : centerAndSouth(c, s);
}
static public JPanel withSideMargin(Component c) {
return withLeftAndRightMargin(c);
}
static public JPanel withSideMargin(int w, Component c) {
return withLeftAndRightMargin(w, c);
}
static public JPanel withSideMargin(int w1, int w2, Component c) {
return withLeftAndRightMargin(w1, w2, c);
}
static public JScrollPane borderlessScrollPane(JScrollPane sp) {
return setBorder(null, withoutViewportBorder(sp));
}
static public JScrollPane jHigherScrollPane(final JComponent c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c) {
public Dimension getPreferredSize() {
Component view = getViewport().getView();
if (view == null)
return super.getPreferredSize();
int pref_width = view.getPreferredSize().width;
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
Dimension dim = new Dimension(pref_width, super.getPreferredSize().height + getHorizontalScrollBar().getSize().height);
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
return dim;
}
};
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JScrollPane(c) {\r\n public Dimension getPreferredSize() {\r\n Co...";
}
});
}
static public JPanel jfullcenter(Component c) {
return jFullCenter(c);
}
static public JPanel vstack(Object... parts) {
return vstack2(parts);
}
static public JPanel vstack(List parts) {
return vstack(toObjectArray(parts));
}
static public JPanel hstack(Object... parts) {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.gridheight = GridBagConstraints.REMAINDER;
smartAddWithLayout(panel, gbc, parts);
gbc.weightx = 1;
panel.add(jrigid(), gbc);
return panel;
}
static public JCheckBox dm_rcheckBox(String field) {
return dm_fieldCheckBox(field);
}
static public JCheckBox dm_rcheckBox(String field, String text) {
return dm_fieldCheckBox(text, field);
}
static public JComponent withLabelToTheRight(JComponent component, String label) {
return centerAndEast(component, jlabel(" " + label));
}
static public JComponent withLabelToTheRight(String label, JComponent component) {
return withLabelToTheRight(component, label);
}
static public JSpinner dm_spinner(String field, int min, int max) {
return liveValueSpinner(dm_fieldLiveValue(field), min, max);
}
static public JSpinner dm_powersOfTwoSpinner(String field, int max) {
SimpleLiveValue lv = dm_fieldLiveValue(field);
return bindLiveValueToSpinner(lv, jPowersOfTwoSpinner(max, lv.get()));
}
static public Component verticalStrut(int height) {
return Box.createVerticalStrut(height);
}
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 setHorizontalMarginForAllButtons(int margin, Component c) {
for (var btn : allButtons(c)) setHorizontalMargin(btn, margin);
}
static public void setHorizontalMarginForAllButtons(Component c, int margin) {
setHorizontalMarginForAllButtons(margin, c);
}
static public String nFrames(long n) {
return n2(n, "frame");
}
static public String nFrames(Collection l) {
return nFrames(l(l));
}
static public String nFrames(Map map) {
return nFrames(l(map));
}
static public String n2(long l) {
return formatWithThousands(l);
}
static public String n2(AtomicLong l) {
return n2(l.get());
}
static public String n2(Collection l) {
return n2(l(l));
}
static public String n2(Map map) {
return n2(l(map));
}
static public String n2(double l, String singular) {
return empty(singular) ? str(l) : n2(l, singular, singular + "s");
}
static public String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static public String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(long l, String singular) {
return empty(singular) ? n2(l) : n_fancy2(l, singular, singular + "s");
}
static public String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static public String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static public String n2(Map m, String singular) {
return n2(l(m), singular);
}
static public String n2(long[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
static public String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static public void setEnclosingTabTitle(JComponent c, String title) {
swing(() -> {
Pair p = enclosingTab(c);
if (p == null)
return;
setTabTitle(p.a, p.b, title);
});
}
static public String nRegions(long n) {
return n2(n, "region");
}
static public String nRegions(Collection l) {
return nRegions(l(l));
}
static public String nRegions(Map map) {
return nRegions(l(map));
}
static public String lines(Iterable lines) {
return fromLines(lines);
}
static public String lines(Object[] lines) {
return fromLines(asList(lines));
}
static public List lines(String s) {
return toLines(s);
}
static public String lines(Iterable l, IF1 f) {
return mapToLines(l, f);
}
static public List ciSorted(Collection c) {
return sortedIgnoreCase(c);
}
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 double nsToMicroseconds(double ns) {
return nanosToMicroseconds(ns);
}
static public String microSymbol() {
return "\u00B5";
}
static public boolean isShowing(Component c) {
return isComponentShowing(c);
}
static public BufferedImage whiteImage(int w, int h) {
return newBufferedImage(w, h, Color.white);
}
static public BufferedImage whiteImage(int size) {
return whiteImage(size, size);
}
static public Map createGraphics_modulators = synchroIdentityHashMap();
static public Graphics2D createGraphics(BufferedImage img) {
Graphics2D g = img.createGraphics();
Object mod = createGraphics_modulators.get(img);
if (mod != null)
callF(mod, g);
return g;
}
static public void createGraphics_modulate(BufferedImage img, Object mod) {
mapPut2(createGraphics_modulators, img, mod);
}
static public BWIntegralImage bwIntegralImage_withMeta(BufferedImage img) {
return setMetaSrc(bwIntegralImage(img), img);
}
static public BWIntegralImage bwIntegralImage_withMeta(BWImage img) {
return setMetaSrc(bwIntegralImage(img), img);
}
static public JPanel centerAndSouthWithMargin(Component c, Component s) {
return centerAndSouth(c, withTopMargin(s));
}
static public JPanel centerAndSouthWithMargin(int margin, Component c, Component s) {
return centerAndSouth(c, withTopMargin(margin, s));
}
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 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 int vstackWithSpacing_default = 10;
static public JPanel vstackWithSpacing(final List parts) {
return vstackWithSpacing(parts, vstackWithSpacing_default);
}
static public JPanel vstackWithSpacing(final List parts, final int spacing) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(spacing / 2, 0, (spacing + 1) / 2, 0);
smartAddWithLayout(panel, gbc, toObjectArray(nonNulls(parts)));
gbc.weighty = 1;
gbc.insets = new Insets(0, 0, 0, 0);
panel.add(jrigid(), gbc);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new GridBagLayout);\r\n new GridBagConstraints gbc...";
}
});
}
static public JPanel vstackWithSpacing(Component... parts) {
return vstackWithSpacing(asList(parts), vstackWithSpacing_default);
}
static public JPanel vstackWithSpacing(int spacing, Component... parts) {
return vstackWithSpacing(asList(parts), spacing);
}
static public Class mc() {
return main.class;
}
static public String printLog() {
return getPrintLog();
}
static public A setBounds(final int x, final int y, final int w, final int h, final A a) {
if (a != null) {
swing(() -> {
a.setBounds(x, y, w, h);
});
}
return a;
}
static public A setBounds(A a, Rect r) {
if (a != null && r != null) {
swing(() -> {
a.setBounds(toRectangle(r));
});
}
return a;
}
static public A setBounds(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 A onBoundsChange(A c, final Object r) {
if (c != null && r != null) {
swing(() -> {
c.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
pcallF(r);
}
public void componentMoved(ComponentEvent e) {
pcallF(r);
}
});
});
}
return c;
}
static public A onBoundsChange(Object r, A c) {
return onBoundsChange(c, r);
}
static public boolean isMain() {
return isMainProgram();
}
static public List cdelete(Class c, Object... params) {
return deleteConcepts(c, params);
}
static public void cdelete(Concept c) {
deleteConcept(c);
}
static public void cdelete(Collection c) {
for (A a : cloneList(c)) cdelete(a);
}
static public boolean isExtendedStateNormal(JFrame f) {
return f != null && swing(() -> f.getExtendedState() == JFrame.NORMAL);
}
static public void maximizeOrRestoreFrame(JFrame f) {
if (f == null)
return;
if (!isExtendedStateNormal(f)) {
swing(() -> {
f.setExtendedState(JFrame.NORMAL);
});
} else
maximizeFrame(f);
}
static public A onFirstShowing(A component, Runnable onShow) {
return onFirstComponentShow(component, onShow);
}
static public boolean swingConfirm(Component owner, String msg) {
return confirmOKCancel(owner, msg);
}
static public boolean swingConfirm(String msg) {
return confirmOKCancel(msg);
}
static public List flattenToList(Object... l) {
Flattener f = new Flattener();
f.add(l);
return f.toList();
}
static public A setAlwaysOnTop(A c) {
return alwaysOnTop(c);
}
static public BufferedImage shootWindow(Window w) {
w.toFront();
sleep(50);
return shootScreen2(w.getBounds());
}
static public Object ccallOpt(Concept.Ref ref, String method, Object... args) {
return callOptWithEnter(cDeref(ref), method, args);
}
static public Object ccallOpt(Object object, String method, Object... args) {
return callOptWithEnter(object, method, args);
}
static public A fontSizePlus(final int delta, final A c) {
if (c != null) {
swing(() -> {
Font font = c.getFont();
c.setFont(font.deriveFont(font.getSize2D() + delta));
});
}
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(() -> {
a.setBackground(color);
a.setOpaque(true);
a.putClientProperty("substancelaf.colorizationFactor", 1.0);
});
}
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 A maximizeFrame(A c) {
JFrame f = swing(new F0() {
public JFrame get() {
try {
JFrame f = getFrame(c);
if (f != null)
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JFrame f = getFrame(c);\r\n if (f != null)\r\n f.setExtendedState(JFrame....";
}
});
if (f != null && !isAWTThread()) {
Dimension d = maximumWindowBounds().getSize();
long start = sysNow();
while (licensed()) {
try {
if (f.getWidth() >= d.getWidth() - 100 && f.getHeight() >= d.getHeight() - 100)
break;
if (sysNow() >= start + 100) {
warn("maximizeFrame timeout");
break;
}
} catch (Throwable __e) {
printStackTrace(__e);
}
sleep(1);
}
}
return c;
}
static public Object swing(Object f) {
return swingAndWait(f);
}
static public void swing(Runnable f) {
swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public 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 String appendWithColon(String s) {
return prependColonSpaceIfNempty(s);
}
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 printStackTrace(A e) {
if (e != null)
print(getStackTrace(e));
return e;
}
static public void printStackTrace() {
printStackTrace(new Throwable());
}
static public void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static public void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static public void setFrameContents(final Component c, final Object contents) {
swing(() -> {
JFrame frame = getFrame(c);
if (frame == null)
return;
frame.getContentPane().removeAll();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrap(contents));
revalidate(frame);
});
}
static public BufferedImage renderComponentToImage(final Component c) {
if (c == null)
return null;
return swing(new F0() {
public BufferedImage get() {
try {
int w = getWidth(c), h = getHeight(c);
BufferedImage img = newBufferedImage(w, h);
c.paint(createGraphics(img));
return img;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "int w = getWidth(c), h = getHeight(c);\r\n BufferedImage img = newBufferedIm...";
}
});
}
static public A copyImageToClipboard(A img) {
TransferableImage trans = new TransferableImage(img);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
vmBus_send("newClipboardContents", img);
print("Copied image to clipboard (" + img.getWidth(null) + "*" + img.getHeight(null) + " px)");
return img;
}
static public File saveInImageDirectoryWithCounter(String subPath, BufferedImage img) {
if (img == null)
return null;
assertNempty(subPath);
File dir = imagesDir();
if (!isImageFileName(subPath))
subPath += ".png";
File f = makeFileNameUnique_beforeExtension_startWith1_noDot(newFile(dir, subPath));
saveImage(f, img);
infoBox("Saved image " + appendBracketed(img.getWidth(null) + "*" + img.getHeight(null)) + ": " + fileInfo(f));
return f;
}
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 CleanExit cleanExit(String msg) {
throw new CleanExit(msg);
}
static public CleanExit cleanExit() {
throw new CleanExit();
}
static public String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
static public void hideTrayIcon(TrayIcon t) {
removeTrayIcon(t);
}
static public void systemExit(int code) {
System.exit(code);
}
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 JFastLogView_noWrap showText_fast_noWrap(String title, Object text) {
return showText_fast_noWrap(null, title, text);
}
static public JFastLogView_noWrap showText_fast_noWrap(JFastLogView_noWrap view, String title, Object text) {
if (view != null) {
view.setText(str(text));
return view;
}
view = jFastLogView_noWrap(str(text));
makeFrame(title, jscroll_copyBackground(view));
return view;
}
static public JFastLogView_noWrap showText_fast_noWrap(Object text) {
return showText_fast_noWrap(autoFrameTitle(), text);
}
static public String renderStackTrace(StackTraceElement[] st) {
return stackTraceToString(st);
}
static public String renderStackTrace(Throwable e) {
return stackTraceToString(e);
}
static public String renderStackTrace(String msg) {
return renderStackTrace(new Throwable(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 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 int l(Object[] a) {
return a == null ? 0 : a.length;
}
static public int l(boolean[] a) {
return a == null ? 0 : a.length;
}
static public int l(byte[] a) {
return a == null ? 0 : a.length;
}
static public int l(short[] a) {
return a == null ? 0 : a.length;
}
static public int l(long[] a) {
return a == null ? 0 : a.length;
}
static public int l(int[] a) {
return a == null ? 0 : a.length;
}
static public int l(float[] a) {
return a == null ? 0 : a.length;
}
static public int l(double[] a) {
return a == null ? 0 : a.length;
}
static public int l(char[] a) {
return a == null ? 0 : a.length;
}
static public int l(Collection c) {
return c == null ? 0 : c.size();
}
static public int l(Iterator i) {
return iteratorCount_int_close(i);
}
static public int l(Map m) {
return m == null ? 0 : m.size();
}
static public int l(CharSequence s) {
return s == null ? 0 : s.length();
}
static public long l(File f) {
return f == null ? 0 : f.length();
}
static public int l(Object o) {
return o == null ? 0 : o instanceof String ? l((String) o) : o instanceof Map ? l((Map) o) : o instanceof Collection ? l((Collection) o) : o instanceof Object[] ? l((Object[]) o) : o instanceof boolean[] ? l((boolean[]) o) : o instanceof byte[] ? l((byte[]) o) : o instanceof char[] ? l((char[]) o) : o instanceof short[] ? l((short[]) o) : o instanceof int[] ? l((int[]) o) : o instanceof float[] ? l((float[]) o) : o instanceof double[] ? l((double[]) o) : o instanceof long[] ? l((long[]) o) : (Integer) call(o, "size");
}
static public int l(MultiSet ms) {
return ms == null ? 0 : ms.size();
}
static public int l(IntRange r) {
return r == null ? 0 : r.length();
}
static public long l(LongRange r) {
return r == null ? 0 : r.length();
}
static public double l(DoubleRange r) {
return r == null ? 0 : r.length();
}
static public int l(IntBuffer b) {
return b == null ? 0 : b.size();
}
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 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 List list(Class type) {
return list(type, db_mainConcepts());
}
static public List list(Class type, Concepts cc) {
return cc.list(type);
}
static public List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static public List list(String type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, String type) {
return concepts.list(type);
}
static public 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 programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public String firstIntAsString(String s) {
return jextract("", s);
}
static public long psI(String snippetID) {
return parseSnippetID(snippetID);
}
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 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 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 File programDir_mine;
static public File programDir() {
return programDir(getProgramID());
}
static public File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
if (me) {
String c = caseID();
if (nempty(c))
dir = newFile(dir, c);
}
return dir;
}
static public File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
static public void clearConceptsOf(String progID) {
getProgramFile(progID, "concepts.structure").delete();
getProgramFile(progID, "concepts.structure.gz").delete();
getProgramFile(progID, "idCounter.structure").delete();
}
static public List syncMap(Object f, Map map) {
return syncMap(map, f);
}
static public List syncMap(Map map, Object f) {
return map(cloneLinkedHashMap(map), f);
}
static public Map syncMap() {
return synchroHashMap();
}
static public Map syncMap(Map map) {
return synchronizedMap(map);
}
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 boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
if (m != null)
m.m = new String[] { substring(a, strL(b)) };
return true;
}
static public boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
int n = s.length();
if (y < x)
y = x;
if (y > n)
y = n;
if (x >= y)
return "";
return s.substring(x, y);
}
static public String substring(String s, IntRange r) {
return r == null ? null : substring(s, r.start, r.end);
}
static public String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static public void dm_watchFields(Collection fields, Runnable onChange) {
for (String field : unnullForIteration(fields)) dm_watchField(field, onChange);
}
static public A setMetaSrcUnlessSame(Object b, A a, Object src) {
if (a != b)
setMeta(a, "src", src);
return a;
}
static public BWImage posterizeBWImage(int brightnessLevels, BWImage img) {
if (brightnessLevels >= 256 || img == null)
return img;
byte[] pixels = img.getBytes();
int w = img.getWidth(), h = img.getHeight(), n = pixels.length;
byte[] pixels2 = new byte[n];
double factor1 = doubleRatio(brightnessLevels, 256);
double factor2 = doubleRatio(255, brightnessLevels - 1);
for (int i = 0; i < n; i++) pixels2[i] = (byte) iround(ifloor(ubyteToInt(pixels[i]) * factor1) * factor2);
return new BWImage(w, h, pixels2);
}
static public BWImage scaledBWImageFromBWIntegralImage(int w, BWIntegralImage img) {
return scaledBWImageFromBWIntegralImage(img, w);
}
static public BWImage scaledBWImageFromBWIntegralImage(BWIntegralImage img, int w) {
return scaledBWImageFromBWIntegralImage(img, w, heightForWidth(img, w));
}
static public BWImage scaledBWImageFromBWIntegralImage(BWIntegralImage img, int w, int h) {
byte[] pixels = scaledGrayBytesFromBWIntegralImage(img, w, h);
return new BWImage(w, h, pixels);
}
static public BWImage scaledBWImageFromBWIntegralImage(int w, IBWIntegralImage img) {
return scaledBWImageFromBWIntegralImage(img, w);
}
static public BWImage scaledBWImageFromBWIntegralImage(IBWIntegralImage img, int w) {
return scaledBWImageFromBWIntegralImage(img, w, heightForWidth(img, w));
}
static public BWImage scaledBWImageFromBWIntegralImage(IBWIntegralImage img, int w, int h) {
byte[] pixels = scaledGrayBytesFromBWIntegralImage(img, w, h);
return new BWImage(w, h, pixels);
}
static public A setMetaSrc(A a, Object src) {
setMeta(a, "src", src);
return a;
}
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 double msToSeconds(long ms) {
return toSeconds(ms);
}
static public ImageSurface imageSurface(BufferedImage img) {
return swingNu(ImageSurface.class, img);
}
static public ImageSurface imageSurface(MakesBufferedImage img) {
return swingNu(ImageSurface.class, img);
}
static public ImageSurface imageSurface() {
return swingNu(ImageSurface.class);
}
static public void imageSurface_pixelated(ImageSurface imageSurface) {
if (imageSurface == null)
return;
imageSurface.setDoubleBuffered(true);
imageSurface.noAlpha = true;
imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR;
repaint(imageSurface);
}
static public void imageSurface_pixelated(ImageSurface imageSurface, boolean pixelated) {
if (pixelated)
imageSurface_pixelated(imageSurface);
else
imageSurface_unpixelated(imageSurface);
}
static public BufferedImage toBufferedImage(Object o) {
return toBufferedImageOpt(o);
}
static public void swingEvery(JComponent component, long delay, Object r) {
installTimer(component, delay, r);
}
static public void swingEvery(JComponent component, long delay, long firstDelay, Object r) {
installTimer(component, r, delay, firstDelay);
}
static public void swingEvery(RootPaneContainer frame, long delay, Object r) {
installTimer(frame, delay, r);
}
static public void swingEvery(RootPaneContainer frame, long delay, long firstDelay, Object r) {
installTimer(frame, delay, firstDelay, r);
}
static public A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static public A toolTipFromLiveValue(LiveValue lv, A c) {
return bindToolTipToLiveValue(lv, c);
}
static public LiveValue dm_transientCalculatedLiveValue(Class type, IF0 calc) {
return dm_transientCalculatedLiveValue(dm_current_mandatory(), type, calc);
}
static public LiveValue dm_transientCalculatedLiveValue(DynModule mod, Class type, IF0 calc) {
Lock __0 = mod.lock;
lock(__0);
try {
SimpleLiveValue value = new SimpleLiveValue(type, calc.get());
mod.onFieldChange(new VF1() {
public void get(String field) {
try {
value.set(calc.get());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "value.set(calc!)";
}
});
return value;
} finally {
unlock(__0);
}
}
static public LiveValue dm_transientCalculatedLiveValue(IF0 calc) {
return dm_transientCalculatedLiveValue(Object.class, calc);
}
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 JTabbedPane jLeftOrTopTabs(boolean horizontal, Object... x) {
return horizontal ? jLeftTabs(x) : jtabs(x);
}
static public JTabbedPane jLeftOrTopTabs(boolean horizontal, Collection c) {
return horizontal ? jLeftTabs(c) : jtabs(c);
}
static public JPanel jRightAlignedButtons(Object... params) {
List l = new ArrayList();
for (int i = 0; i < l(params); i += 2) if (params[i] != null)
if (params[i] instanceof JComponent)
l.add((JComponent) params[i--]);
else
l.add(jbutton((String) params[i], params[i + 1]));
return jRightAlignedLine(l);
}
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 JPanel marginPanel() {
return jtransparent(borderLayoutPanel());
}
static public A setBorder(Border border, A c) {
if (c != null) {
swing(() -> {
c.setBorder(border);
});
}
return c;
}
static public JScrollPane withoutViewportBorder(JScrollPane sp) {
if (sp != null) {
swing(() -> {
sp.setViewportBorder(null);
});
}
return sp;
}
static public JPanel vstack2(final Object... parts) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
smartAddWithLayout(panel, gbc, parts);
gbc.weighty = 1;
panel.add(jrigid(), gbc);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new GridBagLayout);\r\n new GridBagConstraints gbc...";
}
});
}
static public JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
for (Object o : parts) panel.add(wrapForSmartAdd(o), layout);
return panel;
}
static public JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
return smartAddWithLayout(panel, layout, asList(flattenArray2(parts)));
}
static public Component jrigid() {
return javax.swing.Box.createRigidArea(new Dimension(0, 0));
}
static public JSpinner liveValueSpinner(SimpleLiveValue lv, int min, int max) {
JSpinner spinner = jSpinner(lv.get(), min, max);
return bindLiveValueToSpinner(lv, spinner);
}
static public JSpinner bindLiveValueToSpinner(SimpleLiveValue lv, JSpinner spinner) {
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 JSpinner jPowersOfTwoSpinner(int max, int defaultValue) {
return rightAlignSpinner(jListSpinner(powersOfTwoUpTo(max), defaultValue));
}
static public List allButtons(Component c) {
return childrenOfType(c, JButton.class);
}
static public A setHorizontalMargin(final int margin, final A a) {
{
swing(() -> {
Insets i = a.getMargin();
a.setMargin(new Insets(i.top, margin, i.bottom, margin));
});
}
return a;
}
static public A setHorizontalMargin(A a, int margin) {
return setHorizontalMargin(margin, a);
}
static public String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
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 String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public double fraction(double d) {
return d % 1;
}
static public String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
static public String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
static public String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
static public String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
static public String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
static public Pair enclosingTab(Component _c) {
return swing(() -> {
Component c = _c;
while (c != null) {
Container p = c.getParent();
if (p instanceof JTabbedPane)
return pair(((JTabbedPane) p), ((JTabbedPane) p).indexOfComponent(c));
c = c.getParent();
}
return null;
});
}
static public void setTabTitle(JTabbedPane tabs, int idx, String title) {
if (tabs != null && idx >= 0) {
swing(() -> {
if (idx < tabs.getTabCount())
tabs.setTitleAt(idx, title);
});
}
}
static public String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
static public String fromLines(String... lines) {
return fromLines(asList(lines));
}
static public 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 IterableIterator toLines(File f) {
return linesFromFile(f);
}
static public List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
static public int toLines_nextLineBreak(String s, int start) {
int n = s.length();
for (int i = start; i < n; i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static public List mapToLines(Map map) {
List l = new ArrayList();
for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
return l;
}
static public String mapToLines(Map map, Object f) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Map map) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Iterable l) {
return lines(map(f, l));
}
static public String mapToLines(Iterable l, IF1 f) {
return mapToLines((Object) f, l);
}
static public String mapToLines(IF1 f, Iterable l) {
return mapToLines((Object) f, l);
}
static public String mapToLines(Map map, IF2 f) {
return lines(map(map, f));
}
static public String mapToLines(IF1 f, A data1, A... moreData) {
return lines(map(f, data1, moreData));
}
static public List sortedIgnoreCase(Collection c) {
List l = cloneList(c);
Collections.sort(l, caseInsensitiveComparator());
return l;
}
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 double nanosToMicroseconds(double ns) {
return ns / 1000;
}
static public boolean isComponentShowing(final Component c) {
return c != null && swing(new F0() {
public Boolean get() {
try {
return c.isShowing();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.isShowing();";
}
});
}
static public BufferedImage newBufferedImage(int w, int h) {
return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}
static public BufferedImage newBufferedImage(int w, int h, RGB rgb) {
return newBufferedImage(w, h, rgb.getColor());
}
static public BufferedImage newBufferedImage(int w, int h, Color color) {
BufferedImage img = newBufferedImage(w, h);
Graphics2D g = img.createGraphics();
g.setColor(or(color, Color.white));
g.fillRect(0, 0, w, h);
return img;
}
static public BufferedImage newBufferedImage(Pt p, Color color) {
return newBufferedImage(p.x, p.y, color);
}
static public BufferedImage newBufferedImage(int w, int h, int[] pixels) {
return intArrayToBufferedImage(pixels, w, h);
}
static public Map synchroIdentityHashMap() {
return synchroMap(new IdentityHashMap());
}
static public void mapPut2(Map map, A key, B value) {
if (map != null && key != null)
if (value != null)
map.put(key, value);
else
map.remove(key);
}
static public BWIntegralImage bwIntegralImage(BufferedImage img) {
return img == null ? null : new BWIntegralImage(img);
}
static public BWIntegralImage bwIntegralImage(BWImage img) {
return img == null ? null : new BWIntegralImage(img);
}
static public List nonNulls(Iterable l) {
return withoutNulls(l);
}
static public List nonNulls(A[] l) {
return withoutNulls(l);
}
static public Map nonNulls(Map map) {
return withoutNulls(map);
}
static public Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public void pcallF(VF1 f, A a) {
try {
{
if (f != null)
f.get(a);
}
} catch (Throwable __e) {
printStackTrace(__e);
}
}
static public Object pcallF(Runnable r) {
try {
{
if (r != null)
r.run();
}
return null;
} catch (Throwable __e) {
return null;
}
}
static public A pcallF(IF0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(IF1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public boolean isMainProgram() {
return creator() == null;
}
static public void deleteConcepts(Collection conceptsOrIDs) {
db_mainConcepts().deleteConcepts(asList(conceptsOrIDs));
}
static public List deleteConcepts(Class c, Object... params) {
return deleteConcepts(db_mainConcepts(), c, params);
}
static public List deleteConcepts(Concepts cc, Class c, Object... params) {
List l = asList(findConceptsWhere(cc, c, params));
deleteConcepts(l);
return l;
}
static public void deleteConcepts(Class c, IF1 pred) {
deleteConcepts(db_mainConcepts(), c, pred);
}
static public void deleteConcepts(Concepts cc, Class c, IF1 pred) {
deleteConcepts(filter(list(cc, c), pred));
}
static public List deleteConcepts(Concepts cc) {
return deleteConcepts(cc, Concept.class);
}
static public void deleteConcept(long id) {
db_mainConcepts().deleteConcept(id);
}
static public void deleteConcept(Concepts concepts, long id) {
concepts.deleteConcept(id);
}
static public void deleteConcept(Concept c) {
if (c != null)
c.delete();
}
static public void deleteConcept(Concept.Ref ref) {
if (ref != null)
deleteConcept(ref.get());
}
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 A onFirstComponentShow(final A component, final Runnable onShow) {
{
swing(() -> {
component.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
component.removeAncestorListener(this);
pcallF(onShow);
}
public void ancestorRemoved(AncestorEvent event) {
}
public void ancestorMoved(AncestorEvent event) {
}
});
});
}
return component;
}
static public boolean confirmOKCancel(final Component owner, final String msg) {
return isTrue(swingAndWait(new F0() {
public Object get() {
try {
return JOptionPane.showConfirmDialog(owner, msg, "JavaX", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret JOptionPane.showConfirmDialog(owner,\r\n msg, \"JavaX\", JOptionPane.OK_...";
}
}));
}
static public boolean confirmOKCancel(String msg) {
return confirmOKCancel(null, msg);
}
static volatile public boolean sleep_noSleep = false;
static public void sleep(long ms) {
ping();
if (ms < 0)
return;
if (isAWTThread() && ms > 100)
throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public void sleep() {
try {
if (sleep_noSleep)
throw fail("nosleep");
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object callOptWithEnter(Object o, String method, String[] arg) {
return callOptWithEnter(o, method, new Object[] { arg });
}
static public Object callOptWithEnter(Object o, String method, Object... args) {
if (o == null)
return null;
AutoCloseable __1 = tempEnter(o);
try {
return callOpt_withVarargs(o, method, args);
} finally {
_close(__1);
}
}
static public A cDeref(Concept.Ref ref) {
return ref == null ? null : ref.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 Rectangle maximumWindowBounds() {
return maxWindowBounds();
}
static volatile public boolean licensed_yes = true;
static public boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
static public void licensed_off() {
licensed_yes = false;
}
static public void 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 String prependColonSpaceIfNempty(String s) {
return empty(s) ? "" : ": " + s;
}
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 A revalidate(final A c) {
if (c == null || !c.isShowing())
return c;
{
swing(() -> {
c.revalidate();
c.repaint();
});
}
return c;
}
static public void revalidate(JFrame f) {
revalidate((Component) f);
}
static public void revalidate(JInternalFrame f) {
revalidate((Component) f);
}
static public int getWidth(Component c) {
return c == null ? 0 : (int) swingCall(c, "getWidth");
}
static public int getHeight(Component c) {
return c == null ? 0 : (int) swingCall(c, "getHeight");
}
static public void 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 A assertNempty(A a) {
return assertNempty("empty", a);
}
static public A assertNempty(String msg, A a) {
if (empty(a))
throw fail(msg + ": " + a);
return a;
}
static public File imagesDir() {
return userDir_oneOf_createIfNone("Pictures", "OneDrive/Pictures", "OneDrive/Bilder", "Pictures", "Bilder");
}
static public File imagesDir(String sub) {
return newFile(imagesDir(), sub);
}
static public boolean isImageFileName(String s) {
return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif");
}
static public File makeFileNameUnique_beforeExtension_startWith1_noDot(File f) {
File orig = f;
int n = 1;
do {
f = appendToFileBaseName(orig, str(n++));
} while (f.exists());
return f;
}
static public File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static public File newFile(String name) {
return name == null ? null : new File(name);
}
static public File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static public void saveImage(File f, BufferedImage img) {
if (hasJPEGExtension(f))
saveJPG(f, img);
else
savePNG(f, img);
}
static public String appendBracketed(Object o) {
String b = strOrNull(o);
return empty(b) ? "" : "" + " (" + b + ")";
}
static public String appendBracketed(String a, String b) {
return a + appendBracketed(b);
}
static public String fileInfo(File f) {
return renderFileInfo(f);
}
static public String fileInfo(String f) {
return renderFileInfo(newFile(f));
}
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 void removeTrayIcon(final TrayIcon t) {
if (t != null) {
swing(() -> {
SystemTray.getSystemTray().remove(t);
});
}
}
static public JFastLogView_noWrap jFastLogView_noWrap() {
return jFastLogView_noWrap("");
}
static public JFastLogView_noWrap jFastLogView_noWrap(String text) {
return withTypeWriterFont(swingNu(JFastLogView_noWrap.class, text));
}
static public JScrollPane jscroll_copyBackground(Component c) {
return setScrollPaneBackground(getBackground(c), jscroll(c));
}
static public String stackTraceToString(StackTraceElement[] st) {
return lines(st);
}
static public String stackTraceToString(Throwable e) {
return getStackTrace_noRecord(e);
}
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 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 int iteratorCount_int_close(Iterator i) {
try {
int n = 0;
if (i != null)
while (i.hasNext()) {
i.next();
++n;
}
if (i instanceof AutoCloseable)
((AutoCloseable) i).close();
return n;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Pair mapEntryToPair(Map.Entry e) {
return e == null ? null : pair(e.getKey(), e.getValue());
}
static public Set> entrySet(Map map) {
return _entrySet(map);
}
static public A firstThat(Iterable l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(A[] l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public A firstThat(IF1 pred, A[] l) {
return firstThat(l, pred);
}
static public String defaultThreadName_name;
static public String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static public Runnable wrapAsActivity(Object r) {
if (r == null)
return null;
Runnable r2 = toRunnable(r);
Object mod = dm_current_generic();
if (mod == null)
return r2;
return new Runnable() {
public void run() {
try {
AutoCloseable c = (AutoCloseable) (rcall("enter", mod));
AutoCloseable __1 = c;
try {
r2.run();
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable c = (AutoCloseable) (rcall enter(mod));\r\n temp c;\r\n r2.r...";
}
};
}
static public Thread newThread(Object runnable) {
return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)));
}
static public Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static public Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
static public Runnable toRunnable(final Object o) {
if (o instanceof Runnable)
return (Runnable) o;
if (o instanceof String)
throw fail("callF_legacy");
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
static public Map _registerThread_threads;
static public Object _onRegisterThread;
static public Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static public void _registerThread() {
_registerThread(Thread.currentThread());
}
static public 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 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 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 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());
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
static public String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
static public String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static public String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static public String 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 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 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 String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static volatile public String caseID_caseID;
static public String caseID() {
return caseID_caseID;
}
static public void caseID(String id) {
caseID_caseID = id;
}
static public File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
static public File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
static public LinkedHashMap cloneLinkedHashMap(Map map) {
return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
}
static public Map synchroHashMap() {
return synchronizedMap(new HashMap());
}
static public Map synchronizedMap() {
return synchroMap();
}
static public Map synchronizedMap(Map map) {
return synchroMap(map);
}
static public void _onJavaXSet() {
}
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 int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
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 void setMeta(IMeta o, Object key, Object value) {
metaMapPut(o, key, value);
}
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 byte[] scaledGrayBytesFromBWIntegralImage(int w, BWIntegralImage img) {
return scaledGrayBytesFromBWIntegralImage(img, w);
}
static public byte[] scaledGrayBytesFromBWIntegralImage(BWIntegralImage img, int w) {
return scaledGrayBytesFromBWIntegralImage(img, w, heightForWidth(img, w));
}
static public byte[] scaledGrayBytesFromBWIntegralImage(BWIntegralImage img, int w, int h) {
int w1 = img.getWidth(), h1 = img.getHeight();
double stepX = doubleRatio(w1, w), stepY = doubleRatio(h1, h);
byte[] pixels = new byte[w * h];
int i = 0;
double srcY = 0;
for (int y = 0; y < h; y++) {
double srcX = 0, nextSrcY = srcY + stepY;
for (int x = 0; x < w; x++) {
double nextSrcX = srcX + stepX;
int pixel = iround(img.getPixelAverage(srcX, srcY, nextSrcX, nextSrcY));
pixels[i++] = clampToUByte(pixel);
srcX = nextSrcX;
}
srcY = nextSrcY;
}
return pixels;
}
static public byte[] scaledGrayBytesFromBWIntegralImage(int w, IBWIntegralImage img) {
return scaledGrayBytesFromBWIntegralImage(img, w);
}
static public byte[] scaledGrayBytesFromBWIntegralImage(IBWIntegralImage img, int w) {
return scaledGrayBytesFromBWIntegralImage(img, w, heightForWidth(img, w));
}
static public byte[] scaledGrayBytesFromBWIntegralImage(IBWIntegralImage img, int w, int h) {
int w1 = img.getWidth(), h1 = img.getHeight();
double stepX = doubleRatio(w1, w), stepY = doubleRatio(h1, h);
byte[] pixels = new byte[w * h];
int i = 0;
double srcY = 0;
for (int y = 0; y < h; y++) {
double srcX = 0, nextSrcY = srcY + stepY;
for (int x = 0; x < w; x++) {
double nextSrcX = srcX + stepX;
int pixel = iround(img.getPixelAverage(srcX, srcY, nextSrcX, nextSrcY));
pixels[i++] = clampToUByte(pixel);
srcX = nextSrcX;
}
srcY = nextSrcY;
}
return pixels;
}
static public double parseDouble(String s) {
return empty(s) ? 0.0 : Double.parseDouble(s);
}
static public A repaint(A c) {
if (c != null)
c.repaint();
return c;
}
static public void imageSurface_unpixelated(ImageSurface imageSurface) {
if (imageSurface == null)
return;
imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_BILINEAR;
repaint(imageSurface);
}
static public BufferedImage toBufferedImageOpt(Object o) {
if (o instanceof BufferedImage)
return ((BufferedImage) o);
if (o instanceof Image)
return copyImage((Image) o);
if (o instanceof MakesBufferedImage)
return ((MakesBufferedImage) o).getBufferedImage();
if (o instanceof File)
if (isImageFile((File) o))
return loadBufferedImageFile((File) o);
String c = getClassName(o);
if (eqOneOf(c, "main$BWImage", "main$RGBImage"))
return (BufferedImage) call(o, "getBufferedImage");
if (eq(c, "main$PNGFile"))
return (BufferedImage) call(o, "getImage");
return null;
}
static public A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () {
public A get() {
try {
return nuObject(c, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret nuObject(c, args);";
}
});
}
static public A bindToolTipToLiveValue(LiveValue lv, A c) {
bindLiveValueListenerToComponent(c, lv, new Runnable() {
public void run() {
try {
setToolTipText(c, strOrNull(lv.get()));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "setToolTipText(c, strOrNull(lv!))";
}
});
return c;
}
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 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 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 JTabbedPane jLeftTabs(Object... x) {
JTabbedPane tabs = jtabs(x);
tabs.setTabPlacement(JTabbedPane.LEFT);
return tabs;
}
static public JTabbedPane jLeftTabs(Collection c) {
return jLeftTabs(toObjectArray(c));
}
static public JTabbedPane jtabs(Object... x) {
return fillJTabs(swingNu(JTabbedPane.class), x);
}
static public JPanel jRightAlignedLine(Component... components) {
return jrightAlignedLine(components);
}
static public JPanel jRightAlignedLine(List extends Component> components) {
return jrightAlignedLine(components);
}
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 A jtransparent(final A a) {
{
swing(() -> {
a.setOpaque(false);
});
}
return a;
}
static public JPanel borderLayoutPanel() {
return jpanel(new BorderLayout());
}
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(JSpinner s, int value) {
setSpinnerValue(s, (Integer) value);
}
static public void setSpinnerValue(JSpinner s, Object value) {
try {
if (s != null) {
swing(() -> {
s.setValue(value);
});
}
} catch (Throwable __e) {
printStackTrace(__e);
}
}
static public JSpinner rightAlignSpinner(JSpinner spinner) {
setHorizontalAlignment(JTextField.RIGHT, getTextFieldFromSpinner(spinner));
return spinner;
}
static public JSpinner jListSpinner(List entries, A defaultValue) {
return swing(() -> {
JSpinner s = new JSpinner();
s.setModel(new SpinnerListModel(entries));
if (contains(entries, defaultValue))
setSpinnerValue(s, defaultValue);
return s;
});
}
static public List powersOfTwoUpTo(int n) {
IntBuffer l = new IntBuffer();
int i = 1;
while (i <= n && i > 0) {
l.add(i);
i *= 2;
}
return l.asVirtualList();
}
static public String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(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 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 CloseableIterableIterator linesFromFile(File f) {
return linesFromFile(f, null);
}
static public CloseableIterableIterator linesFromFile(File f, IResourceHolder resourceHolder) {
try {
if (!f.exists())
return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)), resourceHolder);
return linesFromReader(utf8bufferedReader(f), resourceHolder);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public CloseableIterableIterator linesFromFile(String path) {
return linesFromFile(path, null);
}
static public CloseableIterableIterator linesFromFile(String path, IResourceHolder resourceHolder) {
return linesFromFile(newFile(path), resourceHolder);
}
static public Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keys(Object map) {
return keys((Map) map);
}
static public Set keys(MultiSet ms) {
return ms.keySet();
}
static public Set keys(MultiMap mm) {
return mm.keySet();
}
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 A or(A a, A b) {
return a != null ? a : b;
}
static public BufferedImage intArrayToBufferedImage(int[] pixels, int w, int h) {
int[] bitMasks = new int[] { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 };
SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, w, h, bitMasks);
DataBufferInt db = new DataBufferInt(pixels, pixels.length);
WritableRaster wr = Raster.createWritableRaster(sm, db, new Point());
return new BufferedImage(ColorModel.getRGBdefault(), wr, false, null);
}
static public Map synchroMap() {
return synchroHashMap();
}
static public Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static public List withoutNulls(Iterable l) {
if (l instanceof List)
if (!containsNulls((List) l))
return ((List) l);
List l2 = new ArrayList();
for (A a : l) if (a != null)
l2.add(a);
return l2;
}
static public Map withoutNulls(Map map) {
Map map2 = similarEmptyMap(map);
for (A a : keys(map)) if (a != null) {
B b = map.get(a);
if (b != null)
map2.put(a, b);
}
return map2;
}
static public List withoutNulls(A[] l) {
List l2 = new ArrayList();
if (l != null)
for (A a : l) if (a != null)
l2.add(a);
return l2;
}
static public Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
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 Object sleepQuietly_monitor = new Object();
static public void sleepQuietly() {
try {
assertFalse(isAWTThread());
synchronized (sleepQuietly_monitor) {
sleepQuietly_monitor.wait();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public AutoCloseable tempEnter(Object o) {
return o == null ? null : optCast(AutoCloseable.class, rcallOpt("enter", o));
}
static public AutoCloseable tempEnter(Enterable o) {
return o == null ? null : o.enter();
}
static public Object callOpt_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me == null) {
return null;
}
if ((me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 (isSnippetID(snippetIDOrURLOrFile)) {
String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return loadBufferedImage(rl.loadLibrary(snippetID));
File dir = imageSnippetsCacheDir();
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
try {
return ImageIO.read(file);
} catch (Throwable e) {
e.printStackTrace();
}
}
String imageURL = snippetImageURL_http(snippetID);
print("Loading image: " + imageURL);
BufferedImage image = imageIO_readURL(imageURL);
if (loadBufferedImage_useImageCache) {
File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
ImageIO.write(image, "png", tempFile);
tempFile.renameTo(new File(dir, snippetID + ".png"));
}
return image;
} else
return loadBufferedImage(new File(snippetIDOrURLOrFile));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public BufferedImage loadBufferedImage(File file) {
return loadBufferedImageFile(file);
}
static public Rectangle maxWindowBounds() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
}
static public void ping_okInCleanUp() {
}
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 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 File userDir_oneOf_createIfNone(String ifNone, String... names) {
return or(userDir_oneOf(names), userDir(ifNone));
}
static public boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x))
return true;
return false;
}
static public String fileExtension(File f) {
if (f == null)
return null;
return fileExtension(f.getName());
}
static public String fileExtension(String s) {
return substring(s, smartLastIndexOf(s, '.'));
}
static public boolean hasJPEGExtension(File f) {
return ewicOneOf(fileName(f), ".jpg", ".jpeg");
}
static public void saveJPG(BufferedImage img, File file) {
try {
if (!ImageIO.write(img, "jpeg", mkdirsFor(file))) {
print("Reconstructing image for saving JPEG");
img = reconstructBufferedImage(img);
if (!ImageIO.write(img, "jpeg", file))
throw fail("Couldn't write JPEG: " + file + " (" + img + ")");
}
vmBus_send("wroteFile", file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void saveJPG(File file, BufferedImage img) {
try {
saveJPG(img, file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void savePNG(BufferedImage img, File file) {
try {
File tempFile = new File(file.getPath() + "_temp");
CriticalAction ca = beginCriticalAction("Save " + f2s(file));
try {
ImageIO.write(img, "png", mkdirsFor(tempFile));
file.delete();
tempFile.renameTo(file);
} finally {
ca.done();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void savePNG(String file, BufferedImage img) {
savePNG(toFile(file), img);
}
static public void savePNG(File file, BufferedImage img) {
savePNG(img, file);
}
static public void savePNG(File file, RGBImage img) {
savePNG(file, img.getBufferedImage());
}
static public String strOrNull(Object o) {
return o == null ? null : str(o);
}
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 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 JScrollPane setScrollPaneBackground(Color c, JScrollPane sp) {
if (sp != null && c != null) {
swing(() -> {
sp.getViewport().setBackground(c);
});
}
return sp;
}
static public Color getBackground(final Component c) {
return c == null ? null : swing(new F0() {
public Color get() {
try {
return c.getBackground();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getBackground();";
}
});
}
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 Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
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 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 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 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 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 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 String _userHome;
static public String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
static public File userHome(String path) {
return new File(userDir(), path);
}
static public File getProgramDir() {
return programDir();
}
static public File getProgramDir(String snippetID) {
return programDir(snippetID);
}
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 byte clampToUByte(long l) {
return (byte) clamp(l, 0, 255);
}
static public BufferedImage copyImage(Image img) {
if (img == null)
return null;
if (img instanceof BufferedImage)
return copyImage((BufferedImage) img);
int w = img.getWidth(null), h = img.getHeight(null);
BufferedImage bi = newBufferedImage(w, h);
drawImage(bi, img);
return bi;
}
static public BufferedImage copyImage(BufferedImage bi) {
if (bi == null)
return null;
ColorModel cm = bi.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = bi.copyData(bi.getRaster().createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
static public boolean isImageFile(File f) {
return isImageFileName(fileName(f));
}
static public BufferedImage loadBufferedImageFile(File file) {
try {
return isFile(file) ? ImageIO.read(file) : null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
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 setToolTipText(final A c, final Object toolTip) {
if (c == null)
return null;
{
swing(() -> {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
});
}
return c;
}
static public A setToolTipText(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
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 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 Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static public JPanel jpanel(LayoutManager layout) {
return swingNu(JPanel.class, layout);
}
static public JPanel jpanel() {
return swingNu(JPanel.class);
}
static public JSpinner jSpinnerCommitOnValidEdit(JSpinner spinner) {
var tf = getTextFieldFromSpinner(spinner);
if (tf != null) {
swing(() -> {
DefaultFormatter formatter = (DefaultFormatter) (tf.getFormatter());
if (formatter != null)
formatter.setCommitsOnValidEdit(true);
});
}
return spinner;
}
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 JFormattedTextField getTextFieldFromSpinner(JSpinner spinner) {
return spinner == null ? null : swing(() -> ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField());
}
static public CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
public Object next() {
throw fail();
}
public boolean hasNext() {
return false;
}
};
static public CloseableIterableIterator emptyCloseableIterableIterator() {
return emptyCloseableIterableIterator_instance;
}
static public 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 CloseableIterableIterator linesFromReader(Reader r) {
return linesFromReader(r, null);
}
static public CloseableIterableIterator linesFromReader(Reader r, IResourceHolder resourceHolder) {
final BufferedReader br = bufferedReader(r);
return holdResource(resourceHolder, iteratorFromFunction_f0_autoCloseable(new F0() {
public String get() {
try {
return readLineFromReaderWithClose(br);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret readLineFromReaderWithClose(br);";
}
}, _wrapIOCloseable(r)));
}
static public BufferedReader utf8bufferedReader(InputStream in) {
try {
return in == null ? null : bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public BufferedReader utf8bufferedReader(File f) {
try {
return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
static public GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
static public 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 boolean containsNulls(Collection c) {
return contains(c, null);
}
static public Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static public void assertFalse(Object o) {
if (!(eq(o, false)))
throw fail(str(o));
}
static public boolean assertFalse(boolean b) {
if (b)
throw fail("oops");
return b;
}
static public boolean assertFalse(String msg, boolean b) {
if (b)
throw fail(msg);
return b;
}
static public A optCast(Class c, Object o) {
return isInstance(c, o) ? (A) o : null;
}
static final public Map callOpt_cache = newDangerousWeakHashMap();
static public Object callOpt_cached(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null)
return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public _MethodCache callOpt_getCache(Class c) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
static public Object invokeMethod(Method m, Object o, Object... args) {
try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 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(() -> {
l.setVerticalTextPosition(SwingConstants.BOTTOM);
l.setHorizontalTextPosition(SwingConstants.CENTER);
});
}
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 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 Runnable asRunnable(Object o) {
return toRunnable(o);
}
static public void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
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 File userDir_oneOf(String... names) {
return oneOfTheFilesInDir(userDir(), names);
}
static public File userDir() {
return new File(userHome());
}
static public File userDir(String path) {
return new File(userHome(), path);
}
static public int smartLastIndexOf(String s, char c) {
if (s == null)
return 0;
int i = s.lastIndexOf(c);
return i >= 0 ? i : l(s);
}
static public int smartLastIndexOf(List l, A sub) {
int i = lastIndexOf(l, sub);
return i < 0 ? l(l) : i;
}
static public String fileName(File f) {
return f == null ? null : f.getName();
}
static public BufferedImage reconstructBufferedImage(BufferedImage img) {
if (img == null)
return null;
RGBImage rgb = new RGBImage(img);
rgb.uncacheBufferedImage();
return rgb.getBufferedImage();
}
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 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 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 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 Set synchroHashSet() {
return synchronizedSet(new HashSet ());
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
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 ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
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 actualUserHome_value;
static public String actualUserHome() {
if (actualUserHome_value == null) {
if (isAndroid())
actualUserHome_value = "/storage/emulated/0/";
else
actualUserHome_value = System.getProperty("user.home");
}
return actualUserHome_value;
}
static public File actualUserHome(String sub) {
return newFile(new File(actualUserHome()), sub);
}
static public float clamp(float x, float a, float b) {
return x < a ? a : x > b ? b : x;
}
static public double clamp(double x, double a, double b) {
return x < a ? a : x > b ? b : x;
}
static public int clamp(int x, int a, int b) {
return x < a ? a : x > b ? b : x;
}
static public long clamp(long x, long a, long b) {
return x < a ? a : x > b ? b : x;
}
static public BufferedImage drawImage(BufferedImage canvas, Image img, Pt p) {
return drawImageOnImage(img, canvas, p.x, p.y);
}
static public void drawImage(BufferedImage g, Image img) {
drawImage(graphics(g), img);
}
static public void drawImage(Graphics2D g, Image img) {
drawImage(g, img, 0, 0);
}
static public void drawImage(Graphics2D g, Image img, Pt p) {
drawImage(g, img, p.x, p.y);
}
static public void drawImage(Graphics2D g, Image img, int x, int y) {
{
if (g != null)
g.drawImage(img, x, y, null);
}
}
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 Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static public Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static public Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static public List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static public boolean 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 String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static public Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
static public List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
static public void clearTabs(final JTabbedPane tabs) {
if (tabs != null) {
swing(() -> {
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(() -> {
tabs.add(title, wrap(c));
});
}
}
static public void addTab(JTabbedPane tabs, String title, Swingable c) {
if (tabs != null) {
swing(() -> {
tabs.add(title, wrap(c));
});
}
}
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 boolToInt(boolean b) {
return b ? 1 : 0;
}
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 BufferedReader bufferedReader(Reader r) {
return bufferedReader(r, 8192);
}
static public BufferedReader bufferedReader(Reader r, int bufSize) {
if (r == null)
return null;
return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r, bufSize), r);
}
static public A holdResource(IResourceHolder holder, A a) {
{
if (holder != null)
holder.add(a);
}
return a;
}
static public CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) {
class IFF2 extends CloseableIterableIterator {
public A a;
public boolean done = false;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
return _a;
}
public void getNext() {
if (done || a != null)
return;
a = f.get();
done = a == null;
}
public void close() throws Exception {
if (closeable != null)
closeable.close();
}
}
;
return new IFF2();
}
static public String readLineFromReaderWithClose(BufferedReader r) {
try {
String s = r.readLine();
if (s == null)
r.close();
return s;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
return c == null ? null : new AutoCloseable() {
public String toString() {
return "c.close();\r\n _registerIO(c, null, false);";
}
public void close() throws Exception {
c.close();
_registerIO(c, null, false);
}
};
}
static public A _registerIOWrap(A wrapper, Object wrapped) {
return wrapper;
}
static public FileInputStream newFileInputStream(File path) throws IOException {
return newFileInputStream(path.getPath());
}
static public FileInputStream newFileInputStream(String path) throws IOException {
FileInputStream f = new FileInputStream(path);
_registerIO(f, path, true);
return f;
}
static public int gzInputStream_defaultBufferSize = 65536;
static public GZIPInputStream gzInputStream(File f) {
try {
return gzInputStream(new FileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public GZIPInputStream gzInputStream(File f, int bufferSize) {
try {
return gzInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public GZIPInputStream gzInputStream(InputStream in) {
return gzInputStream(in, gzInputStream_defaultBufferSize);
}
static public GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
try {
return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
static public List classNames(Collection l) {
return getClassNames(l);
}
static public List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
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 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 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 public Throwable _storeException_value;
static public void _storeException(Throwable e) {
_storeException_value = e;
}
static public File oneOfTheFilesInDir(File dir, String... names) {
return oneOfTheFiles(map(names, name -> newFile(dir, name)));
}
static public int lastIndexOf(String a, String b) {
return a == null || b == null ? -1 : a.lastIndexOf(b);
}
static public int lastIndexOf(String a, char b) {
return a == null ? -1 : a.lastIndexOf(b);
}
static public int lastIndexOf(List l, int i, A a) {
if (l == null)
return -1;
for (i = min(l(l), i) - 1; i >= 0; i--) if (eq(l.get(i), a))
return i;
return -1;
}
static public int lastIndexOf(List l, A a) {
if (l == null)
return -1;
for (int i = l(l) - 1; i >= 0; i--) if (eq(l.get(i), a))
return i;
return -1;
}
static public List synchroList() {
return synchroList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public List collect(Iterable c, String field) {
return collectField(c, field);
}
static public List collect(String field, Iterable c) {
return collectField(c, field);
}
static public void sleepInCleanUp(long ms) {
try {
if (ms < 0)
return;
Thread.sleep(ms);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 Set listFields(Object c) {
TreeSet fields = new TreeSet();
for (Field f : _getClass(c).getDeclaredFields()) fields.add(f.getName());
return fields;
}
static public boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(Object... c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public 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 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 String dropSuffix(String suffix, String s) {
return nempty(suffix) && endsWith(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public BufferedImage drawImageOnImage(Image img, BufferedImage canvas, int x, int y) {
createGraphics(canvas).drawImage(img, x, y, null);
return canvas;
}
static public Graphics2D graphics(BufferedImage img) {
return imageGraphics(img);
}
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 boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean isEmpty(Object[] a) {
return a == null || a.length == 0;
}
static public boolean isEmpty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static public boolean isEmpty(DoubleRange r) {
return r == null || r.isEmpty();
}
static public 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 A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
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 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 File oneOfTheFiles(String... paths) {
if (paths != null)
for (String path : paths) if (fileExists(path))
return newFile(path);
return null;
}
static public File oneOfTheFiles(File... files) {
return oneOfTheFiles(asList(files));
}
static public File oneOfTheFiles(Iterable files) {
if (files != null)
for (File f : files) if (fileExists(f))
return f;
return null;
}
static public List collectField(Iterable c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
static public List collectField(String field, Iterable c) {
return collectField(c, field);
}
static public char stringToChar(String s) {
if (l(s) != 1)
throw fail("bad stringToChar: " + s);
return firstChar(s);
}
static public boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
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 long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
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 ThreadLocal imageGraphics_antiAlias = new ThreadLocal();
static public Graphics2D imageGraphics(BufferedImage img) {
return !isFalse(imageGraphics_antiAlias.get()) ? antiAliasGraphics(img) : createGraphics(img);
}
static public ClassLoader classLoaderForObject(Object o) {
if (o instanceof ClassLoader)
return ((ClassLoader) o);
if (o == null)
return null;
return _getClass(o).getClassLoader();
}
static public String classNameToVM(String name) {
return name.replace(".", "$");
}
static public File loadImageAsFile(String snippetIDOrURL) {
try {
if (isURL(snippetIDOrURL))
throw fail("not implemented");
if (!isSnippetID(snippetIDOrURL))
throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
String snippetID = "" + parseSnippetID(snippetIDOrURL);
File file = imageSnippetCacheFile(snippetID);
if (fileSize(file) > 0)
return file;
String imageURL = snippetImageURL_noHttps(snippetID);
System.err.println("Loading image: " + imageURL);
byte[] data = loadBinaryPage(imageURL);
saveBinaryFile(file, data);
return file;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = DiskSnippetCache_file(snippetID);
return file.exists() ? file : null;
}
public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(DiskSnippetCache_file(snippetID), data);
}
static public byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL(dataSnippetLink(snippetID));
print("Loading library: " + hideCredentials(url));
try {
data = loadBinaryPage(url.openConnection());
} catch (RuntimeException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID));
print("Loading library: " + hideCredentials(url));
data = loadBinaryPage(url.openConnection());
}
print("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
static public long fileSize(String path) {
return getFileSize(path);
}
static public long fileSize(File f) {
return getFileSize(f);
}
static public File loadDataSnippetToFile(String snippetID) {
try {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
return loadDataSnippetToFile_noResourceLoader(snippetID);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File loadDataSnippetToFile_noResourceLoader(String snippetID) {
try {
snippetID = fsI(snippetID);
File f = DiskSnippetCache_file(parseSnippetID(snippetID));
List urlsTried = new ArrayList();
List errors = new ArrayList();
try {
URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
print("Loading library: " + hideCredentials(url));
try {
loadBinaryPageToFile(openConnection(url), f);
if (fileSize(f) == 0)
throw fail();
} catch (Throwable e) {
errors.add(e);
url = addAndReturn(urlsTried, new URL(tb_mainServer() + "/blobs/" + psI(snippetID)));
print(e);
print("Trying other server: " + hideCredentials(url));
loadBinaryPageToFile(openConnection(url), f);
print("Got bytes: " + fileSize(f));
}
if (fileSize(f) == 0)
throw fail();
System.err.println("Bytes loaded: " + fileSize(f));
} catch (Throwable e) {
errors.add(e);
throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
}
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] isGIF_magic = bytesFromHex("47494638");
static public boolean isGIF(byte[] data) {
return byteArrayStartsWith(data, isGIF_magic);
}
static public boolean isGIF(File f) {
return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
}
static public void setVar(IVar v, A value) {
if (v != null)
v.set(value);
}
static public IVF1 setVar(IVar v) {
return a -> {
if (v != null)
v.set(a);
};
}
static public boolean possibleMD5(String s) {
return isMD5(s);
}
static public boolean fileExists(String path) {
return path != null && new File(path).exists();
}
static public boolean fileExists(File f) {
return f != null && f.exists();
}
static public char firstChar(String s) {
return s.charAt(0);
}
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 Graphics2D antiAliasGraphics(BufferedImage img) {
return antiAliasOn(createGraphics(img));
}
static public File imageSnippetCacheFile(String snippetID) {
File dir = imageSnippetsCacheDir();
if (!loadBufferedImage_useImageCache)
return null;
return new File(dir, parseSnippetID(snippetID) + ".png");
}
static public String snippetImageURL_noHttps(String snippetID) {
return snippetImageURL_noHttps(snippetID, "png");
}
static public String snippetImageURL_noHttps(String snippetID, String contentType) {
return snippetImageURL(snippetID, contentType).replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/").replace("https://botcompany.de/", "http://botcompany.de/");
}
static public ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal();
static public ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal();
static public byte[] loadBinaryPage(String url) {
try {
print("Loading " + url);
return loadBinaryPage(loadPage_openConnection(new URL(url)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] loadBinaryPage(URLConnection con) {
try {
Map extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders);
setHeaders(con);
for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
return loadBinaryPage_noHeaders(con);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] loadBinaryPage_noHeaders(URLConnection con) {
try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
InputStream inputStream = con.getInputStream();
loadBinaryPage_responseHeaders.set(con.getHeaderFields());
long len = 0;
try {
len = con.getContentLength();
} catch (Throwable e) {
printStackTrace(e);
}
int n = 0;
while (true) {
int ch = inputStream.read();
if (ch < 0)
break;
buf.write(ch);
if (++n % 100000 == 0)
println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
}
inputStream.close();
return buf.toByteArray();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static byte[] saveBinaryFile(String fileName, byte[] contents) {
try {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
FileOutputStream fileOutputStream = newFileOutputStream(tempFileName);
fileOutputStream.write(contents);
fileOutputStream.close();
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
vmBus_send("wroteFile", file);
return contents;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] saveBinaryFile(File fileName, byte[] contents) {
return saveBinaryFile(fileName.getPath(), contents);
}
static public File getGlobalCache() {
File file = new File(javaxCachesDir(), "Binary Snippets");
file.mkdirs();
return file;
}
static public String dataSnippetLink(String snippetID) {
long id = parseSnippetID(snippetID);
if (id >= 1100000 && id < 1200000)
return imageServerURL() + id;
if (id >= 1200000 && id < 1300000) {
String pw = muricaPassword();
if (empty(pw))
throw fail("Please set 'murica password by running #1008829");
return "https://botcompany.de/files/" + id + "?_pass=" + pw;
}
return fileServerURL() + "/" + id;
}
static public String tb_mainServer_default = "https://code.botcompany.de:9898";
static public Object tb_mainServer_override;
static public String tb_mainServer() {
if (tb_mainServer_override != null)
return (String) callF(tb_mainServer_override);
return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default));
}
static public File tb_mainServer_file() {
return getProgramFile("#1001638", "mainserver.txt");
}
static public boolean tb_mainServer_isDefault() {
return eq(tb_mainServer(), tb_mainServer_default);
}
static public A addAndReturn(Collection c, A a) {
if (c != null)
c.add(a);
return a;
}
static public List allToString(Iterable c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
static public List allToString(Object[] c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
static public boolean byteArrayStartsWith(byte[] a, byte[] b) {
if (a == null || b == null)
return false;
if (a.length < b.length)
return false;
for (int i = 0; i < b.length; i++) if (a[i] != b[i])
return false;
return true;
}
static public byte[] loadBeginningOfBinaryFile(File file, int maxBytes) {
return loadBinaryFilePart(file, 0, maxBytes);
}
static public boolean isMD5(String s) {
return l(s) == 32 && isLowerHexString(s);
}
static public A[] arrayOfSameType(A[] a, int n) {
return newObjectArrayOfSameType(a, n);
}
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 Graphics2D antiAliasOn(Graphics2D g) {
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
return g;
}
static public int loadPage_defaultTimeout = 60000;
static public ThreadLocal loadPage_charset = new ThreadLocal();
static public boolean loadPage_allowGzip = true, loadPage_debug;
static public boolean loadPage_anonymous = false;
static public int loadPage_verboseness = 100000;
static public int loadPage_retries = 1;
static public ThreadLocal loadPage_silent = new ThreadLocal();
static volatile public int loadPage_forcedTimeout;
static public ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal();
static public ThreadLocal>> loadPage_responseHeaders = new ThreadLocal();
static public ThreadLocal> loadPage_extraHeaders = new ThreadLocal();
static public ThreadLocal loadPage_sizeLimit = new ThreadLocal();
public static String loadPageSilently(String url) {
try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadPageSilently(URL url) {
try {
if (!networkAllowanceTest(str(url)))
throw fail("Not allowed: " + url);
IOException e = null;
for (int tries = 0; tries < loadPage_retries; tries++) try {
URLConnection con = loadPage_openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPage_debug)
print(exceptionToStringShort(e));
if (tries < loadPage_retries - 1)
sleepSeconds(1);
}
throw e;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage_preprocess(String url) {
if (url.startsWith("tb/"))
url = tb_mainServer() + "/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
static public String loadPage(String url) {
try {
url = loadPage_preprocess(url);
if (!isTrue(loadPage_silent.get()))
printWithTime("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage(URL url) {
return loadPage(url.toExternalForm());
}
static public String loadPage(URLConnection con, URL url) throws IOException {
return loadPage(con, url, true);
}
static public String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
Long limit = optPar(loadPage_sizeLimit);
if (addHeaders)
try {
if (!loadPage_anonymous)
setHeaders(con);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
con.setRequestProperty("X-No-Cookies", "1");
for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
} catch (Throwable e) {
}
vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
loadPage_responseHeaders.set(con.getHeaderFields());
InputStream in = null;
try {
in = urlConnection_getInputStream(con);
if (loadPage_debug)
print("Put stream in map: " + currentThread());
String contentType = con.getContentType();
if (contentType == null) {
throw new IOException("Page could not be read: " + hideCredentials(url));
}
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null)
charset = loadPage_guessCharset(contentType);
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = newGZIPInputStream(in);
}
Reader r;
try {
r = new InputStreamReader(in, unquote(charset));
} catch (UnsupportedEncodingException e) {
print(toHex(utf8(charset)));
throw e;
}
boolean silent = isTrue(loadPage_silent.get());
StringBuilder buf = new StringBuilder();
int n = 0;
while (limit == null || n < limit) {
ping();
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
if (!silent && (n % loadPage_verboseness) == 0)
print(" " + n + " chars read");
}
return buf.toString();
} finally {
if (loadPage_debug)
print("loadPage done");
vm_generalSubMap("URLConnection per thread").remove(currentThread());
if (in != null)
in.close();
}
}
static public String loadPage_guessCharset(String contentType) {
Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
String match = m.matches() ? m.group(1) : null;
if (loadPage_debug)
print("loadPage: contentType=" + contentType + ", match: " + match);
return or(match, "UTF-8");
}
static public URLConnection loadPage_openConnection(URL url) {
URLConnection con = openConnection(url);
int timeout = toInt(loadPage_forcedTimeout_byThread.get());
if (timeout == 0)
timeout = loadPage_forcedTimeout;
if (timeout != 0)
setURLConnectionTimeouts(con, loadPage_forcedTimeout);
else
setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
return con;
}
static public A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
static public A println(A a) {
return print(a);
}
static public String imageServerURL() {
return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/");
}
static volatile public boolean muricaPassword_pretendNotAuthed = false;
static public String muricaPassword() {
if (muricaPassword_pretendNotAuthed)
return null;
return trim(loadTextFile(muricaPasswordFile()));
}
static public String fileServerURL() {
return "https://botcompany.de/files";
}
static public byte[] loadBinaryFilePart(File file, long start, long end) {
try {
RandomAccessFile raf = new RandomAccessFile(file, "r");
int n = toInt(min(raf.length(), end - start));
byte[] buffer = new byte[n];
try {
raf.seek(start);
raf.readFully(buffer, 0, n);
return buffer;
} finally {
raf.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isLowerHexString(String s) {
for (int i = 0; i < l(s); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
} else
return false;
}
return true;
}
static public A[] newObjectArrayOfSameType(A[] a) {
return newObjectArrayOfSameType(a, a.length);
}
static public A[] newObjectArrayOfSameType(A[] a, int n) {
return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
}
static public boolean networkAllowanceTest(String url) {
return isAllowed("networkAllowanceTest", url);
}
static public void sleepSeconds(double s) {
if (s > 0)
sleep(round(s * 1000));
}
static public A printWithTime(A a) {
return printWithTime("", a);
}
static public A printWithTime(String s, A a) {
print(hmsWithColons() + ": " + s, a);
return a;
}
static public A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
static public A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
static public Object optPar(Object[] params, String name) {
return optParam(params, name);
}
static public Object optPar(String name, Object[] params) {
return optParam(params, name);
}
static public Object optPar(String name, Map params) {
return optParam(name, params);
}
static public A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public Map vm_generalSubMap(Object name) {
synchronized (vm_generalMap()) {
Map map = (Map) (vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = synchroMap());
return map;
}
}
static public InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
return con.getInputStream();
}
static public String unquote(String s) {
if (s == null)
return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i + 1, s.length() - i - 1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
StringBuilder sb = new StringBuilder(l - 1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\'':
ch = '\'';
break;
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s;
}
static public String toHex(byte[] bytes) {
return bytesToHex(bytes);
}
static public String toHex(byte[] bytes, int ofs, int len) {
return bytesToHex(bytes, ofs, len);
}
static public byte[] utf8(String s) {
return toUtf8(s);
}
static public Matcher regexpMatcher(String pat, String s) {
return compileRegexp(pat).matcher(unnull(s));
}
static public URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) {
con.setConnectTimeout(toInt(timeout));
con.setReadTimeout(toInt(timeout));
if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
print("Warning: Timeouts not set by JDK.");
return con;
}
static public URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
if (con.getConnectTimeout() == 0) {
con.setConnectTimeout(toInt(timeout));
if (con.getConnectTimeout() != timeout)
print("Warning: URL connect timeout not set by JDK.");
}
if (con.getReadTimeout() == 0) {
con.setReadTimeout(toInt(timeout));
if (con.getReadTimeout() != timeout)
print("Warning: URL read timeout not set by JDK.");
}
return con;
}
static public File muricaPasswordFile() {
return new File(javaxSecretDir(), "murica/muricaPasswordFile");
}
static volatile public Object isAllowed_function;
static volatile public boolean isAllowed_all = true;
static public boolean isAllowed(String askingMethod, Object... args) {
Object f = vm_generalMap_get("isAllowed_function");
if (f != null && !isTrue(callF(f, askingMethod, args)))
return false;
return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
}
static public long round(double d) {
return Math.round(d);
}
static public String round(String s) {
return roundBracket(s);
}
static public Complex round(Complex c) {
return new Complex(round(c.re), round(c.im));
}
static public String hmsWithColons() {
return hmsWithColons(now());
}
static public String hmsWithColons(long time) {
return new SimpleDateFormat("HH:mm:ss").format(time);
}
static public A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static public A optParam(ThreadLocal tl) {
return optPar(tl);
}
static public Object optParam(String name, Map params) {
return mapGet(params, name);
}
static public A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt)))
throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
return (A) opt[i + 1];
return defaultValue;
}
static public Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
static public Object optParam(String name, Object[] params) {
return optParam(params, name);
}
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len * 2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs + i]);
stringBuilder.append(s.substring(s.length() - 2, s.length()));
}
return stringBuilder.toString();
}
static public byte[] toUtf8(String s) {
try {
return s.getBytes(utf8charset());
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map compileRegexp_cache = syncMRUCache(10);
static public java.util.regex.Pattern compileRegexp(String pat) {
java.util.regex.Pattern p = compileRegexp_cache.get(pat);
if (p == null) {
compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat));
}
return p;
}
static public File javaxSecretDir_dir;
static public File javaxSecretDir() {
return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
}
static public File javaxSecretDir(String sub) {
return newFile(javaxSecretDir(), sub);
}
static public String roundBracket(String s) {
return "(" + s + ")";
}
static public String roundBracket(Object s) {
return roundBracket(str(s));
}
static public B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
static public B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
static public boolean even(int i) {
return (i & 1) == 0;
}
static public boolean even(long i) {
return (i & 1) == 0;
}
static public boolean even(BigInteger n) {
return even(n.intValue());
}
static public Charset utf8charset_cache;
static public Charset utf8charset() {
if (utf8charset_cache == null)
utf8charset_cache = utf8charset_load();
return utf8charset_cache;
}
static public Charset utf8charset_load() {
return Charset.forName("UTF-8");
}
static public Map syncMRUCache(int size) {
return synchroMap(new MRUCache(size));
}
static abstract public class VF2 {
abstract public void get(A a, B b);
}
static public class RollingAverage {
public int windowSize = 50;
public int recalcEvery = 1000;
public int nRecalc;
public double sum;
public double[] list;
public int start, len;
public RollingAverage() {
}
public RollingAverage(int windowSize) {
this.windowSize = windowSize;
}
synchronized public void add(double d) {
init();
if (++nRecalc >= recalcEvery) {
nRecalc = 0;
sum = 0;
for (int i = 0; i < len; i++) sum += _get(i);
}
if (len == windowSize) {
sum -= _get(0);
len--;
start = (start + 1) % windowSize;
}
list[(start + len) % windowSize] = d;
++len;
sum += d;
}
public double _get(int i) {
return list[(start + i) % windowSize];
}
synchronized public double get() {
init();
return doubleRatio(sum, len);
}
public void init() {
if (list == null)
list = new double[windowSize];
}
}
static public class ImageSurface_HighlightRegion extends ImageSurfaceMouseHandler implements G2Drawable {
final public ImageSurface_HighlightRegion setRegionPainter(RegionPainter regionPainter) {
return regionPainter(regionPainter);
}
public ImageSurface_HighlightRegion regionPainter(RegionPainter regionPainter) {
this.regionPainter = regionPainter;
return this;
}
final public RegionPainter getRegionPainter() {
return regionPainter();
}
public RegionPainter regionPainter() {
return regionPainter;
}
public RegionPainter regionPainter = new RegionBoundingBoxPainter();
public FastRegions_BWImage regions;
public int iHighlightedRegion;
public Pt lastPt;
public ImageSurface_HighlightRegion(ImageSurface is) {
if (containsInstance(is.tools, getClass()))
return;
register(is);
is.overlays.add(this);
}
public void close() {
super.close();
is.overlays.remove(this);
}
final public void mouseEntered(MouseEvent e) {
mouseMoved(e);
}
public void mouseMoved(MouseEvent e) {
lastPt = getPt(e);
update();
}
public void mouseExited(MouseEvent e) {
lastPt = null;
update();
}
public int newRegion() {
if (lastPt == null || regions == null)
return 0;
return regions.regionAt(lastPt.x, lastPt.y);
}
public void update() {
int r = newRegion();
if (iHighlightedRegion != r) {
iHighlightedRegion = r;
is.repaint();
}
}
public void setRegions(FastRegions_BWImage regions) {
this.regions = regions;
iHighlightedRegion = -abs(iHighlightedRegion);
update();
}
public void drawOn(Graphics2D g) {
if (iHighlightedRegion == 0 || regionPainter == null)
return;
regionPainter.zoomX(is.getZoomX());
regionPainter.zoomY(is.getZoomY());
regionPainter.g(g);
AutoCloseable __1 = tempAfterwards(new Runnable() {
public void run() {
try {
regionPainter.g(null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "regionPainter.g(null);";
}
});
try {
regionPainter.regions(regions).iRegion(iHighlightedRegion);
regionPainter.drawRegion();
} finally {
_close(__1);
}
}
}
static public class Var implements IVar , ISetter {
public Var() {
}
public Var(A v) {
this.v = v;
}
public A v;
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() {
return v;
}
public synchronized boolean has() {
return v != null;
}
public void clear() {
set(null);
}
public String toString() {
return str(this.get());
}
}
static public class RegionFillPainter extends RegionPainter {
public void drawRegion() {
Area area = regionToArea(regions, iRegion);
g.setColor(withOpacity(.5, Color.green));
g.scale(zoomX, zoomY);
fillShape(g, area);
}
}
static public class BetterThread extends Thread {
public Runnable target;
public BetterThread(Runnable target) {
this.target = target;
_created();
}
public BetterThread(Runnable target, String name) {
super(name);
this.target = target;
_created();
}
public void _created() {
vmBus_send("threadCreated", this);
}
public void run() {
try {
try {
vmBus_send("threadStarted", this);
if (target != null)
target.run();
} finally {
vmBus_send("threadEnded", this);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Runnable getTarget() {
return target;
}
}
static public class AnimatedLine extends Animation {
public int maxSpeed = 1;
public int y, speed;
public void start() {
y = random(h);
newSpeed();
}
public void newSpeed() {
speed = random_incl(-maxSpeed, maxSpeed);
}
public void paint() {
fillRect(g, 0, 0, w, h, Color.white);
drawLine(g, 0, y, w, y, Color.black);
}
public void nextFrame() {
if (oneIn(20))
newSpeed();
y = clamp(y + speed, 0, h - 1);
}
}
static public class CleanExit extends RuntimeException {
public CleanExit() {
}
public CleanExit(String msg) {
super(msg);
}
}
static public class ImageSurface_PositionToolTip extends ImageSurfaceMouseHandler {
public ImageSurface_PositionToolTip(ImageSurface is) {
if (containsInstance(is.tools, ImageSurface_PositionToolTip.class))
return;
register(is);
}
final public void mouseDragged(MouseEvent e) {
mouseMoved(e);
}
public void mouseMoved(MouseEvent e) {
setToolTip(is, getPt(e));
}
}
static public interface IResourceLoader {
public String loadSnippet(String snippetID);
public String getTranspiled(String snippetID);
public int getSnippetType(String snippetID);
public String getSnippetTitle(String snippetID);
public File loadLibrary(String snippetID);
default public File pathToJavaXJar() {
return pathToJavaxJar_noResourceLoader();
}
default public File getSnippetJar(String snippetID, String transpiledSrc) {
return null;
}
}
static public class ReliableSingleThread implements Runnable {
public boolean _isTransient() {
return true;
}
public Object runnable;
public String name = "Single Thread";
public boolean cancelBeforeTrigger = false;
public boolean waitBetweenCancelAndTrigger = false;
public F0 enter;
public int cancelTimeOut = 10000;
public boolean trigger = false;
public Thread thread;
public WeakReference threadBeingCancelled;
public List inserts = syncL();
public ReliableSingleThread(Object runnable) {
this.runnable = runnable;
}
public void trigger() {
go();
}
synchronized public void go() {
if (cancelBeforeTrigger)
cancelAndPossiblyWait();
trigger = true;
if (!running()) {
AutoCloseable __1 = callF(enter);
try {
thread = startThread(name, new Runnable() {
public void run() {
try {
AutoCloseable __2 = callF(enter);
try {
_run();
} finally {
_close(__2);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp callF(enter);\r\n _run();";
}
});
} finally {
_close(__1);
}
}
}
public void run() {
go();
}
public void get() {
go();
}
synchronized public boolean running() {
return thread != null;
}
public void triggerAndWait() {
trigger();
waitUntilDone();
}
public void waitUntilDone() {
while (running()) sleep(1);
}
public void _run() {
try {
while (licensed()) {
Thread oldThread;
synchronized (this) {
var currentInserts = syncGetAndClear(inserts);
pcallFAll(currentInserts);
if (!trigger) {
thread = null;
break;
}
oldThread = getWeakRef(threadBeingCancelled);
trigger = false;
}
if (oldThread != null && oldThread != currentThread())
oldThread.join(cancelTimeOut);
pcallF(runnable);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
synchronized public void cancel() {
if (thread == null)
return;
threadBeingCancelled = new WeakReference(thread);
cancelAndInterruptThread(thread);
thread = null;
}
public void cancelAndWait() {
Thread _thread;
synchronized (this) {
if (thread == null)
return;
_thread = thread;
threadBeingCancelled = new WeakReference(thread);
thread = null;
}
cancelAndInterruptThread(_thread);
}
public void cancelAndTrigger() {
cancelAndPossiblyWait();
trigger();
}
synchronized public boolean triggered() {
return trigger;
}
public void cleanMeUp() {
cancel();
}
public ReliableSingleThread cancelBeforeTrigger() {
cancelBeforeTrigger = true;
return this;
}
public void cancelAndPossiblyWait() {
if (waitBetweenCancelAndTrigger)
cancel();
}
public void insert(Runnable r) {
inserts.add(r);
trigger();
}
}
static public class JFastLogView_noWrap extends JComponent implements Scrollable {
public List lines = syncList();
public boolean endsWithNewLine, verbose;
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return (direction == SwingConstants.HORIZONTAL ? visibleRect.width : visibleRect.height) * 5 / 6;
}
public boolean getScrollableTracksViewportWidth() {
return false;
}
public boolean getScrollableTracksViewportHeight() {
return false;
}
public void paint(Graphics g) {
int w = getWidth(), h = getHeight();
g.setColor(getBackground());
g.fillRect(0, 0, w, h);
g.setColor(getForeground());
FontMetrics fm = componentFontMetrics(this);
int fh = fm.getHeight();
Rectangle clip = g.getClipBounds();
int start, end;
if (clip == null) {
start = 0;
end = l(lines);
} else {
start = max(0, clip.y / fh);
end = min(l(lines), idiv_ceil(clip.y + clip.height, fh));
}
int y = fm.getAscent() + start * fh;
for (int i = start; i < end; i++) {
String s = get(lines, i);
if (s != null)
g.drawString(s, 0, y);
y += fh;
}
}
public Dimension getPreferredSize() {
FontMetrics fm = componentFontMetrics(this);
if (fm == null)
return new Dimension(50, 50);
int fh = fm.getHeight();
int w = 0;
for (int i = 0; i < l(lines); i++) {
String s = get(lines, i);
w = max(w, fm.stringWidth(unnull(s)));
}
return new Dimension(w, fh * l(lines));
}
public JFastLogView_noWrap() {
}
public JFastLogView_noWrap(String text) {
setText(text);
}
{
componentPopupMenuItem(this, "Copy full text", new Runnable() {
public void run() {
try {
copyFullText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyFullText();";
}
});
}
public boolean setLines(Collection lines) {
List newList = asSyncList(lines);
if (eq(this.lines, newList))
return false;
this.lines = newList;
_revalidate(this);
return true;
}
public boolean setText(String text) {
endsWithNewLine = endsWithNewLine(text);
return setLines(lines(text));
}
public void append(String text) {
if (nempty(text))
setText(getText() + text);
}
public String getText() {
return lines_rtrimIf(!endsWithNewLine, cloneList(lines));
}
public void copyFullText() {
copyTextToClipboard(getText());
}
}
static public class proxy_InvocationHandler implements InvocationHandler {
public Object target;
public proxy_InvocationHandler() {
}
public proxy_InvocationHandler(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) {
return call(target, method.getName(), unnull(args));
}
}
static public class UIURLSystem implements IFieldsToList {
public Enterable owner;
public SimpleLiveValue uiURL;
public UIURLSystem() {
}
public UIURLSystem(Enterable owner, SimpleLiveValue uiURL) {
this.uiURL = uiURL;
this.owner = owner;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + owner + ", " + uiURL + ")";
}
public Object[] _fieldsToList() {
return new Object[] { owner, uiURL };
}
transient public Map> uiMap = syncCIMap();
final public UIURLSystem setScp(SingleComponentPanel scp) {
return scp(scp);
}
public UIURLSystem scp(SingleComponentPanel scp) {
this.scp = scp;
return this;
}
final public SingleComponentPanel getScp() {
return scp();
}
public SingleComponentPanel scp() {
return scp;
}
transient public SingleComponentPanel scp;
public JComponent urlBar() {
return withLabel("Show", comboBoxAndButton(onSelectedItem(bindComboBoxToLiveValue(centerComboBox(autoComboBox(url(), cloneKeys(uiMap))), uiURL), url -> showUIURL(url)), "Go", url -> showUIURL(url)));
}
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 __1 = tempEnter(owner);
try {
setURL(trim(url));
go();
} finally {
_close(__1);
}
}
public void go() {
setComponent(scp, renderUIUrl(url()));
}
public String url() {
return uiURL.get();
}
public void setURL(String url) {
uiURL.set(url);
}
public UIURLSystem put(String url, IF0 extends JComponent> maker) {
uiMap.put(url, maker);
return this;
}
}
static public class ScreenCamStream extends SourceTriggeredStream implements Steppable {
final public ScreenCamStream setArea(Rect area) {
return area(area);
}
public ScreenCamStream area(Rect area) {
this.area = area;
return this;
}
final public Rect getArea() {
return area();
}
public Rect area() {
return area;
}
volatile public Rect area = screenBounds(0);
public boolean step() {
if (ended())
return false;
catchError(() -> shootImpl());
return true;
}
public long frameCount() {
return elementCount();
}
public void shootImpl() {
newElement(shootScreen2(area));
}
public void useScreen(int iScreen) {
area = screenBounds_safe(iScreen);
}
}
static public interface IResourceHolder {
public A add(A a);
public Collection takeAll();
}
static public class FunctionTimings {
public Map data = syncMap();
public void time(A function, Runnable r) {
if (r == null)
return;
Average avg = syncMapGetOrCreate(data, function, () -> new Average());
long time = nanoTime();
try {
r.run();
} finally {
time = nanoTime() - time;
avg.add(time);
}
}
public Map get() {
return cloneMap(data);
}
final public void clear() {
reset();
}
public void reset() {
data.clear();
}
public String render() {
return lines(ciSorted(map(get(), (f, avg) -> functionToString(f) + ": " + n2(iround(nsToMicroseconds(avg.get()))) + " " + microSymbol() + "s (" + n2(iround(avg.n())) + ")")));
}
public String functionToString(A f) {
return firstToUpper(str(f));
}
}
static public class Flattener {
public List out = new ArrayList();
public Flattener() {
}
public Flattener(Object... l) {
add(l);
}
public void add(Object o) {
if (o instanceof Object[])
for (var x : ((Object[]) o)) add(x);
else if (o instanceof Iterable)
for (var x : ((Iterable) o)) add(x);
else if (o != null)
out.add(o);
}
public void add(Object... l) {
add((Object) l);
}
public List toList() {
return out;
}
public Object[] toArray() {
return toObjectArray(out);
}
}
static public class TrayIconLastPosition {
public TrayIcon trayIcon;
public WithTimestamp lastPosition;
public TrayIconLastPosition(TrayIcon trayIcon) {
this.trayIcon = trayIcon;
{
if (trayIcon != null)
trayIcon.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
lastPosition = withTimestamp(pt(e.getX(), e.getY()));
}
});
}
}
}
static public class MRUCache extends LinkedHashMap {
public int maxSize = 10;
public MRUCache() {
}
public MRUCache(int maxSize) {
this.maxSize = maxSize;
}
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > maxSize;
}
public Object _serialize() {
return ll(maxSize, cloneLinkedHashMap(this));
}
static public MRUCache _deserialize(List l) {
MRUCache m = new MRUCache();
m.maxSize = (int) first(l);
m.putAll((LinkedHashMap) second(l));
return m;
}
}
static public class TransferableImage implements Transferable {
public Image i;
public TransferableImage(Image i) {
this.i = i;
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (flavor.equals(DataFlavor.imageFlavor) && i != null) {
return i;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] flavors = new DataFlavor[1];
flavors[0] = DataFlavor.imageFlavor;
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
DataFlavor[] flavors = getTransferDataFlavors();
for (int i = 0; i < flavors.length; i++) {
if (flavor.equals(flavors[i])) {
return true;
}
}
return false;
}
}
static public class JGazelleVScriptRunner implements IFieldsToList {
public SimpleLiveValue lvScript;
public JGazelleVScriptRunner() {
}
public JGazelleVScriptRunner(SimpleLiveValue lvScript) {
this.lvScript = lvScript;
}
public Object[] _fieldsToList() {
return new Object[] { lvScript };
}
public GazelleVScript parsedScript;
public GazelleVScript.Run run;
public Object result;
public SingleComponentPanel scpScriptResult = singleComponentPanel();
public WeakVar isScriptResult = new WeakVar();
public WeakVar taResult = new WeakVar();
public JLabel lblScore = jlabel();
public JComponent scriptAndResultPanel() {
return northAndCenter(scriptInputField(), scpScriptResult = singleComponentPanel());
}
public JComponent scriptInputField() {
return withMargin(centerAndEastWithMargin(withLabel("Gazelle V Script:", jLiveTextField(lvScript)), jPopDownButton_noText("Show Scripting Help", runnableThread(new Runnable() {
public void run() {
try {
showText("Gazelle V Scripting Help", GazelleVScript.helpText);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "showText(\"Gazelle V Scripting Help\", GazelleVScript.helpText)";
}
}))));
}
public void showScriptOutput() {
if (result instanceof BWImage) {
showImageResult((BWImage) result);
} else if (result instanceof BufferedImage) {
showImageResult((BufferedImage) result);
} else if (result instanceof Animation) {
showImageResult(((Animation) result).toImage());
} else {
showTextResult(str(result));
}
}
public void showTextResult(String text) {
text = shorten(1000, text);
if (isShowing(taResult.get())) {
setTextKeepCaret(taResult.get(), text);
} else {
var ta = jTextArea_noUndo(text);
scpScriptResult.set(jscroll(ta));
taResult.set(ta);
}
}
public void showImageResult(MakesBufferedImage img) {
showImageResult(toBufferedImage(img));
}
public void showImageResult(BufferedImage img) {
if (img == null)
return;
if (isShowing(isScriptResult.get())) {
isScriptResult.get().setImage(img);
} else {
var is = stdImageSurface();
is.setImage(img);
scpScriptResult.set(jscroll_centered(is));
isScriptResult.set(is);
}
if (isShowing(lblScore)) {
String score = "";
if (sameSize(run.inputImage, img)) {
double distance = bwDistance(toBWImage(run.inputImage), toBWImage(img));
score = "Score: " + formatDoubleX(100 * (1 - distance), 1);
}
setText(lblScore, score);
}
}
public ImageSurface stdImageSurface() {
return pixelatedImageSurface().setAutoZoomToDisplay(true).repaintInThread(false);
}
public void parse() {
parsedScript = new GazelleVScript(lvScript.get());
}
public void runOn(IBWIntegralImage ii) {
run = parsedScript.new Run();
run.setInputImage(ii);
run.setIntegralImage(ii);
run.run();
result = run.result();
}
public void parseAndRunOn(IBWIntegralImage ii) {
try {
parse();
runOn(ii);
} catch (Throwable e) {
result = exceptionToStringShort(e);
printStackTrace(e);
}
showScriptOutput();
}
}
static abstract public class CloseableIterableIterator extends IterableIterator implements AutoCloseable {
public void close() throws Exception {
}
}
static public class BWIntegralImageStream extends SourceTriggeredStream implements Consumer {
public void accept(BufferedImage image) {
catchError(() -> newElement(bwIntegralImage_withMeta(image)));
}
public long frameCount() {
return elementCount();
}
}
static public interface IF2 {
public C get(A a, B b);
}
abstract static public class Animation {
public int w = 128, h = 128;
public double fps = 20;
public Graphics2D g;
public Animation() {
}
public Animation(int w, int h) {
this.h = h;
this.w = w;
}
public void setSize(int w, int h) {
this.w = w;
this.h = h;
}
public void setGraphics(Graphics2D g) {
this.g = g;
}
public void start() {
}
public void paint() {
}
public void nextFrame() {
}
public BufferedImage toImage() {
var img = whiteImage(w, h);
setGraphics(createGraphics(img));
paint();
return img;
}
}
static public class DoubleFPSCounter {
public FPSCounter counter = new FPSCounter();
volatile public double value;
public void inc() {
if (counter.secondsSinceStart() >= 1) {
value = counter.get();
counter = new FPSCounter();
}
counter.inc();
}
public double get() {
return value;
}
}
static public class ScreenSelectorRadioButtons implements Swingable, IFieldsToList {
public SimpleLiveValue lvScreenNr;
public ScreenSelectorRadioButtons() {
}
public ScreenSelectorRadioButtons(SimpleLiveValue lvScreenNr) {
this.lvScreenNr = lvScreenNr;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + lvScreenNr + ")";
}
public Object[] _fieldsToList() {
return new Object[] { lvScreenNr };
}
transient public ButtonGroup radioButtons;
transient public SingleComponentPanel scp;
final public ScreenSelectorRadioButtons setCompactLayout(boolean compactLayout) {
return compactLayout(compactLayout);
}
public ScreenSelectorRadioButtons compactLayout(boolean compactLayout) {
this.compactLayout = compactLayout;
return this;
}
final public boolean getCompactLayout() {
return compactLayout();
}
public boolean compactLayout() {
return compactLayout;
}
public boolean compactLayout = false;
final public ScreenSelectorRadioButtons setHideIfOnlyOne(boolean hideIfOnlyOne) {
return hideIfOnlyOne(hideIfOnlyOne);
}
public ScreenSelectorRadioButtons hideIfOnlyOne(boolean hideIfOnlyOne) {
this.hideIfOnlyOne = hideIfOnlyOne;
return this;
}
final public boolean getHideIfOnlyOne() {
return hideIfOnlyOne();
}
public boolean hideIfOnlyOne() {
return hideIfOnlyOne;
}
public boolean hideIfOnlyOne = false;
final public ScreenSelectorRadioButtons setScreenLabel(String screenLabel) {
return screenLabel(screenLabel);
}
public ScreenSelectorRadioButtons screenLabel(String screenLabel) {
this.screenLabel = screenLabel;
return this;
}
final public String getScreenLabel() {
return screenLabel();
}
public String screenLabel() {
return screenLabel;
}
public String screenLabel = "Screen";
public JComponent visualize() {
return swing(() -> {
if (scp == null) {
scp = singleComponentPanel();
awtEveryAndNow(scp, 5.0, new Runnable() {
public void run() {
try {
updateScreenCount();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "updateScreenCount();";
}
});
}
var n = screenCount();
radioButtons = jRadioButtons(countIteratorAsList(n, i -> (compactLayout ? "" : screenLabel + " ") + (i + 1)));
setRadioButtonToolTips(radioButtons, i -> "Select screen " + (i + 1));
selectRadioButton(radioButtons, lvScreenNr.get());
onRadioButtonChange(radioButtons, i -> lvScreenNr.set(i));
scp.setComponent(compactLayout ? hideIfOnlyOne && n == 1 ? null : hstack(flattenList2(nempty(screenLabel) ? jlabel(screenLabel) : null, buttonsInGroup(radioButtons))) : jline(flattenList2(buttonsInGroup(radioButtons))));
return scp;
});
}
public void updateScreenCount() {
if (radioButtons != null && radioButtons.getButtonCount() != screenCount())
visualize();
}
}
static public class SourceTriggeredStream