Warning : session_start(): open(/var/lib/php/sessions/sess_aqlea4gd4kov33407q7smoa3f7, 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.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.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.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.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.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import static loadableUtils.utils.getExceptionCause;
import static loadableUtils.utils.joinWithSpace;
import static loadableUtils.utils.callF;
import static loadableUtils.utils.javaTok;
import static loadableUtils.utils.jlabel;
import static loadableUtils.utils.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.db;
import loadableUtils.utils.LongRange;
import loadableUtils.utils.IntRange;
import loadableUtils.utils.MultiMap;
import loadableUtils.utils.Meta;
import loadableUtils.utils.SimpleLiveValue;
import loadableUtils.utils.Matrix;
import loadableUtils.utils.F2;
import loadableUtils.utils.RandomAccessAbstractList;
import loadableUtils.utils.IBWIntegralImage;
import loadableUtils.utils.Producer;
import loadableUtils.utils.IntBuffer;
import loadableUtils.utils.AbstractMatrix;
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.score;
import static loadableUtils.utils.stepAll;
import static loadableUtils.utils.infoMessage;
import static loadableUtils.utils.brightnessToRGBA;
import static loadableUtils.utils.rcallOpt;
import static loadableUtils.utils.childrenOfType;
import static loadableUtils.utils.nanoTime;
import static loadableUtils.utils.b;
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.setSCPComponent;
import static loadableUtils.utils.jPopDownButton_noText;
import static loadableUtils.utils.swingLater;
import static loadableUtils.utils.currentImage;
import static loadableUtils.utils.setImage;
import static loadableUtils.utils.getScreenWidth;
import static loadableUtils.utils.tsNow;
import static loadableUtils.utils.dm_reload;
import static loadableUtils.utils.getDBProgramID;
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.toSeconds;
import static loadableUtils.utils.rect;
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.withLeftAndRightMargin;
import static loadableUtils.utils.dm_doEvery;
import static loadableUtils.utils.flattenArray2;
import static loadableUtils.utils.getParent;
import static loadableUtils.utils.strOrEmpty;
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.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.newConceptsWithClassFinder;
import static loadableUtils.utils.joinSubList;
import static loadableUtils.utils.onSelectedItem;
import static loadableUtils.utils.replace;
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.jscroll_centered;
import static loadableUtils.utils.parentFile;
import static loadableUtils.utils.dm_rEnter;
import static loadableUtils.utils.toString;
import static loadableUtils.utils.regionMatches;
import static loadableUtils.utils.bindLiveValueListenerToComponent;
import static loadableUtils.utils.screenBounds;
import static loadableUtils.utils.toRectangle;
import static loadableUtils.utils.widthForHeight;
import static loadableUtils.utils.jLiveValueLabel;
import static loadableUtils.utils.shortClassName_dropNumberPrefix;
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.vmBus_query;
import static loadableUtils.utils.getPreferredSize;
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.plus;
import static loadableUtils.utils.dm_watchField;
import static loadableUtils.utils.ifloor;
import static loadableUtils.utils.repeat;
import static loadableUtils.utils.structureForUser;
import static loadableUtils.utils.asArray;
import static loadableUtils.utils.pt;
import static loadableUtils.utils.showText;
import static loadableUtils.utils.setDefaultClassFinder;
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.fillRect;
import static loadableUtils.utils.getSelectedItem;
import static loadableUtils.utils.similarEmptyMap;
import static loadableUtils.utils.toFile;
import static loadableUtils.utils.dropFirst;
import static loadableUtils.utils.mod;
import static loadableUtils.utils.humanizeFormLabel;
import static loadableUtils.utils.wrapForSmartAdd;
import static loadableUtils.utils.shootScreen2;
import static loadableUtils.utils.onChange;
import static loadableUtils.utils.withTopMargin;
import static loadableUtils.utils.error;
import static loadableUtils.utils.elapsedSeconds;
import static loadableUtils.utils.hotwire;
import static loadableUtils.utils.heldInstance;
import loadableUtils.utils.Pair;
import loadableUtils.utils.BetterThreadLocal;
import loadableUtils.utils.IBWImage;
import loadableUtils.utils.WidthAndHeight;
import loadableUtils.utils.Enterable;
import loadableUtils.utils.G2Drawable;
import static loadableUtils.utils._MethodCache;
import static loadableUtils.utils.defaultMargin;
import javax.swing.border.*;
import java.text.NumberFormat;
import java.awt.datatransfer.StringSelection;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
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 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(new Runnable() {
public void run() {
try {
pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "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(new Runnable() {
public void run() {
try {
Pair p = enclosingTab(c);
if (p == null)
return;
setTabTitle(p.a, p.b, title);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Pair p = enclosingTab(c);\r\n if (p == null) return;\r\n ...";
}
});
}
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 __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 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 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 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 Object swing(Object f) {
return swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public 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(new Runnable() {
public void run() {
try {
c.setBorder(border);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.setBorder(border);";
}
});
}
return c;
}
static public JScrollPane withoutViewportBorder(JScrollPane sp) {
if (sp != null) {
swing(new Runnable() {
public void run() {
try {
sp.setViewportBorder(null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "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(new Runnable() {
public void run() {
try {
Insets i = a.getMargin();
a.setMargin(new Insets(i.top, margin, i.bottom, margin));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Insets i = a.getMargin(); \r\n a.setMargin(new Insets(i.top, margin, i.botto...";
}
});
}
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(new Runnable() {
public void run() {
try {
if (idx < tabs.getTabCount())
tabs.setTitleAt(idx, title);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (idx < tabs.getTabCount())\r\n 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 volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal ping_isCleanUpThread = new ThreadLocal();
static public boolean ping() {
newPing();
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 void _onJavaXSet() {
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public int[] unnull(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnull(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnull(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnull(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public int unnull(Integer i) {
return i == null ? 0 : i;
}
static public long unnull(Long l) {
return l == null ? 0L : l;
}
static public double unnull(Double l) {
return l == null ? 0.0 : l;
}
static public 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 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 String unnullForIteration(String s) {
return s == null ? "" : s;
}
static public Collection unnullForIteration(Collection l) {
return l == null ? immutableEmptyList() : l;
}
static public List unnullForIteration(List l) {
return l == null ? immutableEmptyList() : l;
}
static public int[] unnullForIteration(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnullForIteration(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnullForIteration(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public short[] unnullForIteration(short[] l) {
return l == null ? emptyShortArray() : l;
}
static public Map unnullForIteration(Map l) {
return l == null ? immutableEmptyMap() : l;
}
static public Iterable unnullForIteration(Iterable i) {
return i == null ? immutableEmptyList() : i;
}
static public A[] unnullForIteration(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnullForIteration(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnullForIteration(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnullForIteration(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnullForIteration(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public long unnullForIteration(Long l) {
return l == null ? 0L : l;
}
static public void 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 int ubyteToInt(byte b) {
return b & 0x0FF;
}
static public int ubyteToInt(char c) {
return c & 0x0FF;
}
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 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 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 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(new Runnable() {
public void run() {
try {
a.setOpaque(false);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.setOpaque(false);";
}
});
}
return a;
}
static public JPanel borderLayoutPanel() {
return jpanel(new BorderLayout());
}
static public JSpinner 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(new Runnable() {
public void run() {
try {
s.setValue(value);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "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 Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
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 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 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 void newPing() {
var tl = newPing_actionTL();
Runnable action = tl == null ? null : tl.get();
{
if (action != null)
action.run();
}
}
static public void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static public Thread currentThread() {
return Thread.currentThread();
}
static public boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public boolean eq(Symbol a, String b) {
return eq(str(a), b);
}
static public 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 int[] emptyIntArray_a = new int[0];
static public int[] emptyIntArray() {
return emptyIntArray_a;
}
static public char[] emptyCharArray = new char[0];
static public char[] emptyCharArray() {
return emptyCharArray;
}
static public double[] emptyDoubleArray = new double[0];
static public double[] emptyDoubleArray() {
return emptyDoubleArray;
}
static public Map emptyMap() {
return new HashMap();
}
static public Object[] emptyObjectArray_a = new Object[0];
static public Object[] emptyObjectArray() {
return emptyObjectArray_a;
}
static public Symbol emptySymbol_value;
static public Symbol emptySymbol() {
if (emptySymbol_value == null)
emptySymbol_value = symbol("");
return emptySymbol_value;
}
static public 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 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(new Runnable() {
public void run() {
try {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ...";
}
});
}
return c;
}
static public A setToolTipText(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
static public String strOrNull(Object o) {
return o == null ? null : str(o);
}
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 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 A printStackTrace(A e) {
if (e != null)
print(getStackTrace(e));
return e;
}
static public void printStackTrace() {
printStackTrace(new Throwable());
}
static public void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static public void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static public void lockOrFail(Lock lock, long timeout) {
try {
ping();
vmBus_send("locking", lock, "thread", currentThread());
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
vmBus_send("locked", lock, "thread", currentThread());
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static public 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 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 String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
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(new Runnable() {
public void run() {
try {
DefaultFormatter formatter = (DefaultFormatter) (tf.getFormatter());
if (formatter != null)
formatter.setCommitsOnValidEdit(true);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "DefaultFormatter formatter = (DefaultFormatter) (tf.getFormatter());\r\n if...";
}
});
}
return spinner;
}
static public 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 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 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 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 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 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 x30_pkg.x30_util.BetterThreadLocal newPing_actionTL;
static public x30_pkg.x30_util.BetterThreadLocal newPing_actionTL() {
if (newPing_actionTL == null)
newPing_actionTL = vm_generalMap_getOrCreate("newPing_actionTL", () -> {
Runnable value = (Runnable) (callF_gen(vm_generalMap_get("newPing_valueForNewThread")));
var tl = new x30_pkg.x30_util.BetterThreadLocal();
tl.set(value);
return tl;
});
return newPing_actionTL;
}
static volatile public boolean licensed_yes = true;
static public boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
static public void licensed_off() {
licensed_yes = false;
}
static public Map synchroHashMap() {
return synchronizedMap(new HashMap());
}
static public boolean containsNulls(Collection c) {
return contains(c, null);
}
static public WeakHasherMap symbol_map = new WeakHasherMap(new Hasher() {
public int hashCode(Symbol symbol) {
return symbol.text.hashCode();
}
public boolean equals(Symbol a, Symbol b) {
if (a == null)
return b == null;
return b != null && eq(a.text, b.text);
}
});
static public Symbol symbol(String s) {
if (s == null)
return null;
synchronized (symbol_map) {
Symbol symbol = new Symbol(s, true);
Symbol existingSymbol = symbol_map.findKey(symbol);
if (existingSymbol == null)
symbol_map.put(existingSymbol = symbol, true);
return existingSymbol;
}
}
static public Symbol symbol(CharSequence s) {
if (s == null)
return null;
if (s instanceof Symbol)
return (Symbol) s;
if (s instanceof String)
return symbol((String) s);
return symbol(str(s));
}
static public Symbol symbol(Object o) {
return symbol((CharSequence) o);
}
static public 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 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 Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public void pcallFAll_minimalExceptionHandling(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
ping();
pcallF_minimalExceptionHandling(f, args);
}
}
static public void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) {
while (it.hasNext()) {
ping();
pcallF_minimalExceptionHandling(it.next(), args);
}
}
static public Set vm_busListeners_live_cache;
static public Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
static public Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static public Map vm_busListenersByMessage_live_cache;
static public Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
static public Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public String 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 Runnable asRunnable(Object o) {
return toRunnable(o);
}
static public void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static public void clearTabs(final JTabbedPane tabs) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
tabs.removeAll();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tabs.removeAll();";
}
});
}
}
static public int asInt(Object o) {
return toInt(o);
}
static public Object[] arrayrep(Object a, int n) {
return asArray(repeat(a, n));
}
static public boolean isComponentOrSwingable(Object o) {
if (o instanceof Swingable)
return true;
return o instanceof Component;
}
static public void addTab(JTabbedPane tabs, String title, Component c) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
tabs.add(title, wrap(c));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tabs.add(title, wrap(c));";
}
});
}
}
static public void addTab(JTabbedPane tabs, String title, Swingable c) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
tabs.add(title, wrap(c));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tabs.add(title, wrap(c));";
}
});
}
}
static public 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 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 int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static public int parseInt(char c) {
return Integer.parseInt(str(c));
}
static public int boolToInt(boolean b) {
return b ? 1 : 0;
}
static public 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 String className(Object o) {
return getClassName(o);
}
static public boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
static public A vm_generalMap_getOrCreate(Object key, F0 create) {
return vm_generalMap_getOrCreate(key, f0ToIF0(create));
}
static public A vm_generalMap_getOrCreate(Object key, IF0 create) {
Map generalMap = vm_generalMap();
if (generalMap == null)
return null;
synchronized (generalMap) {
A a = (A) (vm_generalMap_get(key));
if (a == null)
vm_generalMap_put(key, a = create == null ? null : create.get());
return a;
}
}
static public A callF_gen(F0 f) {
return f == null ? null : f.get();
}
static public B callF_gen(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public A callF_gen(IF0 f) {
return f == null ? null : f.get();
}
static public B callF_gen(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF_gen(A a, IF1 f) {
return f == null ? null : f.get(a);
}
static public C callF_gen(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public C callF_gen(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public void callF_gen(VF1 f, A a) {
{
if (f != null)
f.get(a);
}
}
static public void callF_gen(A a, IVF1 f) {
{
if (f != null)
f.get(a);
}
}
static public void callF_gen(IVF1 f, A a) {
{
if (f != null)
f.get(a);
}
}
static public Object callF_gen(Runnable r) {
{
if (r != null)
r.run();
}
return null;
}
static public Object callF_gen(Object f, Object... args) {
return callF(f, args);
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static public Map synchronizedMap() {
return synchroMap();
}
static public Map synchronizedMap(Map map) {
return synchroMap(map);
}
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 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 volatile public PersistableThrowable lastException_lastException;
static public PersistableThrowable lastException() {
return lastException_lastException;
}
static public void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
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 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 boolean emptyString(String s) {
return s == null || s.length() == 0;
}
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 void _registerIO(Object object, String path, boolean opened) {
}
static public IF0 f0ToIF0(F0 f) {
return f == null ? null : () -> f.get();
}
static public Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
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 Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static public Throwable _storeException_value;
static public void _storeException(Throwable e) {
_storeException_value = e;
}
static public PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static public 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 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 boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
static public String theAGIBlueDomain() {
return "agi.blue";
}
static public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(Symbol a, Symbol b) {
return eq(a, b);
}
static public boolean eqic(Symbol a, String b) {
return eqic(asString(a), b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
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 Symbol implements CharSequence {
public String text;
public Symbol() {
}
public Symbol(String text, boolean dummy) {
this.text = text;
}
public int hashCode() {
return _hashCode(text);
}
public String toString() {
return text;
}
public boolean equals(Object o) {
return this == o;
}
public int length() {
return text.length();
}
public char charAt(int index) {
return text.charAt(index);
}
public CharSequence subSequence(int start, int end) {
return text.substring(start, end);
}
}
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 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 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 final public class WeakHasherMap extends AbstractMap implements Map {
public Hasher hasher = null;
final public boolean keyEquals(Object k1, Object k2) {
return (hasher == null ? k1.equals(k2) : hasher.equals(k1, k2));
}
final public int keyHashCode(Object k1) {
return (hasher == null ? k1.hashCode() : hasher.hashCode(k1));
}
final public WeakKey WeakKeyCreate(K k) {
if (k == null)
return null;
else
return new WeakKey(k);
}
final public WeakKey WeakKeyCreate(K k, ReferenceQueue super K> q) {
if (k == null)
return null;
else
return new WeakKey(k, q);
}
final public class WeakKey extends WeakReference {
public int hash;
public WeakKey(K k) {
super(k);
hash = keyHashCode(k);
}
final public WeakKey create(K k) {
if (k == null)
return null;
else
return new WeakKey(k);
}
public WeakKey(K k, ReferenceQueue super K> q) {
super(k, q);
hash = keyHashCode(k);
}
final public WeakKey create(K k, ReferenceQueue super K> q) {
if (k == null)
return null;
else
return new WeakKey(k, q);
}
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o.getClass().equals(WeakKey.class)))
return false;
Object t = this.get();
@SuppressWarnings("unchecked")
Object u = ((WeakKey) o).get();
if ((t == null) || (u == null))
return false;
if (t == u)
return true;
return keyEquals(t, u);
}
@Override
public int hashCode() {
return hash;
}
}
public HashMap hash;
public ReferenceQueue super K> queue = new ReferenceQueue();
@SuppressWarnings("unchecked")
final public void processQueue() {
WeakKey wk;
while ((wk = (WeakKey) queue.poll()) != null) {
hash.remove(wk);
}
}
public WeakHasherMap(int initialCapacity, float loadFactor) {
hash = new HashMap(initialCapacity, loadFactor);
}
public WeakHasherMap(int initialCapacity) {
hash = new HashMap(initialCapacity);
}
public WeakHasherMap() {
hash = new HashMap();
}
public WeakHasherMap(Hasher h) {
hash = new HashMap();
hasher = h;
}
@Override
public int size() {
return entrySet().size();
}
@Override
public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override
public boolean containsKey(Object key) {
@SuppressWarnings("unchecked")
K kkey = (K) key;
return hash.containsKey(WeakKeyCreate(kkey));
}
@Override
public V get(Object key) {
@SuppressWarnings("unchecked")
K kkey = (K) key;
return hash.get(WeakKeyCreate(kkey));
}
@Override
public V put(K key, V value) {
processQueue();
return hash.put(WeakKeyCreate(key, queue), value);
}
@Override
public V remove(Object key) {
processQueue();
@SuppressWarnings("unchecked")
K kkey = (K) key;
return hash.remove(WeakKeyCreate(kkey));
}
@Override
public void clear() {
processQueue();
hash.clear();
}
@SuppressWarnings("TypeParameterShadowing")
final public class Entry implements Map.Entry {
public Map.Entry ent;
public K key;
public Entry(Map.Entry ent, K key) {
this.ent = ent;
this.key = key;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return ent.getValue();
}
@Override
public V setValue(V value) {
return ent.setValue(value);
}
final public boolean keyvalEquals(K o1, K o2) {
return (o1 == null) ? (o2 == null) : keyEquals(o1, o2);
}
final public boolean valEquals(V o1, V o2) {
return (o1 == null) ? (o2 == null) : o1.equals(o2);
}
@SuppressWarnings("NonOverridingEquals")
public boolean equals(Map.Entry e) {
return (keyvalEquals(key, e.getKey()) && valEquals(getValue(), e.getValue()));
}
@Override
public int hashCode() {
V v;
return (((key == null) ? 0 : keyHashCode(key)) ^ (((v = getValue()) == null) ? 0 : v.hashCode()));
}
}
final public class EntrySet extends AbstractSet> {
public Set> hashEntrySet = hash.entrySet();
@Override
public Iterator> iterator() {
return new Iterator>() {
public Iterator> hashIterator = hashEntrySet.iterator();
public Map.Entry next = null;
@Override
public boolean hasNext() {
while (hashIterator.hasNext()) {
Map.Entry ent = hashIterator.next();
WeakKey wk = ent.getKey();
K k = null;
if ((wk != null) && ((k = wk.get()) == null)) {
continue;
}
next = new Entry(ent, k);
return true;
}
return false;
}
@Override
public Map.Entry next() {
if ((next == null) && !hasNext())
throw new NoSuchElementException();
Map.Entry e = next;
next = null;
return e;
}
@Override
public void remove() {
hashIterator.remove();
}
};
}
@Override
public boolean isEmpty() {
return !(iterator().hasNext());
}
@Override
public int size() {
int j = 0;
for (Iterator> i = iterator(); i.hasNext(); i.next()) j++;
return j;
}
@Override
public boolean remove(Object o) {
processQueue();
if (!(o instanceof Map.Entry, ?>))
return false;
@SuppressWarnings("unchecked")
Map.Entry e = (Map.Entry) o;
Object ev = e.getValue();
WeakKey wk = WeakKeyCreate(e.getKey());
Object hv = hash.get(wk);
if ((hv == null) ? ((ev == null) && hash.containsKey(wk)) : hv.equals(ev)) {
hash.remove(wk);
return true;
}
return false;
}
@Override
public int hashCode() {
int h = 0;
for (Iterator> i = hashEntrySet.iterator(); i.hasNext(); ) {
Map.Entry ent = i.next();
WeakKey wk = ent.getKey();
Object v;
if (wk == null)
continue;
h += (wk.hashCode() ^ (((v = ent.getValue()) == null) ? 0 : v.hashCode()));
}
return h;
}
}
public Set> entrySet = null;
@Override
public Set> entrySet() {
if (entrySet == null)
entrySet = new EntrySet();
return entrySet;
}
public K findKey(Object key) {
processQueue();
K kkey = (K) key;
WeakKey wkey = WeakKeyCreate(kkey);
WeakKey found = hashMap_findKey(hash, wkey);
return found == null ? null : found.get();
}
}
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 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 {
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 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 public interface Hasher {
public int hashCode(A a);
public boolean equals(A a, A b);
}
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 extends Meta {
public DoneFlag ended = new DoneFlag(true);
volatile public A lastElement;
public AtomicLong elementCount = new AtomicLong();
transient public List> onNewElement;
public SourceTriggeredStream onNewElement(IVF1 f) {
onNewElement = syncAddOrCreate(onNewElement, f);
return this;
}
public void newElement(A a) {
lastElement = a;
inc(elementCount);
pcallFAll(onNewElement, a);
}
public void onNewElement(Runnable r) {
onNewElement(runnableToIVF1(r));
}
public A get() {
return lastElement;
}
public long elementCount() {
return elementCount.get();
}
public void end() {
ended.raise();
}
public boolean ended() {
return ended.isUp();
}
public void catchError(Runnable r) {
main.catchError(ended, r);
}
public void directlyFeedInto(Consumer consumer) {
if (consumer != null)
onNewElement(a -> consumer.accept(a));
}
}
static public class RegionBoundingBoxPainter extends RegionPainter {
final public RegionBoundingBoxPainter setLineWidth(int lineWidth) {
return lineWidth(lineWidth);
}
public RegionBoundingBoxPainter lineWidth(int lineWidth) {
this.lineWidth = lineWidth;
return this;
}
final public int getLineWidth() {
return lineWidth();
}
public int lineWidth() {
return lineWidth;
}
public int lineWidth = 3;
public void drawRegion() {
Rect r = regions.regionBounds(iRegion);
g.setColor(withOpacity(.75, Color.red));
AutoCloseable __1 = tempSetStroke(g, new BasicStroke(lineWidth));
try {
drawRect(g, growRectTopAndLeft(scaleRect_floor(growRectRightAndBottom(r), zoomX, zoomY)));
} finally {
_close(__1);
}
}
}
abstract static public class RegionPainter {
final public RegionPainter setZoomX(double zoomX) {
return zoomX(zoomX);
}
public RegionPainter zoomX(double zoomX) {
this.zoomX = zoomX;
return this;
}
final public double getZoomX() {
return zoomX();
}
public double zoomX() {
return zoomX;
}
public double zoomX;
final public RegionPainter setZoomY(double zoomY) {
return zoomY(zoomY);
}
public RegionPainter zoomY(double zoomY) {
this.zoomY = zoomY;
return this;
}
final public double getZoomY() {
return zoomY();
}
public double zoomY() {
return zoomY;
}
public double zoomY;
final public RegionPainter setRegions(FastRegions_BWImage regions) {
return regions(regions);
}
public RegionPainter regions(FastRegions_BWImage regions) {
this.regions = regions;
return this;
}
final public FastRegions_BWImage getRegions() {
return regions();
}
public FastRegions_BWImage regions() {
return regions;
}
public FastRegions_BWImage regions;
final public RegionPainter setIRegion(int iRegion) {
return iRegion(iRegion);
}
public RegionPainter iRegion(int iRegion) {
this.iRegion = iRegion;
return this;
}
final public int getIRegion() {
return iRegion();
}
public int iRegion() {
return iRegion;
}
public int iRegion;
final public RegionPainter setG(Graphics2D g) {
return g(g);
}
public RegionPainter g(Graphics2D g) {
this.g = g;
return this;
}
final public Graphics2D getG() {
return g();
}
public Graphics2D g() {
return g;
}
public Graphics2D g;
abstract public void drawRegion();
}
static public interface IFieldsToList {
public Object[] _fieldsToList();
}
static public class FastRegions_BWImage implements Runnable, IFieldsToList {
public BWImage image;
public FastRegions_BWImage() {
}
public FastRegions_BWImage(BWImage image) {
this.image = image;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + image + ")";
}
public Object[] _fieldsToList() {
return new Object[] { image };
}
public int w, h, runner;
final public int getSize() {
return size();
}
public int size() {
return size;
}
public int size;
public IntBuffer stack = new IntBuffer();
public int[] regionMatrix;
public IntBuffer regionPixels = new IntBuffer();
public IntBuffer regionFirstPixel;
public IntBuffer regionSize;
public IntBuffer regionBounds;
public int regionCounter;
public boolean verbose = false;
public double regionStep = .1;
public int x(int pos) {
return pos % w;
}
public int y(int pos) {
return pos / w;
}
public int pos(int x, int y) {
return y * w + x;
}
public Pt pt(int pos) {
return new Pt(x(pos), y(pos));
}
public boolean validPos(int x, int y) {
return x >= 0 && y >= 0 && x < w && y < h;
}
public int getColor(int pos) {
return image.getInt(x(pos), y(pos));
}
public FastRegions_BWImage(BufferedImage img) {
this(toBWImage(img));
}
public void run() {
try {
w = image.getWidth();
h = image.getHeight();
size = w * h;
regionMatrix = new int[size];
{
if (regionFirstPixel != null)
regionFirstPixel.add(0);
}
{
if (regionPixels != null)
regionPixels.setSize(size);
}
while (runner < size) {
if (regionMatrix[runner] == 0) {
int region = ++regionCounter;
{
if (regionFirstPixel != null)
regionFirstPixel.add(regionPixels != null ? l(regionPixels) : runner);
}
stack.add(runner);
int color = getColor(runner);
int rsize = 0, x1 = w, y1 = h, x2 = 0, y2 = 0;
while (nempty(stack)) {
int pos = stack.popLast();
if (regionMatrix[pos] != 0)
continue;
if (getColor(pos) != color)
continue;
regionMatrix[pos] = region;
++rsize;
{
if (regionPixels != null)
regionPixels.add(pos);
}
int x = x(pos), y = y(pos);
if (x < x1)
x1 = x;
if (x > x2)
x2 = x;
if (y < y1)
y1 = y;
if (y > y2)
y2 = y;
if (x > 0)
stack.add(pos - 1);
if (x < w - 1)
stack.add(pos + 1);
if (y > 0)
stack.add(pos - w);
if (y < h - 1)
stack.add(pos + w);
}
{
if (regionSize != null)
regionSize.add(rsize);
}
{
if (regionBounds != null)
regionBounds.addAll(x1, y1, x2, y2);
}
}
++runner;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public IBWImage regionsImage() {
return iBWImageFromFunction((x, y) -> {
var region = regionMatrix[pos(x, y)];
return ((region - 1) * regionStep) % (1.0 + regionStep - 0.0001);
}, w, h);
}
final public int nRegions() {
return regionCount();
}
public int regionCount() {
return regionCounter;
}
abstract public class RegionIterator {
public int pos;
abstract public boolean next();
public int pos() {
return pos;
}
public int x() {
return FastRegions_BWImage.this.x(pos);
}
public int y() {
return FastRegions_BWImage.this.y(pos);
}
}
public class FloodRegionIterator extends RegionIterator {
public int region;
public IntBuffer stack = new IntBuffer();
public BitSet seen = new BitSet(size);
public FloodRegionIterator(int region) {
this.region = region;
int pos = regionFirstPixel.get(region);
printVars("region", region, "pos", pos);
seen.set(pos);
stack.add(pos);
}
public boolean next() {
if (empty(stack))
return false;
pos = stack.popLast();
int x = x(), y = y();
if (x > 0)
tryPosition(pos - 1);
if (x < w - 1)
tryPosition(pos + 1);
if (y > 0)
tryPosition(pos - w);
if (y < h - 1)
tryPosition(pos + w);
return true;
}
final public void tryPosition(int p) {
if (!seen.get(p) && regionMatrix[p] == region) {
seen.set(p);
stack.add(p);
}
}
}
public class CachedRegionIterator extends RegionIterator {
public int i, to;
public CachedRegionIterator(int region) {
i = regionFirstPixel.get(region);
to = region + 1 < l(regionFirstPixel) ? regionFirstPixel.get(region + 1) : l(regionPixels);
}
public boolean next() {
if (i >= to)
return false;
pos = regionPixels.get(i++);
return true;
}
}
public int regionSize(int iRegion) {
return regionSize.get(iRegion);
}
final public Pt firstPixel(int iRegion) {
return samplePixel(iRegion);
}
public Pt samplePixel(int iRegion) {
int i = regionFirstPixel.get(iRegion);
return pt(regionPixels != null ? regionPixels.get(i) : i);
}
public boolean inRegion(int iRegion, int x, int y) {
return validPos(x, y) && regionMatrix[pos(x, y)] == iRegion;
}
public Rect regionBounds(int iRegion) {
return rectFromPoints(regionBounds.get((iRegion - 1) * 4), regionBounds.get((iRegion - 1) * 4 + 1), regionBounds.get((iRegion - 1) * 4 + 2), regionBounds.get((iRegion - 1) * 4 + 3));
}
public int regionAt(int x, int y) {
return !validPos(x, y) ? 0 : regionMatrix[pos(x, y)];
}
public RegionIterator regionIterator(int iRegion) {
return regionPixels != null ? new FloodRegionIterator(iRegion) : new CachedRegionIterator(iRegion);
}
public void collectFirstPixels() {
regionFirstPixel = new IntBuffer();
}
public void collectBounds() {
regionBounds = new IntBuffer();
}
public Matrix regionBitMatrix(int iRegion) {
return new AbstractMatrix(w, h) {
public Boolean get(int x, int y) {
return inRegion(iRegion, x, y);
}
};
}
}
static public interface ISetter {
public void set(A a);
}
static public class DoneFlag extends Flag {
transient volatile public Object error;
transient public boolean printErrors = false;
public DoneFlag() {
}
public DoneFlag(boolean printErrors) {
this.printErrors = printErrors;
}
public void done() {
raise();
}
final public void setError(Object error) {
done(error);
}
public void done(Object error) {
this.error = error;
if (printErrors)
printStackTrace_gen(error);
raise();
}
public boolean hasError() {
return error != null;
}
public boolean isDone() {
return isUp();
}
}
static public class FPSCounter {
public Timestamp started = new Timestamp();
public double counter;
synchronized public void inc() {
counter++;
}
synchronized public double get() {
return doubleRatio(counter, secondsSinceStart());
}
public double secondsSinceStart() {
return elapsedSeconds(started);
}
synchronized public void reset() {
started = tsNow();
counter = 0;
}
}
static public interface IVar extends IF0 {
public void set(A a);
public A get();
default public boolean has() {
return get() != null;
}
default public void clear() {
set(null);
}
}
static public class GazelleVScript implements IFieldsToList {
public String text;
public GazelleVScript() {
}
public GazelleVScript(String text) {
this.text = text;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + text + ")";
}
public Object[] _fieldsToList() {
return new Object[] { text };
}
public List tok;
static public String helpText = "Gazelle V Script\r\n----------------\r\n\r\nSeparate commands with spaces. Language is case-insensitive.\r\nComments like in Java with /* */ or //\r\n\r\n1p, 2p etc: Scale image down to x pixels\r\n1c, 2c, ..., 256c: Reduce gray scale levels\r\n1w, 2w etc: Scale image width only to x pixels\r\nstruct: show object structure\r\nniceStruct: show object structure indented\r\nrasters: reproduce horizontal bars\r\nclassName: show type of object on stack\r\nq1...q4: select quadrant\r\noriginal: show input image in color\r\n";
public class Sequence {
public Map vars = new HashMap();
}
public class Run implements Steppable {
public ListAndIndex ptr;
public String token;
public Stack stack = new Stack();
final public Run setInputImage(IBWIntegralImage inputImage) {
return inputImage(inputImage);
}
public Run inputImage(IBWIntegralImage inputImage) {
this.inputImage = inputImage;
return this;
}
final public IBWIntegralImage getInputImage() {
return inputImage();
}
public IBWIntegralImage inputImage() {
return inputImage;
}
public IBWIntegralImage inputImage;
public IBWIntegralImage integralImage;
final public Run setBwImage(BWImage bwImage) {
return bwImage(bwImage);
}
public Run bwImage(BWImage bwImage) {
this.bwImage = bwImage;
return this;
}
final public BWImage getBwImage() {
return bwImage();
}
public BWImage bwImage() {
return bwImage;
}
public BWImage bwImage;
public Run setIntegralImage(IBWIntegralImage ii) {
push(integralImage = ii);
return this;
}
public Run() {
parse();
ptr = new ListAndIndex(tok, 1);
}
public void push(Object o) {
stack.add(o);
}
public Object value() {
return last(stack);
}
public boolean step() {
token = ptr.get();
if (token == null)
return false;
next();
if (isInteger(token)) {
int i = parseInt(token);
token = tpp();
if (is("p"))
scaleToHeight(i);
else if (is("c"))
posterize(i);
else if (is("w"))
scaleWidthOnly(i);
else
warn("Unknown token: " + token);
} else if (is("rasters"))
push(reproduceRasterBars(bwIntegralImage()));
else if (is("struct"))
push(struct(value()));
else if (is("niceStruct"))
push(sfuIndent(value()));
else if (is("className"))
push(className(value()));
else if (is("q1"))
clip(0, .5, 0, .5);
else if (is("q2"))
clip(.5, 1, 0, .5);
else if (is("q3"))
clip(0, .5, .5, 1);
else if (is("q4"))
clip(.5, 1, .5, 1);
else if (is("original"))
push(toBufferedImage(inputImage));
else {
warn("Unknown token: " + token);
}
return true;
}
public boolean is(String t) {
return eqic(token, t);
}
public String tpp() {
var token = ptr.get();
next();
return token;
}
public void next() {
if (!ptr.atEnd())
ptr = ptr.plus(2);
}
public void scaleToHeight(int pixelRows) {
pixelRows = min(pixelRows, 512);
if (integralImage == null) {
warn("No integral image to scale down");
return;
}
push(bwImage = scaledBWImageFromBWIntegralImage_withMeta_height(pixelRows, integralImage));
}
public void posterize(int colors) {
colors = clamp(colors, 2, 256);
if (bwImage == null) {
warn("No image to posterize");
return;
} else
push(bwImage = posterizeBWImage_withMeta(colors, bwImage));
}
public IBWIntegralImage bwIntegralImage() {
Object val = value();
if (val instanceof IBWIntegralImage)
return ((IBWIntegralImage) val);
if (val instanceof BWImage) {
var ii = main.bwIntegralImage((BWImage) val);
setIntegralImage(ii);
return ii;
}
throw fail("Not an image on stack");
}
public void scaleWidthOnly(int w) {
var ii = bwIntegralImage();
push(bwImage = scaledBWImageFromBWIntegralImage_withMeta(ii, w, ii.getHeight()));
}
public void clip(double x1, double x2, double y1, double y2) {
Object val = value();
if (val instanceof IBWIntegralImage) {
int w = ((IBWIntegralImage) val).getWidth(), h = ((IBWIntegralImage) val).getHeight();
Rect r = toRect_round(scaleRect(w, h, doubleRectFromPoints(x1, y1, x2, y2)));
setIntegralImage(new IIBWVirtualClip(((IBWIntegralImage) val), r));
} else if (val instanceof BWImage)
throw todo();
else
throw fail("Not an image on stack");
}
public Object result() {
return last(stack);
}
public void run() {
try {
stepAll(this);
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
public void parse() {
if (tok == null)
tok = javaTok(text);
}
}
abstract static public class ImageSurfaceMouseHandler extends MouseAdapter implements AutoCloseable {
public ImageSurface is;
public void register(ImageSurface is) {
this.is = is;
is.tools.add(this);
is.addMouseListener(this);
is.addMouseMotionListener(this);
}
public void close() {
try {
if (is == null)
return;
is.tools.remove(this);
is.removeMouseListener(this);
is.removeMouseMotionListener(this);
is = null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Pt getPt(MouseEvent e) {
return toPt(getPoint(e));
}
public Point getPoint(MouseEvent e) {
return new Point((int) (e.getX() / is.getZoomX()), (int) (e.getY() / is.getZoomY()));
}
}
static public class WeakVar implements IVar {
public WeakReference ref;
public synchronized void set(A a) {
ref = weakRef(a);
}
public synchronized A get() {
if (ref == null)
return null;
A value = ref.get();
if (value == null)
ref = null;
return value;
}
}
static public class ListAndIndex implements IFieldsToList {
static final public String _fieldOrder = "list idx";
public List list;
public int idx;
public ListAndIndex() {
}
public ListAndIndex(List list, int idx) {
this.idx = idx;
this.list = list;
}
public boolean equals(Object o) {
if (!(o instanceof ListAndIndex))
return false;
ListAndIndex __1 = (ListAndIndex) o;
return eq(list, __1.list) && idx == __1.idx;
}
public int hashCode() {
int h = 276903961;
h = boostHashCombine(h, _hashCode(list));
h = boostHashCombine(h, _hashCode(idx));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { list, idx };
}
public boolean atEnd() {
return idx >= l(list);
}
public A get() {
return _get(list, idx);
}
public int size() {
return l(list);
}
public String toString() {
return subList(list, 0, idx) + ", then " + subList(list, idx);
}
public ListAndIndex plus(int ofs) {
return new ListAndIndex(list, idx + ofs);
}
}
static public class IIBWVirtualClip extends Meta implements IBWIntegralImage {
public IBWIntegralImage fullImage;
public int x1, y1, w, h;
public IIBWVirtualClip() {
}
public IIBWVirtualClip(IBWIntegralImage fullImage, Rect r) {
this(fullImage, r.x, r.y, r.w, r.h);
}
public IIBWVirtualClip(IBWIntegralImage fullImage, int x1, int y1, int w, int h) {
this.h = h;
this.w = w;
this.y1 = y1;
this.x1 = x1;
this.fullImage = fullImage;
optimize();
}
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
public int getIIValue(int x, int y) {
return fullImage.getIIValue(x + x1, y + y1);
}
public double getIIValue(double x, double y) {
return fullImage.getIIValue(x + x1, y + y1);
}
public BufferedImage getBufferedImage() {
return clipBufferedImage(fullImage.getBufferedImage(), x1, y1, w, h);
}
public void optimize() {
if (fullImage instanceof IIBWVirtualClip) {
x1 += ((IIBWVirtualClip) fullImage).x1;
y1 += ((IIBWVirtualClip) fullImage).y1;
fullImage = ((IIBWVirtualClip) fullImage).fullImage;
}
}
}
static public class Flag implements Runnable {
public boolean up = false;
public synchronized boolean raise() {
if (!up) {
up = true;
notifyAll();
return true;
} else
return false;
}
public synchronized void waitUntilUp() {
while (!up) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public boolean waitUntilUp(double timeout) {
return waitUntilUp(toMS(timeout));
}
public synchronized boolean waitUntilUp(long timeout) {
if (!up) {
try {
wait(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return isUp();
}
public synchronized boolean isUp() {
return up;
}
public boolean get() {
return isUp();
}
public String toString() {
return isUp() ? "up" : "down";
}
public void waitForThisOr(Flag otherFlag) {
try {
while (!isUp() && !otherFlag.isUp()) Thread.sleep(50);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void run() {
raise();
}
}
static public BufferedImage toBufferedImage(Object o) {
return toBufferedImageOpt(o);
}
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 containsInstance(Iterable i, Class c) {
if (i != null)
for (Object o : i) if (isInstanceX(c, o))
return true;
return false;
}
static public Class> getClass(String name) {
return _getClass(name);
}
static public Class getClass(Object o) {
return _getClass(o);
}
static public Class getClass(Object realm, String name) {
return _getClass(realm, name);
}
static public void register(Concept c) {
registerConcept(c);
}
static public AutoCloseable tempAfterwards(final Object r) {
return new AutoCloseable() {
public void close() {
callF(r);
}
};
}
static public void _close(AutoCloseable c) {
if (c != null)
try {
c.close();
} catch (Throwable e) {
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else
throw rethrow(e);
}
}
static public int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static public Area regionToArea(FastRegions_BWImage regions, int iRegion) {
return bitMatrixToArea(regions.regionBitMatrix(iRegion));
}
static public Color withOpacity(Color c, double alpha) {
return colorWithAlpha(c, alpha);
}
static public Color withOpacity(double alpha, Color c) {
return colorWithAlpha(alpha, c);
}
static public void fillShape(Graphics2D g, Shape shape) {
if (g != null && shape != null)
g.fill(shape);
}
static public Random random_random = new Random();
static public int random(int n) {
return random(random_random, n);
}
static public int random(int n, Random r) {
return random(r, n);
}
static public int random(Random r, int n) {
return n <= 0 ? 0 : getRandomizer(r).nextInt(n);
}
static public double random(double max) {
return random() * max;
}
static public double random() {
return random_random.nextInt(100001) / 100000.0;
}
static public double random(double min, double max) {
return min + random() * (max - min);
}
static public int random(int min, int max) {
return min + random(max - min);
}
static public int random(int min, int max, Random r) {
return random(r, min, max);
}
static public int random(Random r, int min, int max) {
return min + random(r, max - min);
}
static public A random(List l) {
return oneOf(l);
}
static public A random(Collection c) {
if (c instanceof List)
return random((List ) c);
int i = random(l(c));
return collectionGet(c, i);
}
static public int random(IntRange r) {
return random(r.start, r.end);
}
static public Pair random(Map map) {
return entryToPair(random(entries(map)));
}
static public int random_incl(int min, int max) {
return random_incl(min, max, defaultRandomizer());
}
static public int random_incl(int min, int max, Random random) {
return random(min, max + 1, random);
}
static public int random_incl(int max) {
return random(0, max + 1);
}
static public void drawLine(BufferedImage image, int x1, int y1, int x2, int y2, Color color) {
drawLine(imageGraphics(image), x1, y1, x2, y2, color);
}
static public void drawLine(Graphics2D g, int x1, int y1, int x2, int y2, Color color) {
g.setColor(color);
g.drawLine(x1, y1, x2, y2);
}
static public void drawLine(BufferedImage image, Pt a, Pt b, Color color) {
drawLine(imageGraphics(image), a, b, color);
}
static public void drawLine(Graphics2D g, Pt a, Pt b, Color color) {
drawLine(g, a.x, a.y, b.x, b.y, color);
}
static public boolean oneIn(int n) {
return random(n) == 0;
}
static public boolean oneIn(int n, Random random) {
return random(random, n) == 0;
}
static public boolean oneIn(Random random, int n) {
return oneIn(n, random);
}
static public A setToolTip(A c, Object toolTip) {
return setToolTipText(c, toolTip);
}
static public A setToolTip(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
static public void setToolTip(TrayIcon trayIcon, String toolTip) {
setTrayIconToolTip(trayIcon, toolTip);
}
static public Set> entrySet(Map map) {
return _entrySet(map);
}
static public void put(Map map, A a, B b) {
if (map != null)
map.put(a, b);
}
static public void put(List l, int i, A a) {
if (l != null && i >= 0 && i < l(l))
l.set(i, a);
}
static public void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
static public void remove(Collection l, A a) {
if (l != null)
l.remove(a);
}
static public B remove(Map map, Object a) {
return map == null ? null : map.remove(a);
}
static public void remove(BitSet bs, int i) {
bs.clear(i);
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public Method hashMap_findKey_method;
static public A hashMap_findKey(HashMap map, Object key) {
try {
if (hashMap_findKey_method == null)
hashMap_findKey_method = findMethodNamed(HashMap.class, "getNode");
Map.Entry entry = (Map.Entry) hashMap_findKey_method.invoke(map, hashMap_internalHash(key), key);
return entry == null ? null : entry.getKey();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public int syncL(Collection l) {
if (l == null)
return 0;
synchronized (collectionMutex(l)) {
return l.size();
}
}
static public int syncL(Map map) {
if (map == null)
return 0;
synchronized (collectionMutex(map)) {
return map.size();
}
}
static public List syncL() {
return syncList();
}
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 Class _run(String progID, String... args) {
Class main = hotwire(progID);
callMain(main, args);
return main;
}
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 List syncGetAndClear(Collection l) {
return syncCloneAndClearList(l);
}
static public void pcallFAll(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) pcallF(f, args);
}
static public void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static public A getWeakRef(Reference ref) {
return ref == null ? null : ref.get();
}
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 void cancelAndInterruptThread(Thread t) {
if (t == null)
return;
cancelThread(t);
t.interrupt();
}
static public Map syncCIMap() {
return (Map) synchroMap(caseInsensitiveMap());
}
static public JComponent withLabel(String label, JComponent component) {
return westAndCenter(jlabel(label + " "), component);
}
static public JComponent withLabel(JComponent label, JComponent component) {
return westAndCenterWithMargin(label, component);
}
static public JPanel comboBoxAndButton(JComboBox cb, String buttonText, IVF1 onEnter) {
Runnable r = new Runnable() {
public void run() {
try {
callF(onEnter, getText(cb));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onEnter, getText(cb))";
}
};
return centerAndEastWithMargin(onEnter(cb, r), jbutton(buttonText, r));
}
static public ThreadLocal bindComboBoxToLiveValue_debug = new ThreadLocal();
static public A bindComboBoxToLiveValue(final A cb, final SimpleLiveValue lv) {
final boolean debug = isTrue(bindComboBoxToLiveValue_debug.get());
bindLiveValueListenerToComponent(cb, lv, new Runnable() {
public void run() {
try {
selectItem(cb, lv.get());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "selectItem(cb, lv!)";
}
});
onChange(cb, new Runnable() {
public void run() {
try {
String s = getText(cb);
if (debug)
print("ComboBox: " + s);
lv.set(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "String s = getText(cb); // also works on editable combo boxes\r\n if (debug)...";
}
});
return cb;
}
static public JComboBox centerComboBox(JComboBox cb) {
centerTextField(textFieldFromComboBox(cb));
return cb;
}
static public AutoComboBox autoComboBox() {
return autoComboBox(new ArrayList());
}
static public AutoComboBox autoComboBox(final Collection items) {
return swing(new F0() {
public AutoComboBox get() {
try {
AutoComboBox cb = new AutoComboBox();
cb.setKeyWord(items);
return cb;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new AutoComboBox cb;\r\n cb.setKeyWord(items);\r\n ret cb;";
}
});
}
static public AutoComboBox autoComboBox(String value, Collection items) {
return setText(autoComboBox(items), value);
}
static public List cloneKeys(Map map) {
return cloneList(keys(map));
}
static public JLabel jCenteredLabel(String text) {
return jcenteredLabel(text);
}
static public JLabel jCenteredLabel() {
return jcenteredLabel();
}
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 void setComponent(SingleComponentPanel scp, Component c) {
setSCPComponent(scp, c);
}
static public void setComponent(SingleComponentPanel scp, IF0 c) {
if (scp != null)
setComponent(scp, callF(c));
}
static public void catchError(DoneFlag doneFlag, Runnable r) {
try {
{
if (r != null)
r.run();
}
} catch (Throwable e) {
doneFlag.setError(e);
}
}
static public Rect screenBounds_safe(int iScreen) {
return screenBounds(min(iScreen, screenCount() - 1));
}
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 B syncMapGetOrCreate(Map map, A key, Class extends B> c) {
return syncGetOrCreate(map, key, c);
}
static public B syncMapGetOrCreate(Map map, A key, Object f) {
return syncGetOrCreate(map, key, f);
}
static public B syncMapGetOrCreate(Class extends B> c, Map map, A key) {
return syncGetOrCreate(c, map, key);
}
static public B syncMapGetOrCreate(Map map, A key, IF0 f) {
return syncGetOrCreate(map, key, f);
}
static public Map cloneMap(Map map) {
if (map == null)
return new HashMap();
synchronized (map) {
return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
}
}
static public List cloneMap(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : cloneList(l)) x.add(f.get(o));
return x;
}
static public JTextField jLiveTextField(SimpleLiveValue lv) {
return jLiveValueTextField_bothWays(lv);
}
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 A setTextKeepCaret(final String text, final A c) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
int caret = c.getCaretPosition();
setText(c, text);
setCaretPosition(c, caret);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "int caret = c.getCaretPosition();\r\n setText(c, text);\r\n setCaretPositio...";
}
});
}
return c;
}
static public A setTextKeepCaret(A c, String text) {
return setTextKeepCaret(text, c);
}
static public boolean sameSize(WidthAndHeight a, BufferedImage b) {
return a != null && b != null && a.getWidth() == b.getWidth() && a.getHeight() == b.getHeight();
}
static public float bwDistance(BWImage a, BWImage b, float maxDistance) {
return 1f - bwImageSimilarityResized(a, b, 1f - maxDistance);
}
static public float bwDistance(BWImage a, BWImage b) {
return bwDistance(a, b, 1f);
}
static public BWImage toBWImage(RGBImage img) {
return toBW(img);
}
static public BWImage toBWImage(BufferedImage img) {
return img == null ? null : new BWImage(img);
}
static public BWImage toBWImage(MakesBufferedImage img) {
if (img == null)
return null;
if (img instanceof BWImage)
return ((BWImage) img);
return new BWImage(toBufferedImage(img));
}
static public String formatDoubleX(double d, int digits) {
return formatDoubleFull(d, digits);
}
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 int screenCount() {
return l(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices());
}
static public ButtonGroup jRadioButtons(Collection strings) {
return jradiobuttons(strings);
}
static public ButtonGroup jRadioButtons(String... strings) {
return jradiobuttons(strings);
}
static public List countIteratorAsList(int b) {
return countIteratorAsList(0, b);
}
static public List countIteratorAsList(int a, int b) {
return countIteratorToList(a, b);
}
static public List countIteratorAsList(int b, IF1 f) {
return countIteratorAsList(0, b, f);
}
static public List countIteratorAsList(int a, int b, IF1 f) {
return countIteratorToList(a, b, f);
}
static public List countIteratorAsList(int a, int b, int step) {
return countIteratorToList(a, b, step);
}
static public List countIteratorAsList(double a, double b, double step, IF1 f) {
return countIteratorToList(a, b, step, f);
}
static public List countIteratorAsList(double a, double b, double step) {
return countIteratorToList(a, b, step);
}
static public List countIteratorAsList(IF1 f, double a, double b, double step) {
return countIteratorToList(f, a, b, step);
}
static public List countIteratorAsList(IF1 f, int b) {
return countIteratorAsList(f, 0, b);
}
static public List countIteratorAsList(IF1 f, int a, int b) {
return countIteratorToList(f, a, b);
}
static public void setRadioButtonToolTips(ButtonGroup group, IF1 toolTip) {
var buttons = buttonsInGroup(group);
for (int i = 0; i < l(buttons); i++) setToolTip(buttons.get(i), toolTip.get(i));
}
static public void selectRadioButton(final AbstractButton rb) {
if (rb == null)
return;
{
swing(new Runnable() {
public void run() {
try {
rb.setSelected(true);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "rb.setSelected(true);";
}
});
}
}
static public void selectRadioButton(ButtonGroup group, int index) {
selectRadioButton(get(buttonsInGroup(group), index));
}
static public void onRadioButtonChange(final ButtonGroup group, final Object f) {
final Var idx = new Var(selectedButtonIdx(group));
Runnable r = new Runnable() {
public void run() {
try {
int idx2 = selectedButtonIdx(group);
if (idx2 >= 0 && idx2 != idx.get()) {
idx.set(idx2);
pcallF(f, idx2);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "int idx2 = selectedButtonIdx(group);\r\n if (idx2 >= 0 && idx2 != idx.get())...";
}
};
for (AbstractButton b : buttonsInGroup(group)) onChange(b, r);
}
static public void onRadioButtonChange(ButtonGroup group, IVF1 f) {
onRadioButtonChange(group, (Object) f);
}
static public List flattenList2(Object... a) {
List l = new ArrayList();
if (a != null)
for (Object x : a) if (x instanceof Collection)
for (Object sub : (Collection) x) l.addAll(flattenList2(sub));
else if (x != null)
l.add(x);
return l;
}
static public 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 List buttonsInGroup(ButtonGroup g) {
if (g == null)
return ll();
return asList(g.getElements());
}
static public int inc(AtomicInteger i) {
return incAtomicInt(i);
}
static public int inc(AtomicInteger i, int delta) {
return incAtomicInt(i, delta);
}
static public long inc(AtomicLong l) {
return incAtomicLong(l);
}
static public long inc(AtomicLong l, long b) {
return l.addAndGet(b);
}
static public int inc(IntVar v) {
synchronized (v) {
int val = v.get() + 1;
v.set(val);
return val;
}
}
static public IVF1 runnableToIVF1(Runnable r) {
return r == null ? null : a -> r.run();
}
static public AutoCloseable tempSetStroke(Graphics2D g, Stroke s) {
Stroke oldStroke = g.getStroke();
g.setStroke(s);
return () -> g.setStroke(oldStroke);
}
static public void drawRect(BufferedImage image, int x, int y, int w, int h, Color color) {
Graphics2D g = imageGraphics(image);
drawRect(g, x, y, w, h, color);
g.dispose();
}
static public void drawRect(Graphics2D g, int x, int y, int w, int h, Color color) {
g.setColor(color);
g.drawRect(x, y, w, h);
}
static public void drawRect(Graphics2D g, Rect r) {
g.drawRect(r.x, r.y, r.w, r.h);
}
static public void drawRect(int x, int y, int w, int h, Color color) {
drawRect(currentImage(), x, y, w, h, color);
}
static public void drawRect(Rect r, Color color) {
drawRect(r.x, r.y, r.w, r.h, color);
}
static public void drawRect(BufferedImage image, Rect r, Color c) {
if (r != null)
drawRect(image, r.x, r.y, r.w, r.h, c);
}
static public Rect growRectTopAndLeft(Rect r) {
return growRectTopAndLeft(r, 1);
}
static public Rect growRectTopAndLeft(Rect r, int pixels) {
return new Rect(r.x - pixels, r.y - pixels, r.w + pixels, r.h + pixels);
}
static public Rect scaleRect_floor(Rect r, double factorX) {
return scaleRect_floor(r, factorX, factorX);
}
static public Rect scaleRect_floor(Rect r, double factorX, double factorY) {
return rectFromPoints(ifloor(r.x * factorX), ifloor(r.y * factorY), ifloor(r.x2() * factorX), ifloor(r.y2() * factorY));
}
static public Rect scaleRect_floor(double factor, Rect r) {
return scaleRect_floor(r, factor);
}
static public Rect scaleRect_floor(DoubleRect r, double factorX) {
return scaleRect_floor(r, factorX, factorX);
}
static public Rect scaleRect_floor(DoubleRect r, double factorX, double factorY) {
return rect(ifloor(r.x * factorX), ifloor(r.y * factorY), ifloor(r.w * factorX), ifloor(r.h * factorY));
}
static public Rect growRectRightAndBottom(Rect r, int x, int y) {
return new Rect(r.x, r.y, r.w + x, r.h + y);
}
static public Rect growRectRightAndBottom(Rect r) {
return growRectRightAndBottom(r, 1, 1);
}
static public IBWImage iBWImageFromFunction(IF2_IntInt_Double f, int w, int h) {
return new IBWImage() {
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
public float getFloatPixel(int x, int y) {
return (float) f.get(x, y);
}
};
}
static public void printVars(Object... params) {
printVars_str(params);
}
static public int done_minPrint = 10;
static public long done(long startTime, String desc) {
long time = now() - startTime;
if (time >= done_minPrint)
print(desc + " [" + time + " ms]");
return time;
}
static public long done(String desc, long startTime) {
return done(startTime, desc);
}
static public long done(long startTime) {
return done(startTime, "");
}
static public A printStackTrace_gen(A e) {
if (e instanceof Throwable)
printStackTrace((Throwable) e);
else
print(e);
return e;
}
static public BufferedImage inputImage_image;
static public BufferedImage inputImage() {
if (inputImage_image != null)
return inputImage_image;
final ImageChooser ic = new ImageChooser();
if (!showTitledForm_blocking("Please Choose Image To Work On", "", ic))
throw fail("No input image selected");
return ic.getImage();
}
static public boolean isInteger(String s) {
int n = l(s);
if (n == 0)
return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n)
return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9')
return false;
++i;
}
return true;
}
static public boolean is(String a, String b) {
return false;
}
static public RasterBars reproduceRasterBars(IBWIntegralImage ii) {
var thinImage = scaledBWImageFromBWIntegralImage_withMeta(ii, 1, ii.getHeight());
var streaks = streaksOfRepeatingElements(listFromFunction(thinImage.getHeight(), y -> thinImage.getInt(0, y)));
return new RasterBars(ii.getWidth(), ii.getHeight(), streaks);
}
static public Value value(A a) {
return new Value (a);
}
static public String sfuIndent(Object o) {
return sfuIndent(Integer.MAX_VALUE, o);
}
static public String sfuIndent(int levels, Object o) {
return indentedStructureForUser(levels, o);
}
static public Rect toRect_round(DoubleRect r) {
if (r == null)
return null;
int x = iround(r.x), y = iround(r.y);
return new Rect(x, y, iround(r.x2()) - x, iround(r.y2()) - y);
}
static public Rect scaleRect(Rect r, double factorX, double factorY) {
return rectFromPoints(iround(r.x * factorX), iround(r.y * factorY), iround(r.x2() * factorX), iround(r.y2() * factorY));
}
static public Rect scaleRect(Rect r, double factor) {
return scaleRect(r, factor, factor);
}
static public Rect scaleRect(double factor, Rect r) {
return scaleRect(r, factor);
}
static public DoubleRect scaleRect(DoubleRect r, double factorX, double factorY) {
return doubleRect(r.x * factorX, r.y * factorY, r.w * factorX, r.h * factorY);
}
static public DoubleRect scaleRect(double factorX, double factorY, DoubleRect r) {
return scaleRect(r, factorX, factorY);
}
static public DoubleRect doubleRectFromPoints(double x1, double y1, double x2, double y2) {
return new DoubleRect(x1, y1, x2 - x1, y2 - y1);
}
static public RuntimeException todo() {
throw new RuntimeException("TODO");
}
static public RuntimeException todo(Object msg) {
throw new RuntimeException("TODO: " + msg);
}
static public Pt toPt(Point p) {
return p == null ? null : new Pt(p.x, p.y);
}
static public Pt toPt(Dimension d) {
return d == null ? null : new Pt(d.width, d.width);
}
static public WeakReference weakRef(A a) {
return newWeakReference(a);
}
static public int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
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 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 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 Area bitMatrixToArea(Matrix m) {
return scanlineBitMatrixToArea(toScanlineBitMatrix(m));
}
static public Color colorWithAlpha(Color c, double alpha) {
return new Color(c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, (float) clampZeroToOne(alpha));
}
static public Color colorWithAlpha(double alpha, Color c) {
return colorWithAlpha(c, alpha);
}
static public Random getRandomizer(Random r) {
return r != null ? r : defaultRandomGenerator();
}
static public A oneOf(List l) {
return empty(l) ? null : l.get(new Random().nextInt(l.size()));
}
static public char oneOf(String s) {
return empty(s) ? '?' : s.charAt(random(l(s)));
}
static public String oneOf(String... l) {
return oneOf(asList(l));
}
static public A collectionGet(Collection c, int idx) {
if (c == null || idx < 0 || idx >= l(c))
return null;
if (c instanceof List)
return listGet((List ) c, idx);
Iterator it = c.iterator();
for (int i = 0; i < idx; i++) if (it.hasNext())
it.next();
else
return null;
return it.hasNext() ? it.next() : null;
}
static public Pair entryToPair(Map.Entry e) {
return mapEntryToPair(e);
}
static public Set> entries(Map map) {
return _entrySet(map);
}
static public Random defaultRandomizer() {
return defaultRandomGenerator();
}
static public ThreadLocal imageGraphics_antiAlias = new ThreadLocal();
static public Graphics2D imageGraphics(BufferedImage img) {
return !isFalse(imageGraphics_antiAlias.get()) ? antiAliasGraphics(img) : createGraphics(img);
}
static public void setTrayIconToolTip(TrayIcon trayIcon, String toolTip) {
if (trayIcon != null)
trayIcon.setToolTip(toolTip);
}
static public Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
static public Method findMethodNamed(Object obj, String method) {
if (obj == null)
return null;
if (obj instanceof Class)
return findMethodNamed((Class) obj, method);
return findMethodNamed(obj.getClass(), method);
}
static public Method findMethodNamed(Class c, String method) {
while (c != null) {
for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) {
makeAccessible(m);
return m;
}
c = c.getSuperclass();
}
return null;
}
static public int hashMap_internalHash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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 Map _registerThread_threads;
static public Object _onRegisterThread;
static public Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static public void _registerThread() {
_registerThread(Thread.currentThread());
}
static public Object 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 List syncCloneAndClearList(Collection l) {
if (l == null)
return emptyList();
synchronized (collectionMutex(l)) {
List l2 = cloneList(l);
l.clear();
return l2;
}
}
static public Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
static public void cancelThread(Thread t) {
if (t == null)
return;
ping();
synchronized (ping_actions) {
ping_actions.put(t, "cancelled");
ping_anyActions = true;
}
}
static public TreeMap caseInsensitiveMap() {
return new TreeMap(caseInsensitiveComparator());
}
static public JPanel westAndCenter(final Component w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.WEST, wrap(w));
panel.add(BorderLayout.CENTER, wrap(c));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST...";
}
});
}
static public JPanel westAndCenterWithMargin(Component w, Component c) {
return westAndCenter(withRightMargin(w), c);
}
static public JPanel westAndCenterWithMargin(int margin, Component w, Component c) {
return westAndCenter(withRightMargin(margin, w), c);
}
static public String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
static public String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
static public String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return l.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret l.getText();";
}
});
}
static public String getText(final JComboBox cb) {
if (cb == null)
return null;
if (isEditableComboBox(cb))
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
static public JComboBox selectItem(A item, JComboBox cb) {
if (cb != null) {
swing(new Runnable() {
public void run() {
try {
cb.setSelectedItem(item);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.setSelectedItem(item);";
}
});
}
return cb;
}
static public JComboBox selectItem(JComboBox cb, A item) {
return selectItem(item, cb);
}
static public JList selectItem(JList list, A item) {
{
swing(new Runnable() {
public void run() {
try {
selectRow(list, jlist_indexOf(list, item));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "selectRow(list, jlist_indexOf(list, item));";
}
});
}
return list;
}
static public A centerTextField(A tf) {
tf.setHorizontalAlignment(JTextField.CENTER);
return tf;
}
static public JLabel jcenteredLabel(String text) {
return setHorizontalAlignment(JLabel.CENTER, jLabel(text));
}
static public JLabel jcenteredLabel() {
return jcenteredLabel(" ");
}
static public A optCast(Class c, Object o) {
return isInstance(c, o) ? (A) o : null;
}
static public LinkedHashMap cloneLinkedHashMap(Map map) {
return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
}
static public B syncGetOrCreate(Map map, A key, Class extends B> c) {
try {
synchronized (map) {
return getOrCreate(map, key, c);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public B syncGetOrCreate(Map map, A key, Object f) {
synchronized (map) {
return getOrCreate(map, key, f);
}
}
static public B syncGetOrCreate(Class extends B> c, Map map, A key) {
return syncGetOrCreate(map, key, c);
}
static public B syncGetOrCreate(Map map, A key, IF0 f) {
synchronized (map) {
return getOrCreate(map, key, f);
}
}
static public JTextField jLiveValueTextField_bothWays(final SimpleLiveValue lv) {
final JTextField ta = jTextField();
bindTextComponentToLiveValue_bothWays(ta, lv);
return ta;
}
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 void setCaretPosition(final JTextComponent c, final int pos) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
try {
int _pos = max(0, min(l(c.getText()), pos));
c.setCaretPosition(_pos);
} catch (Throwable __e) {
printStackTrace(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall {\r\n int _pos = max(0, min(l(c.getText()), pos));\r\n c.setCaret...";
}
});
}
}
static public float bwImageSimilarityResized(BWImage a, BWImage b, float similarityRequired) {
int aw = a.w(), ah = a.h();
int bw = b.w(), bh = b.h();
int wp = max(aw, bw), hp = max(ah, bh);
float ratio1 = ((float) aw) / ah, ratio2 = ((float) bw) / bh;
float mismatch = ratio1 / ratio2;
if (mismatch < 1f)
mismatch = 1f / mismatch;
float factor = wp * hp / mismatch;
float maxError = (1f - similarityRequired) * factor;
float diff = 0;
for (int y = 0; y < hp; y++) for (int x = 0; x < wp; x++) {
diff += Math.abs(a.getPixel(x * aw / wp, y * ah / hp) - b.getPixel(x * bw / wp, y * bh / hp));
if (diff > maxError)
return similarityRequired - 0.001f;
}
return 1f - diff / factor;
}
static public BWImage toBW(RGBImage img) {
return img == null ? null : new BWImage(img);
}
static public String formatDoubleFull(double d, int digits) {
String format = digits <= 0 ? "0" : "0." + rep(digits, '0');
return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d);
}
static public Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
static public Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
static public String baseClassName(String className) {
return substring(className, className.lastIndexOf('.') + 1);
}
static public String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
static public String prependIfNempty(String prefix, String s) {
return empty(s) ? unnull(s) : prefix + s;
}
static public ButtonGroup jradiobuttons(Collection strings) {
return selectFirstRadioButton(jUnselectedRadioButtons(strings));
}
static public ButtonGroup jradiobuttons(String... strings) {
return jradiobuttons(asList(strings));
}
static public int selectedButtonIdx(ButtonGroup g) {
List l = buttonsInGroup(g);
for (int i = 0; i < l(l); i++) if (l.get(i).isSelected())
return i;
return -1;
}
static public int incAtomicInt(AtomicInteger i) {
return i.incrementAndGet();
}
static public int incAtomicInt(AtomicInteger i, int delta) {
return i.addAndGet(delta);
}
static public long incAtomicLong(AtomicLong l) {
return l.incrementAndGet();
}
static public void printVars_str(Object... params) {
print(renderVars_str(params));
}
static public long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static public boolean showTitledForm_blocking(String title, Object... _parts) {
assertNotOnAWTThread();
final Var var = new Var();
onFrameClose(showFormTitled(title, arrayPlus(_parts, new Runnable() {
public void run() {
try {
var.set(true);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "var.set(true)";
}
})), new Runnable() {
public void run() {
try {
if (!var.has())
var.set(false);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!var.has()) var.set(false)";
}
});
waitUntilVarSet(var);
return var.get();
}
static public List> streaksOfRepeatingElements(List l) {
List> out = new ArrayList();
int i = 0, n = l(l);
while (i < n) {
A a = l.get(i);
int j = i + 1;
while (j < n && eq(a, l.get(j))) ++j;
out.add(pair(intRange(i, j), a));
i = j;
}
return out;
}
static public List listFromFunction(int n, IF1 f) {
return new RandomAccessAbstractList() {
public int size() {
return n;
}
public A get(int i) {
return f.get(i);
}
};
}
static public List listFromFunction(IF1 f, int n) {
return listFromFunction(n, f);
}
static public String indentedStructureForUser(Object o) {
return indentedStructureForUser(Integer.MAX_VALUE, o);
}
static public String indentedStructureForUser(int levels, Object o) {
return indentStructureString(levels, structForUser(o));
}
static public DoubleRect doubleRect(double w, double h) {
return new DoubleRect(0, 0, w, h);
}
static public DoubleRect doubleRect(double x, double y, double w, double h) {
return new DoubleRect(x, y, w, h);
}
static public WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
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 Area scanlineBitMatrixToArea(ScanlineBitMatrix m) {
return joinAreas(map(__43 -> toRectangle(__43), m.runs()));
}
static public ScanlineBitMatrix toScanlineBitMatrix(Matrix m) {
if (m == null)
return null;
if (m instanceof ScanlineBitMatrix)
return ((ScanlineBitMatrix) m);
return new ScanlineBitMatrix(m);
}
static public float clampZeroToOne(float x) {
return x < 0 ? 0 : x > 1 ? 1 : x;
}
static public double clampZeroToOne(double x) {
return x < 0 ? 0 : x > 1 ? 1 : x;
}
static public Random defaultRandomGenerator() {
return ThreadLocalRandom.current();
}
static public