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.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
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.structure;
import static loadableUtils.utils.structureToPrintWriter;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.tablePopupMenuFirst;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.dynamicObjectIsLoading;
import static loadableUtils.utils.rethrow;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.IVF2;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
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.IConceptIndex;
import loadableUtils.utils.IConceptCounter;
import loadableUtils.utils.IterableIterator;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.GlobalID;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import static loadableUtils.utils.db_mainConcepts;
import static loadableUtils.utils.db_setMainConcepts;
import static loadableUtils.utils.fixNewLines;
import static loadableUtils.utils.sfu;
import static loadableUtils.utils.getExceptionCause;
import static loadableUtils.utils.joinWithSpace;
import static loadableUtils.utils.callF;
import static loadableUtils.utils.javaTok;
import static loadableUtils.utils.interceptPrintInThisThread;
import static loadableUtils.utils.jlabel;
import static loadableUtils.utils.join;
import static loadableUtils.utils.isAWTThread;
import static loadableUtils.utils.set;
import static loadableUtils.utils.call;
import static loadableUtils.utils.fail;
import static loadableUtils.utils.print;
import static loadableUtils.utils.printAlsoToSystemOut;
import static loadableUtils.utils.doLater;
import static loadableUtils.utils.cget;
import static loadableUtils.utils.db;
import loadableUtils.utils.LongRange;
import loadableUtils.utils.IntRange;
import loadableUtils.utils.MultiMap;
import loadableUtils.utils.Meta;
import loadableUtils.utils.ITokCondition;
import loadableUtils.utils.PingSource;
import loadableUtils.utils.ThreadPool;
import loadableUtils.utils.SimpleLiveValue;
import loadableUtils.utils.Matrix;
import loadableUtils.utils.Best;
import loadableUtils.utils.IRef;
import loadableUtils.utils.F2;
import loadableUtils.utils.RandomAccessAbstractList;
import loadableUtils.utils.IBWIntegralImage;
import loadableUtils.utils.Producer;
import loadableUtils.utils.IntBuffer;
import loadableUtils.utils.Cache;
import loadableUtils.utils.AbstractMatrix;
import loadableUtils.utils.OKOrError;
import loadableUtils.utils.WithTimestamp;
import loadableUtils.utils.IMeta;
import loadableUtils.utils.LiveValue;
import loadableUtils.utils.Timestamp;
import loadableUtils.utils.DoubleRect;
import loadableUtils.utils.Complex;
import loadableUtils.utils.Either;
import loadableUtils.utils.Steppable;
import loadableUtils.utils.T3;
import loadableUtils.utils.Swingable;
import loadableUtils.utils.JavaXClassLoader;
import loadableUtils.utils.Average;
import loadableUtils.utils.BWIntegralImage;
import loadableUtils.utils.DoubleRange;
import loadableUtils.utils.Seconds;
import loadableUtils.utils.Scored;
import static loadableUtils.utils.withTimestamp;
import static loadableUtils.utils.score;
import static loadableUtils.utils.stepAll;
import static loadableUtils.utils.isRunnableX;
import static loadableUtils.utils.wrappedTextArea;
import static loadableUtils.utils.infoMessage;
import static loadableUtils.utils.brightnessToRGBA;
import static loadableUtils.utils.withBorder;
import static loadableUtils.utils.sorted;
import static loadableUtils.utils.rcallOpt;
import static loadableUtils.utils.childrenOfType;
import static loadableUtils.utils.unCurlyBracket;
import static loadableUtils.utils.isA;
import static loadableUtils.utils.nanoTime;
import static loadableUtils.utils.activateFrame_v3;
import static loadableUtils.utils.b;
import static loadableUtils.utils.ewicOneOf;
import static loadableUtils.utils.jCenteredSection;
import static loadableUtils.utils.dm_fieldLabel;
import static loadableUtils.utils.n;
import static loadableUtils.utils.abs;
import static loadableUtils.utils.prepareProgramFile;
import static loadableUtils.utils.callMain;
import static loadableUtils.utils.evalJava_prep;
import static loadableUtils.utils.caseInsensitiveComparator;
import static loadableUtils.utils.getComponents;
import static loadableUtils.utils.rep;
import static loadableUtils.utils.area;
import static loadableUtils.utils.add;
import static loadableUtils.utils.singleComponentPanel;
import static loadableUtils.utils.simpleDateFormat_local;
import static loadableUtils.utils.withMargin;
import static loadableUtils.utils.addActionListener;
import static loadableUtils.utils.hasMethod;
import static loadableUtils.utils.countIteratorToList;
import static loadableUtils.utils.containsOneOf;
import static loadableUtils.utils.setFrameIconLater;
import static loadableUtils.utils.intersectRects;
import static loadableUtils.utils.setSCPComponent;
import static loadableUtils.utils.hideWindow;
import static loadableUtils.utils.ymdMinusHMS;
import static loadableUtils.utils.withLeftMargin;
import static loadableUtils.utils.pingSource_tl;
import static loadableUtils.utils.jPopDownButton_noText;
import static loadableUtils.utils.swingLater;
import static loadableUtils.utils.currentImage;
import static loadableUtils.utils._defaultClassFinder;
import static loadableUtils.utils.boolOptParam;
import static loadableUtils.utils.getOptMC;
import static loadableUtils.utils.setImage;
import static loadableUtils.utils.regexp;
import static loadableUtils.utils.alwaysOnTop;
import static loadableUtils.utils.setFrameTitle;
import static loadableUtils.utils._inCore;
import static loadableUtils.utils.getScreenWidth;
import static loadableUtils.utils.tsNow;
import static loadableUtils.utils.boundsOnScreen;
import static loadableUtils.utils.jfind_preprocess;
import static loadableUtils.utils.formatFunctionCall;
import static loadableUtils.utils.dm_reload;
import static loadableUtils.utils.fileInSameDir;
import static loadableUtils.utils.setFrameIcon;
import static loadableUtils.utils.isIdentifier;
import static loadableUtils.utils.getSnippetTitle;
import static loadableUtils.utils.getTimeZone;
import static loadableUtils.utils.jFullCenter;
import static loadableUtils.utils.dm_fieldCheckBox;
import static loadableUtils.utils.classNamesInJarOrDir;
import static loadableUtils.utils.scaffoldingEnabled;
import static loadableUtils.utils.indent;
import static loadableUtils.utils.infoBox;
import static loadableUtils.utils.toSeconds;
import static loadableUtils.utils.rect;
import static loadableUtils.utils.cleanUp;
import static loadableUtils.utils.dm_stem;
import static loadableUtils.utils.forEach;
import static loadableUtils.utils.disposeWindow;
import static loadableUtils.utils.getScore;
import static loadableUtils.utils.moveToTopRightCorner;
import static loadableUtils.utils.stdcompare;
import static loadableUtils.utils.centerAndEast;
import static loadableUtils.utils.metaMapPut;
import static loadableUtils.utils.makeFrame;
import static loadableUtils.utils.okOrError;
import static loadableUtils.utils.setDoubleBuffered;
import static loadableUtils.utils.asVirtualList;
import static loadableUtils.utils.bufferedImage;
import static loadableUtils.utils.mapToObjectArray;
import static loadableUtils.utils.maximumSafeArraySize;
import static loadableUtils.utils.dm_q;
import static loadableUtils.utils.javaTokForJFind_array;
import static loadableUtils.utils.withLeftAndRightMargin;
import static loadableUtils.utils.childOfType;
import static loadableUtils.utils.shortName;
import static loadableUtils.utils.findTranslators2;
import static loadableUtils.utils.ping_v3;
import static loadableUtils.utils.emptyIterableIterator;
import static loadableUtils.utils.flattenArray2;
import static loadableUtils.utils.formatDouble;
import static loadableUtils.utils.getParent;
import static loadableUtils.utils.strOrEmpty;
import static loadableUtils.utils.pqO;
import static loadableUtils.utils.shorten_str;
import static loadableUtils.utils.run;
import static loadableUtils.utils.has;
import static loadableUtils.utils.last;
import static loadableUtils.utils.caseInsensitiveSet;
import static loadableUtils.utils.checkCondition;
import static loadableUtils.utils.warn;
import static loadableUtils.utils.distance;
import static loadableUtils.utils.jrightAlignedLine;
import static loadableUtils.utils.toRect;
import static loadableUtils.utils.synchroSet;
import static loadableUtils.utils.formatDouble_significant2;
import static loadableUtils.utils.installWindowDragger;
import static loadableUtils.utils.addIfNotNull;
import static loadableUtils.utils.isString;
import static loadableUtils.utils.installTimer;
import static loadableUtils.utils.setAdd;
import static loadableUtils.utils.clipBufferedImage;
import static loadableUtils.utils.formatDouble1;
import static loadableUtils.utils.setText;
import static loadableUtils.utils.vmBus_timerStarted;
import static loadableUtils.utils.splitAtSpace;
import static loadableUtils.utils.getBounds;
import static loadableUtils.utils.northAndCenterWithMargin;
import static loadableUtils.utils.getAndClearList;
import static loadableUtils.utils.loadTextFileResource;
import static loadableUtils.utils.renderUserThreadsWithStackTraces;
import static loadableUtils.utils.nBytes;
import static loadableUtils.utils.newConceptsWithClassFinder;
import static loadableUtils.utils.replaceSublist;
import static loadableUtils.utils.selectedItem;
import static loadableUtils.utils.codeTokensOnly;
import static loadableUtils.utils.isSpaceEtc;
import static loadableUtils.utils.joinSubList;
import static loadableUtils.utils.javaTokC;
import static loadableUtils.utils.onSelectedItem;
import static loadableUtils.utils.muricaCredentials;
import static loadableUtils.utils.onUpdate;
import static loadableUtils.utils.hotwire_copyOver;
import static loadableUtils.utils.replace;
import static loadableUtils.utils.profileToConsole;
import static loadableUtils.utils.myLibraryFiles;
import static loadableUtils.utils.nChars;
import static loadableUtils.utils.findCodeTokens;
import static loadableUtils.utils.withTypeWriterFont;
import static loadableUtils.utils.printWithMS;
import static loadableUtils.utils.setSplitPaneOnFirstShowing;
import static loadableUtils.utils.format;
import static loadableUtils.utils.heightForWidth;
import static loadableUtils.utils.onEnter;
import static loadableUtils.utils.hsplit;
import static loadableUtils.utils.changeListener;
import static loadableUtils.utils.containsNewLine;
import static loadableUtils.utils.centerAndEastWithMargin;
import static loadableUtils.utils.getFrame;
import static loadableUtils.utils.countIterator_exclusive;
import static loadableUtils.utils.centerAndSouth;
import static loadableUtils.utils.jhsplit;
import static loadableUtils.utils.dm_fieldLiveValue;
import static loadableUtils.utils.findAllFiles_noDirs;
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.allScreenBounds;
import static loadableUtils.utils.findClass_fullName;
import static loadableUtils.utils.withBottomMargin;
import static loadableUtils.utils.typeWriterFont;
import static loadableUtils.utils.javaCompile_overInternalBot;
import static loadableUtils.utils.copyLocalLog;
import static loadableUtils.utils.jscroll_centered;
import static loadableUtils.utils.parentFile;
import static loadableUtils.utils.listSet;
import static loadableUtils.utils.hfulltag;
import static loadableUtils.utils.gazelle_wavySpacer;
import static loadableUtils.utils.getCanonicalPath;
import static loadableUtils.utils.callOnLoadMethods;
import static loadableUtils.utils.dm_rEnter;
import static loadableUtils.utils.reTok;
import static loadableUtils.utils.toString;
import static loadableUtils.utils.callCalc;
import static loadableUtils.utils.mapI_if1;
import static loadableUtils.utils.squareBracket;
import static loadableUtils.utils.isQuoted;
import static loadableUtils.utils.applyDefaultMargin;
import static loadableUtils.utils.isDigit;
import static loadableUtils.utils.dm_callOS;
import static loadableUtils.utils.loadTextFileFromZip;
import static loadableUtils.utils.regionMatches;
import static loadableUtils.utils.warnIfOddCount;
import static loadableUtils.utils.logQuoted;
import static loadableUtils.utils.loadLibraries;
import static loadableUtils.utils.printFileInfo;
import static loadableUtils.utils.dm_callOSOpt;
import static loadableUtils.utils.bindLiveValueListenerToComponent;
import static loadableUtils.utils.getPreferredWidth;
import static loadableUtils.utils.screenBounds;
import static loadableUtils.utils.callStringifier;
import static loadableUtils.utils.toRectangle;
import static loadableUtils.utils.allMethodNames;
import static loadableUtils.utils.widthForHeight;
import static loadableUtils.utils.centerLabel;
import static loadableUtils.utils.javaxCodeDir;
import static loadableUtils.utils.jLiveValueLabel;
import static loadableUtils.utils.combineAutoCloseables;
import static loadableUtils.utils.shortClassName_dropNumberPrefix;
import static loadableUtils.utils.identityHashCode;
import static loadableUtils.utils.minimizeWindow;
import static loadableUtils.utils.appendToFileBaseName;
import static loadableUtils.utils.jbutton;
import static loadableUtils.utils.addDyn;
import static loadableUtils.utils.setEnabled;
import static loadableUtils.utils.functionCall;
import static loadableUtils.utils.javaTokForStructure;
import static loadableUtils.utils.isCISet;
import static loadableUtils.utils.northAndCenter;
import static loadableUtils.utils.jline;
import static loadableUtils.utils.toMS;
import static loadableUtils.utils.cancelTimer;
import static loadableUtils.utils.creator;
import static loadableUtils.utils.vmBus_query;
import static loadableUtils.utils.change;
import static loadableUtils.utils.assertEquals;
import static loadableUtils.utils.clearAllTokens;
import static loadableUtils.utils.toPath;
import static loadableUtils.utils.getPreferredSize;
import static loadableUtils.utils.unicode_downPointingTriangle;
import static loadableUtils.utils.jLiveValueCheckBox;
import static loadableUtils.utils.md5;
import static loadableUtils.utils.getBorder;
import static loadableUtils.utils.getLookAndFeel;
import static loadableUtils.utils.renderFileInfo;
import static loadableUtils.utils.jCheckBoxMenuItem;
import static loadableUtils.utils.appendToFile;
import static loadableUtils.utils.find;
import static loadableUtils.utils.jenableUndoRedo;
import static loadableUtils.utils.setChecked;
import static loadableUtils.utils.setFont;
import static loadableUtils.utils.syncList;
import static loadableUtils.utils.takeFirst;
import static loadableUtils.utils.isEditableComboBox;
import static loadableUtils.utils.numberOfCores;
import static loadableUtils.utils.showWindow;
import static loadableUtils.utils.plus;
import static loadableUtils.utils.dm_watchField;
import static loadableUtils.utils.fillJPopupMenu;
import static loadableUtils.utils.hotwire_makeClassLoader;
import static loadableUtils.utils.codeTokensAsStringArray;
import static loadableUtils.utils.ifloor;
import static loadableUtils.utils.hmsWithColonsAndMS;
import static loadableUtils.utils.blend;
import static loadableUtils.utils.smartIndexOf;
import static loadableUtils.utils.indexOf;
import static loadableUtils.utils.repeat;
import static loadableUtils.utils.structureForUser;
import static loadableUtils.utils.ok;
import static loadableUtils.utils.nohup;
import static loadableUtils.utils.jCheckBox;
import static loadableUtils.utils.toMS_int;
import static loadableUtils.utils.onWindowClosing;
import static loadableUtils.utils.asArray;
import static loadableUtils.utils.pt;
import static loadableUtils.utils.showText;
import static loadableUtils.utils.setDefaultClassFinder;
import static loadableUtils.utils.countLines;
import static loadableUtils.utils.isCurlyBracketed;
import static loadableUtils.utils.getBytecodePathForClass;
import static loadableUtils.utils.transpileRaw_makeTranslator;
import static loadableUtils.utils.standardCredentials;
import static loadableUtils.utils.installWindowResizeDraggerOnBorder;
import static loadableUtils.utils.singular;
import static loadableUtils.utils.minus;
import static loadableUtils.utils.syncAddOrCreate;
import static loadableUtils.utils.fileNameEncode;
import static loadableUtils.utils.reversedList;
import static loadableUtils.utils.intRange;
import static loadableUtils.utils.getScreenHeight;
import static loadableUtils.utils.ratio;
import static loadableUtils.utils.countIterator;
import static loadableUtils.utils.boolPar;
import static loadableUtils.utils.fillRect;
import static loadableUtils.utils.westCenterAndEastWithMargin;
import static loadableUtils.utils.indentx;
import static loadableUtils.utils.getSelectedItem;
import static loadableUtils.utils.isChecked;
import static loadableUtils.utils.similarEmptyMap;
import static loadableUtils.utils.toFile;
import static loadableUtils.utils.tempAdd;
import static loadableUtils.utils.onMouseDown;
import static loadableUtils.utils.tempDisposeWindow;
import static loadableUtils.utils.pixelCount;
import static loadableUtils.utils.pairA;
import static loadableUtils.utils.appendToBaseName;
import static loadableUtils.utils.dropFirst;
import static loadableUtils.utils.newWeakHashSet;
import static loadableUtils.utils.mod;
import static loadableUtils.utils.squareBracketed;
import static loadableUtils.utils.makeUndecoratedFrame;
import static loadableUtils.utils.subByteArray;
import static loadableUtils.utils.findClass;
import static loadableUtils.utils.humanizeFormLabel;
import static loadableUtils.utils.addSuffix;
import static loadableUtils.utils.wrapForSmartAdd;
import static loadableUtils.utils.asSet;
import static loadableUtils.utils.autoFrameTitle;
import static loadableUtils.utils.westCenterAndEast;
import static loadableUtils.utils.restart;
import static loadableUtils.utils.installTrayIcon;
import static loadableUtils.utils.shootScreen2;
import static loadableUtils.utils.filter;
import static loadableUtils.utils.syncLinkedHashSet;
import static loadableUtils.utils.mapPut;
import static loadableUtils.utils.onChange;
import static loadableUtils.utils.pingSource;
import static loadableUtils.utils.mapToParams;
import static loadableUtils.utils.isNonEmptySingleZip_byMagicHeader;
import static loadableUtils.utils.isInQ;
import static loadableUtils.utils.uniqueFileNameUsingMD5_80_v2;
import static loadableUtils.utils.isMenuSeparatorIndicator;
import static loadableUtils.utils.applyMargin;
import static loadableUtils.utils.withTopMargin;
import static loadableUtils.utils.dirOfFile;
import static loadableUtils.utils.error;
import static loadableUtils.utils.setBackground;
import static loadableUtils.utils.sysNow;
import static loadableUtils.utils.elapsedSeconds;
import static loadableUtils.utils.bigint;
import static loadableUtils.utils.hotwire;
import static loadableUtils.utils.metaGet;
import static loadableUtils.utils.heldInstance;
import static loadableUtils.utils.nestedIterator;
import static loadableUtils.utils.trayIcon_imageAutoSize;
import loadableUtils.utils.Pair;
import loadableUtils.utils.BetterThreadLocal;
import loadableUtils.utils.IBWImage;
import loadableUtils.utils.WidthAndHeight;
import loadableUtils.utils.Enterable;
import loadableUtils.utils.SimpleCRUD_v2;
import static loadableUtils.utils.getPrintLog;
import static loadableUtils.utils.unstructure;
import static loadableUtils.utils.StefansOS_ConnectToServer;
import static loadableUtils.utils._MethodCache;
import static loadableUtils.utils.defaultMargin;
import static loadableUtils.utils.preferredScreen;
import static loadableUtils.utils.showForm_makeFrame;
import loadableUtils.utils.Decolorizer;
import javax.swing.border.*;
import com.github.sarxos.webcam.*;
import java.awt.datatransfer.StringSelection;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.text.NumberFormat;
import java.awt.geom.*;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import net.lingala.zip4j.model.*;
import net.lingala.zip4j.io.outputstream.*;
import net.lingala.zip4j.model.enums.*;
import net.lingala.zip4j.headers.*;
import net.lingala.zip4j.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import org.fife.ui.autocomplete.*;
import org.fife.rsta.ui.CollapsibleSectionPanel;
import org.fife.rsta.ui.GoToDialog;
import org.fife.rsta.ui.SizeGripIcon;
import org.fife.rsta.ui.search.FindDialog;
import org.fife.rsta.ui.search.ReplaceDialog;
import org.fife.rsta.ui.search.ReplaceToolBar;
import org.fife.rsta.ui.search.SearchEvent;
import org.fife.rsta.ui.search.SearchListener;
import org.fife.rsta.ui.search.FindToolBar;
import org.fife.ui.rsyntaxtextarea.ErrorStrip;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;
import org.fife.ui.rtextarea.SearchContext;
import org.fife.ui.rtextarea.SearchEngine;
import org.fife.ui.rtextarea.SearchResult;
import org.fife.ui.rsyntaxtextarea.*;
import java.text.*;
import java.awt.datatransfer.*;
import java.awt.geom.AffineTransform;
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 pixelRows = 128, colors = 8;
public String script = "64p 8c gradientImage";
public String newScript;
public String screenCamScript;
public String selectedTab;
public String javaCode;
public boolean horizontalLayout = false;
public int fpsTarget = 20;
public String webCamName;
public boolean webCamAccessEnabled = true;
public WatchTarget watchTarget;
public G22_TestScreenPanel testScreen = new G22_TestScreenPanel();
transient public ImageSurface isPosterized;
transient public ScreenCamStream imageStream = new ScreenCamStream();
transient public Gazelle22_ImageToRegions imageToRegions_finished;
transient public DoubleFPSCounter fpsCounter = new DoubleFPSCounter();
transient public int fps;
transient public WatchTargetSelector watchTargetSelector;
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 UIURLSystem uiURLs;
transient public JComboBox cbWebCam;
transient public SingleComponentPanel scpWebCamImage;
transient public WebcamPanel webCamPanel;
transient public JLeftArrowScriptIDE screenCamScriptIDE;
transient public GazelleV_LeftArrowScript.Script runningScreenCamScript;
transient public Concepts concepts;
public String uiURL = "Main Tabs";
transient public FileWatchService fileWatcher;
transient public SimpleCRUD_v2 labelCRUD;
transient public SimpleCRUD_v2 imageCRUD;
transient public JComponent imageCRUDVis;
transient public JGallery gallery;
transient public JComponent galleryComponent;
transient public FlexibleRateTimer screenCamTimer;
transient public SingleComponentPanel scpMain;
transient public JTabbedPane mainTabs;
transient public boolean showRegionsAsOutline = true;
transient public JComponent watchScreenPane;
transient public String screenCamRecognitionOutput;
transient public G22Utils g22utils = new G22Utils();
transient public BackgroundProcessesUI backgroundProcessesUI;
transient public BackgroundProcessesUI.Entry bgScreenCam = new BackgroundProcessesUI.Entry("Screen Cam").menuItem(jMenuItem("Screen Cam", new Runnable() {
public void run() {
try {
showScreenCam();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "showScreenCam();";
}
}));
transient public BackgroundProcessesUI.Entry bgWebCam = new BackgroundProcessesUI.Entry("Web Cam").menuItem(jMenuItem("Web Cam", new Runnable() {
public void run() {
try {
showWebCam();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "showWebCam();";
}
}));
public boolean autoRunChallenge = true;
transient public G22ChallengesPanel challengesPanel;
transient public JComponent urlBar;
public void start() {
try {
super.start();
testScreen.onChange(() -> change());
dm_onFieldChange("horizontalLayout", new Runnable() {
public void run() {
try {
dm_reload();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_reload();";
}
});
if (concepts == null) {
printWithMS("Starting DB");
db();
concepts = db_mainConcepts();
} else
assertSame(concepts, db_mainConcepts());
concepts.quietSave = true;
indexConceptField(concepts, GalleryImage.class, "path");
indexConceptField(concepts, Example.class, "item");
g22utils.concepts(concepts);
g22utils.modifyLeftArrowParser = __7 -> modifyLeftArrowParser(__7);
g22utils.basicParserTest();
onConceptChanges(concepts, () -> {
{
if (labelCRUD != null)
labelCRUD.updateEnclosingTabTitle();
}
updateEnclosingTabTitleWithCount(galleryComponent, countConcepts(GalleryImage.class));
});
uiURLs = new UIURLSystem(me(), dm_fieldLiveValue("uiURL"));
uiURLs.addPreferredUIURL("Main Tabs");
backgroundProcessesUI = new BackgroundProcessesUI();
dm_watchFieldAndNow("enabled", () -> backgroundProcessesUI.addOrRemove(enabled, bgScreenCam));
scriptRunner = new JGazelleVScriptRunner(dm_fieldLiveValue("script", me()));
printWithMS("Making image stream");
imageStream.onNewElement(img -> {
fpsCounter.inc();
setField("fps", iround(fpsCounter.get()));
assertTrue("meta", getMetaSrc(img) instanceof ScreenShotMeta);
Gazelle22_ImageToRegions itr = new Gazelle22_ImageToRegions(functionTimings, img, new SnPSettings(pixelRows, colors));
itr.run();
imageToRegions_finished = itr;
if (shouldRunScript())
rstRunScript.go();
if (screenCamScriptIDE != null && screenCamScriptIDE.visible())
try {
g22_runPostAnalysisLeftArrowScript(itr, runningScreenCamScript);
} catch (Throwable e) {
printStackTrace(e);
screenCamScriptIDE.showRuntimeError(e);
}
String text = nRegions(itr.regions.regionCount());
setField("screenCamRecognitionOutput", text);
g22_renderPosterizedHighlightedImage(isPosterized, itr, showRegionsAsOutline);
});
watchTargetSelector = new WatchTargetSelector();
printWithMS("Starting screen cam");
ownResource(screenCamTimer = new FlexibleRateTimer(fpsTarget, new Runnable() {
public void run() {
try {
AutoCloseable __1 = enter();
try {
if (!enabled)
return;
{
if (watchTargetSelector != null)
watchTargetSelector.updateScreenCount();
}
Timestamp deadline = tsNowPlusMS(1000 / fpsTarget);
{
if (watchTarget != null)
watchTarget.mainWindow(getWindow(urlBar));
}
{
if (watchTarget != null)
watchTarget.configureScreenCamStream(imageStream);
}
imageStream.step();
long remaining = deadline.minus(tsNow());
remainingMSPerFrame.add(remaining);
setField("remainingMS", iround(remainingMSPerFrame.get()));
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); \n if (!enabled) return;\n watchTargetSelector?.updateS...";
}
}));
screenCamTimer.start();
dm_onFieldChange("fpsTarget", () -> screenCamTimer.setFrequencyImmediately(fpsTarget));
printWithMS("Starting dir watcher");
startDirWatcher();
printWithMS("Gathering images from disk");
for (var f : allImageFiles(galleryDir())) addToGallery(f);
printWithMS("Got dem images");
transpileRaw_makeTranslator = () -> hotwire("#7");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void startDirWatcher() {
fileWatcher = new FileWatchService();
fileWatcher.addRecursiveListener(picturesDir(), file -> {
if (!isImageFile(file))
return;
addToGallery(file);
});
}
public JComponent visualize() {
gallery = new JGallery();
galleryComponent = gallery.visualize();
new AWTOnConceptChanges(concepts, galleryComponent, () -> {
gallery.setImageFiles(map(list(GalleryImage.class), i -> i.path));
}).install();
isPosterized = g22utils.stdImageSurface();
labelCRUD = new SimpleCRUD_v2(concepts, Label.class);
labelCRUD.hideFields("globalID");
labelCRUD.addCountToEnclosingTab(true);
labelCRUD.itemToMap_inner2 = l -> litorderedmap("Name", l.name, "# Examples", n2(countConcepts(concepts, Example.class, "label", l)));
imageCRUD = new SimpleCRUD_v2(concepts, GalleryImage.class);
imageCRUD.addCountToEnclosingTab(true);
imageCRUD.itemToMap_inner2 = img -> litorderedmap("File", fileName(img.path), "Folder", dirPath(img.path));
imageCRUDVis = imageCRUD.visualize();
imageCRUD.addButton(jPopDownButton_noText("Forget missing images", runnableThread(new Runnable() {
public void run() {
try {
AutoCloseable __12 = enter();
try {
forgetMissingImages();
} finally {
_close(__12);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); forgetMissingImages();";
}
})));
imageCRUD.addButton("Back to gallery", runnableThread(new Runnable() {
public void run() {
try {
AutoCloseable __2 = enter();
try {
uiURLs.showUIURL("Gallery");
} finally {
_close(__2);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); showUIURL(\"Gallery\")";
}
}));
var studyPanel = new StudyPanel();
watchScreenPane = borderlessScrollPane(jHigherScrollPane(jfullcenter(vstack(withLeftAndRightMargin(hstack(dm_rcheckBox("enabled", "Watch"), watchTargetSelector.visualize(), jlabel(" in "), withLabelToTheRight("colors @ ", dm_spinner("colors", 2, 256)), withLabelToTheRight("p", dm_powersOfTwoSpinner("pixelRows", 512)))), verticalStrut(2), withSideMargins(centerAndEastWithMargin(dm_fieldLabel("screenCamRecognitionOutput"), dm_transientCalculatedToolTip(() -> speedInfo_long(), rightAlignLabel(dm_transientCalculatedLabel(() -> speedInfo())))))))));
initUIURLs();
mainTabs = scrollingTabs(jTopOrLeftTabs(horizontalLayout, "Screen Cam", jOnDemand(() -> screenCamPanel()), new WithToolTip("Study", "Here you can analyze gallery images"), withTopAndBottomMargin(studyPanel.visualize()), new WithToolTip("Java", "Write & run actual Java code"), withBottomMargin(jOnDemand(() -> javaPanel())), new WithToolTip("Gallery", "Gallery view with preview images"), withBottomMargin(withRightAlignedButtons(galleryComponent, "Gallery CRUD", new Runnable() {
public void run() {
try {
uiURLs.showUIURL("Gallery CRUD");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "showUIURL(\"Gallery CRUD\")";
}
})), new WithToolTip("Challenges", "Gazelle's self-tests"), challengesPanel()));
challengesPanel.updateCount();
addUIURLToMainTabs("Left Arrow Script");
addUIURLToMainTabs("Paint");
addTabs(mainTabs, new WithToolTip("Databases", "Choose the Gazelle database to use"), databasesPanel());
for (String tab : tabNames(mainTabs)) {
var _tab_8 = dropTrailingBracketedCount(tab);
uiURLs.put(_tab_8, () -> {
int i = indexOfTabNameWithoutTrailingCount(mainTabs, _tab_8);
if (i < 0)
return jcenteredlabel("Hmm. Tab not found");
selectTab(mainTabs, i);
return mainTabs;
});
}
onTabSelected(mainTabs, () -> {
if (!isShowing(mainTabs))
return;
String tabName = dropTrailingBracketedCount(selectedTabName(mainTabs));
if (!eqicOneOf(uiURL, "Main Tabs", tabName))
uiURLs.showUIURL("Main Tabs");
});
var cbEnabled = toolTip("Switch screen cam on or off", dm_checkBox("enabled", ""));
var lblScreenCam = setToolTip("Show scaled down and color-reduced screen image", jlabel("Screen Cam"));
tabComponentClickFixer(lblScreenCam);
var screenCamTab = hstackWithSpacing(cbEnabled, lblScreenCam);
replaceTabTitleComponent(mainTabs, "Screen Cam", screenCamTab);
labelCRUD.update();
imageCRUD.update();
persistSelectedTabAsLiveValue(mainTabs, dm_fieldLiveValue("selectedTab"));
urlBar = uiURLs.urlBar();
focusOnFirstShow(urlBar);
setToolTip(uiURLs.comboBox, "UI navigation system (partially populated)");
scpMain = singleComponentPanel();
uiURLs.scp(scpMain);
uiURLs.showUIURL(uiURL);
var lblDB = toolTip("Currently selected database (" + f2s(concepts.conceptsDir()) + ")", jSimpleLabel(conceptsDirName()));
componentPopupMenuItems(lblDB, "Manage or switch databases...", runnableThread(new Runnable() {
public void run() {
try {
uiURLs.showUIURL("Databases");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "showUIURL(\"Databases\")";
}
}));
var vis = northAndCenter(withSideAndTopMargin(westCenterAndEast(withLabelToTheRight(lblDB, "| "), urlBar, withLeftMargin(backgroundProcessesUI.shortLabel()))), scpMain);
return vis;
}
public JComponent screenCamPanel() {
return centerAndSouthOrEast(horizontalLayout, withTools(isPosterized), watchScreenPane);
}
public JComponent screenCamPlusScriptPanel() {
AutoCloseable __3 = enter();
try {
print("screenCamPlusScriptPanel");
try {
var ide = screenCamScriptIDE = leftArrowScriptIDE();
ide.runButtonShouldBeEnabled = () -> eq(getText(ide.btnRun), "Stop") || ide.runButtonShouldBeEnabled_base();
ide.runScript = () -> {
if (eq(getText(ide.btnRun), "Stop"))
runningScreenCamScript = null;
else {
runningScreenCamScript = screenCamScriptIDE.parsedScript();
ide.showStatus("Running");
}
setText(ide.btnRun, runningScreenCamScript == null ? "Run" : "Stop");
};
return centerAndSouthOrEast(horizontalLayout, jhsplit(jscroll_centered_borderless(isPosterized), screenCamScriptIDE.lvScript(dm_fieldLiveValue("screenCamScript")).visualize()), watchScreenPane);
} catch (Throwable e) {
print(e);
throw rethrow(e);
}
} finally {
_close(__3);
}
}
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" + " (of targeted " + fpsTarget + " FPS)";
}
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() {
scriptRunner.parseAndRunOn(imageToRegions_finished.ii);
}
public boolean shouldRunScript() {
return isShowing(scriptRunner.scpScriptResult);
}
public JComponent testScreenPanel() {
return withSideAndTopMargin(testScreen.visualize());
}
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) {
return withTools(jscroll_centered_borderless(is), is);
}
public JComponent withTools(JComponent component, ImageSurface is) {
return centerAndEastWithMargin(component, vstack(verticalStrut(5), jimageButtonScaledToWidth(16, "#1103054", "Save screenshot in gallery", runnableThread(new Runnable() {
public void run() {
try {
saveScreenshotToGallery();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "saveScreenshotToGallery();";
}
}))));
}
public class WatchTargetSelector {
public JComboBox cb = jComboBox();
public int screenCount, camCount;
public JComponent visualize() {
updateList();
selectItem(cb, watchTarget);
loadableUtils.utils.onChange(cb, watchTarget -> {
setField("watchTarget", watchTarget);
});
return cb;
}
public void updateScreenCount() {
if (screenCount != screenCount())
updateList();
}
public void updateList() {
swing(() -> {
setComboBoxItems(cb, makeWatchTargets());
});
}
public List makeWatchTargets() {
return flattenToList(countIteratorAsList_incl(1, screenCount = screenCount(), i -> new WatchScreen(i)), new WatchMouse(), new WatchScreenWithMouse(), new WatchOtherScreen());
}
}
public class SnPSelector {
final public SnPSelector setSettings(SnPSettings settings) {
return settings(settings);
}
public SnPSelector settings(SnPSettings settings) {
this.settings = settings;
return this;
}
final public SnPSettings getSettings() {
return settings();
}
public SnPSettings settings() {
return settings;
}
public SnPSettings settings = new SnPSettings();
transient public List onChange;
public SnPSelector onChange(Runnable r) {
onChange = syncAddOrCreate(onChange, r);
return this;
}
public SnPSelector removeChangeListener(Runnable r) {
main.remove(onChange, r);
return this;
}
public void change() {
pcallFAll(onChange);
}
public JComponent visualize() {
var colors = jspinner(settings.colors, 2, 256);
loadableUtils.utils.onChange(colors, () -> {
settings.colors = intFromSpinner(colors);
change();
});
var pixelRows = jPowersOfTwoSpinner(512, settings.pixelRows);
loadableUtils.utils.onChange(pixelRows, () -> {
settings.pixelRows = intFromSpinner(pixelRows);
change();
});
return hstack(colors, jlabel(" colors @ "), pixelRows, jlabel(" p"));
}
}
public JComponent wrapCRUD(SimpleCRUD_v2 crud) {
return wrapCRUD(crud, crud.visualize());
}
public JComponent wrapCRUD(SimpleCRUD_v2 crud, JComponent vis) {
return crud == null ? null : withTopAndBottomMargin(jRaisedSection(withMargin(vis)));
}
public File galleryDir() {
return picturesDir(gazelle22_imagesSubDirName());
}
public void saveScreenshotToGallery() {
AutoCloseable __4 = enter();
try {
var img = imageStream.get();
saveImageWithCounter(galleryDir(), "Screenshot", img);
} finally {
_close(__4);
}
}
public GalleryImage addToGallery(File imgFile) {
if (!isImageFile(imgFile))
return null;
var img = uniq(concepts, GalleryImage.class, "path", imgFile);
return img;
}
public class StudyPanel {
public SnPSelector snpSelector = new SnPSelector();
public GalleryImage image;
public BufferedImage originalImage;
public ImageSurface isOriginalWithRegions = g22utils.stdImageSurface();
public ImageSurface isPosterized = g22utils.stdImageSurface();
public SingleComponentPanel scp = singleComponentPanel();
public SingleComponentPanel analysisPanel = singleComponentPanel();
public SingleComponentPanel scpExampleCRUD = singleComponentPanel();
public ConceptsComboBox cbImage = swing(() -> new ConceptsComboBox(concepts, GalleryImage.class));
public Gazelle22_ImageToRegions itr;
public int iSelectedRegion;
public SimpleCRUD_v2 regionCRUD;
public SimpleCRUD_v2 exampleCRUD;
public StudyPanel() {
print("Making StudyPanel " + this);
cbImage.sortTheList = l -> sortedByComparator(l, (a, b) -> cmpAlphanumIC(fileName(a.path), fileName(b.path)));
main.onChangeAndNow(cbImage, img -> {
print("Image selected 1: " + img);
print("Me: " + me() + ", q thread: " + me().q().hasThread() + "q jobs done: " + me().q().nJobsDone());
print("Module queue current job: " + me().q().currentJob());
dm_q(me(), new Runnable() {
public void run() {
try {
print("Image selected: " + img);
image = img;
scp.setComponent(studyImagePanel());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "print(\"Image selected: \" + img);\n image = img;\n scp.setComp...";
}
});
});
isPosterized.removeAllTools();
isPosterized.onMousePositionChanged(r_dm_q(me(), () -> regionUpdate()));
imageSurfaceOnLeftMouseDown(isPosterized, pt -> dm_q(me(), new Runnable() {
public void run() {
try {
chooseRegionAt(pt);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "chooseRegionAt(pt)";
}
}));
snpSelector.onChange(r_dm_q(me(), () -> runSnP()));
}
public void chooseRegionAt(Pt p) {
if (itr == null)
return;
iSelectedRegion = itr.regions.regionAt(p);
if (iSelectedRegion > 0) {
var savedRegion = uniq_returnIfNew(concepts, SavedRegion.class, "image", image, "snpSettings", snpSelector.settings.cloneMe(), "regionIndex", iSelectedRegion);
if (savedRegion != null) {
print("Saved new region!");
var bitMatrix = toScanlineBitMatrix(itr.regions.regionBitMatrix(iSelectedRegion));
cset(savedRegion, "bitMatrix", bitMatrix);
}
}
regionUpdate();
}
public JComponent studyImagePanel() {
if (image == null)
return null;
originalImage = loadImage2(image.path);
if (originalImage == null)
return jcenteredlabel("Image not found");
isOriginalWithRegions.setImage(originalImage);
iSelectedRegion = 0;
itr = new Gazelle22_ImageToRegions(functionTimings, originalImage, snpSelector.settings);
runSnP();
regionCRUD = new SimpleCRUD_v2(concepts, SavedRegion.class);
regionCRUD.addFilter("image", image);
regionCRUD.showSearchBar(false).showAddButton(false).showEditButton(false).iconButtons(true);
regionCRUD.itemToMap_inner2 = region -> {
var examples = conceptsWhere(concepts, Example.class, "item", region);
return litorderedmap("Pixels", region.bitMatrix == null ? "-" : n2(region.bitMatrix.pixelCount()), "Labels", joinWithComma(map(examples, e -> e.label)), "Position", region.bitMatrix == null ? "-" : region.bitMatrix.boundingBoxOfTrueBits());
};
var regionCRUDComponent = regionCRUD.visualize();
regionCRUD.onSelectionChanged(() -> updateExampleCRUD());
return hsplit(jtabs("Image + regions", jscroll_centered_borderless(isOriginalWithRegions), "Posterized", jscroll_centered_borderless(isPosterized)), northAndCenterWithMargin(analysisPanel, hsplit(jCenteredSection("Saved regions", regionCRUDComponent), scpExampleCRUD)));
}
public void runSnP() {
if (itr == null)
return;
itr.run();
regionUpdate();
}
public void regionUpdate() {
if (itr == null)
return;
var pixels = itr.posterized.getRGBPixels();
g22_highlightRegion(pixels, isPosterized, itr, showRegionsAsOutline);
itr.regions.markRegionInPixelArray(pixels, iSelectedRegion, 0xFFADD8E6);
var highlighted = bufferedImage(pixels, itr.posterized.getWidth(), itr.posterized.getHeight());
isPosterized.setImage(highlighted);
isPosterized.performAutoZoom();
updateAnalysis();
}
public void updateAnalysis() {
}
public void updateExampleCRUD() {
var region = regionCRUD.selected();
if (region == null) {
scpExampleCRUD.clear();
return;
}
exampleCRUD = new SimpleCRUD_v2(concepts, Example.class);
exampleCRUD.entityName = () -> "label for region";
exampleCRUD.addFilter("item", region);
exampleCRUD.showSearchBar(false);
exampleCRUD.iconButtons(true);
scpExampleCRUD.set(jCenteredSection("Labels for region", exampleCRUD.visualize()));
}
public void importImage() {
JFileChooser fc = new JFileChooser();
if (fc.showOpenDialog(cbImage) == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile().getAbsoluteFile();
if (!isImageFile(file)) {
infoMessage("Not an image file");
return;
}
var img = addToGallery(file);
waitUntil(250, 5.0, () -> comboBoxContainsItem(cbImage, img));
setSelectedItem(cbImage, img);
}
}
public JComponent visualize() {
return jRaisedSection(northAndCenterWithMargins(centerAndEast(withLabel("Study", cbImage), hstack(jlabel(" in "), snpSelector.visualize(), horizontalStrut(10), jPopDownButton_noText("Import image...", runnableThread(new Runnable() {
public void run() {
try {
AutoCloseable __13 = enter();
try {
importImage();
} finally {
_close(__13);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); importImage();";
}
})))), scp));
}
}
public void initUIURLs() {
uiURLs.put("Main Tabs", () -> horizontalLayout ? withMargin(mainTabs) : withSideMargin(mainTabs));
uiURLs.put("Screen Cam FPS", () -> jFullCenter(vstackWithSpacing(jCenteredLabel("FPS target (frames per second) for screen cam:"), jFullCenter(dm_spinner("fpsTarget", 1, 60)), jCenteredLabel("(You can lower this value if you have a slower computer)"))));
uiURLs.put("Timings", () -> {
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())";
}
});
return withRightAlignedButtons(taTimings, "Reset", new Runnable() {
public void run() {
try {
resetTimings();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "resetTimings();";
}
});
});
uiURLs.put("Test Screen", () -> testScreenPanel());
uiURLs.put("Left Arrow Script", () -> leftArrowScriptPanel());
uiURLs.put("Settings", () -> settingsPanel());
uiURLs.put("System Info", () -> systemInfoPanel());
uiURLs.put("Web Cam", () -> webCamPanel());
uiURLs.put("Labels", () -> wrapCRUD(labelCRUD));
uiURLs.put(new WithToolTip("Screen Cam + Linear Script", "Run a simple (linear) Gazelle V script"), () -> withBottomMargin(scriptRunner.scriptAndResultPanel()));
uiURLs.put(new WithToolTip("Left Arrow Script", "Run a \"left-arrow script\""), () -> withBottomMargin(leftArrowScriptPanel()));
uiURLs.put("Screen Cam + Script", () -> jOnDemand(() -> screenCamPlusScriptPanel()));
uiURLs.put(new WithToolTip("Gallery CRUD", "Gallery view with more functions (delete etc)"), () -> wrapCRUD(imageCRUD, imageCRUDVis));
uiURLs.put("Paint", () -> withBottomMargin(paintPanel()));
}
public JComponent settingsPanel() {
var cbMinimizeToTray = jCheckBox(isTrue(getOpt(dm_stem(), "minimizeToTray")));
onUpdate(cbMinimizeToTray, () -> dm_callStem(me(), "setMinimizeToTray", isChecked(cbMinimizeToTray)));
return jscroll(makeForm3("Minimize to tray", toolTip("Remove Gazelle from task bar when minimized (click Gazelle icon in system tray to reactivate)", cbMinimizeToTray), "Access web cams", dm_checkBox("webCamAccessEnabled")));
}
public File gazelleJar() {
return getBytecodePathForClass(this);
}
public JComponent systemInfoPanel() {
var gazelleJar = gazelleJar();
var cbMinimizeToTray = jCheckBox(isTrue(getOpt(dm_stem(), "minimizeToTray")));
onUpdate(cbMinimizeToTray, () -> dm_callStem(me(), "setMinimizeToTray", isChecked(cbMinimizeToTray)));
return (makeForm3("Java Version", jlabel(javaVersion()), "Gazelle Jar", new JFilePathLabel(gazelleJar).visualize(), "Gazelle Jar Size", str_toMB_oneDigit(fileSize(gazelleJar)), "Compilation Date", jlabel(or2(loadTextFileResource(classLoader(this), "compilation-date.txt"), "unknown")), "Gazelle Count", toolTip("How many Gazelles are running in the world", jLiveValueLabel((LiveValue) dm_callOSOpt("lvComputerCount"))), "Gazelle Database", new JFilePathLabel(concepts.conceptsFile()).visualize(), "Gazelle Database Size", str_toKB(fileSize(concepts.conceptsFile()))));
}
public JComponent operatorsPanel() {
return jcenteredlabel("TODO");
}
public JLeftArrowScriptIDE leftArrowScriptIDE() {
var ide = g22utils.leftArrowIDE();
ide.withResultPanel();
return ide;
}
public void modifyLeftArrowParser(GazelleV_LeftArrowScriptParser parser) {
parser.allowTheWorld(me(), mc(), utils.class);
}
public JComponent leftArrowScriptPanel() {
var ide = leftArrowScriptIDE();
ide.lvScript(dm_fieldLiveValue("newScript"));
return ide.visualize();
}
public JComponent javaPanel() {
AutoCloseable __5 = enter();
try {
var scpResult = singleComponentPanel();
JMiniJavaIDE ide = new JMiniJavaIDE();
ide.stringifier(g22utils.stringifier);
ide.extraClassMembers = script -> {
List tok = javaTok(script);
if (contains(tok, "draw"))
return "\n import java.awt.*;\n import java.awt.image.*;\n \n interface SimpleRenderable {\n void renderOn(Graphics2D g);\n }\n \n static BufferedImage draw(int w, int h, SimpleRenderable r) {\n BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);\n Graphics2D g = img.createGraphics();\n g.setColor(Color.white);\n g.fillRect(0, 0, w, h);\n g.setColor(Color.black);\n r.renderOn(g);\n return img;\n }\n ";
return "";
};
ide.callCompiledObject = o -> {
Object result = ide.callCompiledObject_base(o);
if (result instanceof BufferedImage)
scpResult.set(jscroll_centered_borderless(g22utils.stdImageSurface((BufferedImage) result)));
return result;
};
ide.lvScript(dm_fieldLiveValue("javaCode"));
return jhsplit(jCenteredSection("Image will show here", scpResult), ide.visualize());
} finally {
_close(__5);
}
}
public JComponent webCamPanel() {
if (cbWebCam == null) {
var cams = listWebCams();
cbWebCam = jTypedComboBox(cams, findWebCamByName(cams, webCamName));
}
if (scpWebCamImage == null)
scpWebCamImage = singleComponentPanel();
return northAndCenterWithMargins(centerAndEastWithMargin(withLabel("Cam", cbWebCam), jline(jbutton("Start", runnableThread(new Runnable() {
public void run() {
try {
AutoCloseable __14 = enter();
try {
startWebCam();
} finally {
_close(__14);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); startWebCam();";
}
})), jbutton("Stop", runnableThread(new Runnable() {
public void run() {
try {
AutoCloseable __15 = enter();
try {
stopWebCam();
} finally {
_close(__15);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); stopWebCam();";
}
})))), scpWebCamImage);
}
public void stopWebCam() {
if (webCamPanel != null) {
webCamPanel.stop();
webCamPanel = null;
{
if (scpWebCamImage != null)
scpWebCamImage.clear();
}
backgroundProcessesUI.remove(bgWebCam);
}
}
public void startWebCam() {
AutoCloseable __6 = tempInfoBox("Starting Web Cam");
try {
stopWebCam();
var cam = getSelectedItem_typed(cbWebCam);
setField("webCamName", cam == null ? null : cam.getName());
if (cam != null) {
scpWebCamImage.set(webCamPanel = new WebcamPanel(cam, true));
backgroundProcessesUI.add(bgWebCam);
}
} finally {
_close(__6);
}
}
public void forgetMissingImages() {
int n = l(deleteConcepts(GalleryImage.class, img -> !img.imageExists()));
infoBox(n == 0 ? "Nothing to forget" : "Forgot " + nImages(n));
}
public void addUIURLToMainTabs(String url) {
swing(() -> {
if (containsTabNameWithoutTrailingCount(mainTabs, url))
return;
if (!uiURLs.hasURL(url)) {
print("URL not found: " + url);
return;
}
addTab(mainTabs, url, uiURLs.renderUIURL(url));
});
}
public void showScreenCam() {
uiURLs.showUIURL("Screen Cam");
}
public void showWebCam() {
uiURLs.showUIURL("Web Cam");
}
public JComponent challengesPanel() {
if (challengesPanel == null)
challengesPanel = new G22ChallengesPanel().g22utils(g22utils);
return challengesPanel.visualize();
}
public Gazelle22_ImageToRegions imageToRegions(BufferedImage inputImage, SnPSettings snpSettings) {
return new Gazelle22_ImageToRegions(functionTimings, inputImage, snpSettings);
}
public JComponent databasesPanel() {
return new G22DatabasesPanel(g22utils, concepts).visualize();
}
public JComponent paintPanel() {
return new JPaintTool().visualize();
}
}
static public boolean _moduleClass_GazelleScreenCam = true;
static public class Label extends ConceptWithGlobalID {
public String name;
public String toString() {
return name;
}
}
static public class GalleryImage extends Concept {
public File path;
public String toString() {
return fileName(path);
}
public boolean imageExists() {
return fileExists(path);
}
}
static public class SavedRegion extends Concept {
static final public String _fieldOrder = "image snpSettings regionIndex bitMatrix";
public Ref image = new Ref();
public SnPSettings snpSettings;
public int regionIndex;
public ScanlineBitMatrix bitMatrix;
}
static public class Example extends Concept {
static final public String _fieldOrder = "label item confidence";
public Ref label = new Ref();
public Ref item = new Ref();
public double confidence = 1;
}
static public class IfThenTheory extends Concept {
public Ref if_ = new Ref();
public Ref then = new Ref();
}
abstract static public class WatchTarget {
public void mainWindow(Window window) {
}
abstract public void configureScreenCamStream(ScreenCamStream stream);
}
static public class WatchScreen extends WatchTarget implements IFieldsToList {
public int screenNr;
public WatchScreen() {
}
public WatchScreen(int screenNr) {
this.screenNr = screenNr;
}
public boolean equals(Object o) {
if (!(o instanceof WatchScreen))
return false;
WatchScreen __9 = (WatchScreen) o;
return screenNr == __9.screenNr;
}
public int hashCode() {
int h = -1787428357;
h = boostHashCombine(h, _hashCode(screenNr));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { screenNr };
}
public String toString() {
return "Screen " + screenNr;
}
public void configureScreenCamStream(ScreenCamStream stream) {
stream.useScreen(screenNr - 1);
}
}
static public class WatchMouse extends WatchTarget implements IFieldsToList {
static final public String _fieldOrder = "width height";
public int width;
public int height;
public WatchMouse(int width, int height) {
this.height = height;
this.width = width;
}
public boolean equals(Object o) {
if (!(o instanceof WatchMouse))
return false;
WatchMouse __10 = (WatchMouse) o;
return width == __10.width && height == __10.height;
}
public int hashCode() {
int h = 1876823350;
h = boostHashCombine(h, _hashCode(width));
h = boostHashCombine(h, _hashCode(height));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { width, height };
}
public WatchMouse() {
height = 256;
width = iround(height * 16.0 / 9);
}
public String toString() {
return "Mouse";
}
public void configureScreenCamStream(ScreenCamStream stream) {
stream.area(mouseArea(width, height));
}
}
static public class WatchScreenWithMouse extends WatchTarget implements IFieldsToList {
public WatchScreenWithMouse() {
}
public boolean equals(Object o) {
return o instanceof WatchScreenWithMouse;
}
public int hashCode() {
int h = -1449766972;
return h;
}
public Object[] _fieldsToList() {
return null;
}
public String toString() {
return "Screen w/mouse";
}
public void configureScreenCamStream(ScreenCamStream stream) {
stream.useScreen(screenNrContaining(mouseLocationPt()));
}
}
static public class WatchOtherScreen extends WatchTarget implements IFieldsToList {
public WatchOtherScreen() {
}
public boolean equals(Object o) {
return o instanceof WatchOtherScreen;
}
public int hashCode() {
int h = 1734016877;
return h;
}
public Object[] _fieldsToList() {
return null;
}
public String toString() {
return "Other Screen";
}
final public void setMainWindow(Window mainWindow) {
mainWindow(mainWindow);
}
public void mainWindow(Window mainWindow) {
this.mainWindow = mainWindow;
}
final public Window getMainWindow() {
return mainWindow();
}
public Window mainWindow() {
return mainWindow;
}
transient public Window mainWindow;
public void configureScreenCamStream(ScreenCamStream stream) {
stream.useScreen(mod(screenNrOfWindow(mainWindow) + 1, numberOfScreens()));
}
}
static public void standaloneInit() {
__javax = x30.class;
x30.__javax = x30.class;
x30_pkg.x30_util.__setJavaX(x30.class);
x30.cleanKillMsg = "";
callOnLoadMethods(mc());
}
static public class PrintLogModule extends DynPrintLog {
public void start() {
try {
super.start();
setModuleName("Log");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String getPrintLog() {
return printLog();
}
public boolean useErrorHandling() {
return false;
}
}
static public class Stem extends Concept {
static final public String _fieldOrder = "host module frameRect minimized maximized alwaysOnTop autoUpdate minimizeToTray window btnMax titleComponent compileButton";
transient public GazelleHost host;
public DynModule module;
public Rect frameRect;
public boolean minimized, maximized, alwaysOnTop, autoUpdate, minimizeToTray;
public List fieldsToShareBetweenDatabases() {
return identifiers("frameRect, minimized, maximized, alwaysOnTop, autoUpdate, minimizeToTray");
}
transient public JFrame window;
transient public JButton btnMax;
transient public JLabel titleComponent;
final public JButton getCompileButton() {
return compileButton();
}
public JButton compileButton() {
return compileButton;
}
transient public JButton compileButton;
public Stem() {
}
public Stem(GazelleHost host) {
this.host = host;
}
public Stem(GazelleHost host, DynModule module) {
this.module = module;
this.host = host;
}
public Rect getFrameRect() {
return toRect(getBounds(window));
}
public void saveFrameRect() {
setField("frameRect", getFrameRect());
}
public void setAlwaysOnTop(boolean alwaysOnTop) {
this.alwaysOnTop = alwaysOnTop;
change();
alwaysOnTop(window, alwaysOnTop);
}
public void setMinimizeToTray(boolean minimizeToTray) {
cset(this, "minimizeToTray", minimizeToTray);
}
public void setWindow(JFrame window) {
this.window = window;
if (frameRect != null)
setBounds(window, frameRect);
onBoundsChange(window, new Runnable() {
public void run() {
try {
saveFrameRect();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "saveFrameRect();";
}
});
alwaysOnTop(window, alwaysOnTop);
}
public void activateWindow() {
activateFrame_v3(window);
}
public boolean isMain() {
return this == host.stem;
}
public void minimize() {
cset(this, "minimized", true);
if (!minimizeToTray || host.trayIcon == null || !isMain())
minimizeWindow(window);
else
hideWindow(window);
}
public void deleteMe() {
printAlsoToSystemOut = true;
print("deleteMe " + isMain());
if (isMain()) {
host.cleanExit();
} else {
cleanMeUp();
}
}
public void cleanMeUp() {
disposeWindow(window);
{
cleanUp(module);
module = null;
}
cdelete(this);
}
public void grabWindowState() {
setField("maximized", !isExtendedStateNormal(window));
}
public void updateBtnMax() {
if (!isShowing(btnMax))
return;
grabWindowState();
setText(btnMax, maximized ? "NORM" : "MAX");
}
public JComponent makeWindowBorderAndTitle(JComponent contents, String title) {
var icons = jline();
if (host.allowFrameMaximization) {
icons.add(btnMax = jbutton("", runnableThread(new Runnable() {
public void run() {
try {
maximizeOrRestoreFrame(window);
updateBtnMax();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "maximizeOrRestoreFrame(window);\r\n updateBtnMax();";
}
})));
onFirstShowing(btnMax, new Runnable() {
public void run() {
try {
updateBtnMax();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "updateBtnMax();";
}
});
}
icons.add(toolTip("Minimize this window", jbutton("MIN", new Runnable() {
public void run() {
try {
minimize();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "minimize();";
}
})));
if (isMain())
icons.add(toolTip("Exit Gazelle", jbutton("QUIT", runnableThread(new Runnable() {
public void run() {
try {
if (swingConfirm(window, "Really quit Gazelle?"))
deleteMe();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (swingConfirm(window, \"Really quit Gazelle?\"))\r\n deleteMe();";
}
}))));
else
icons.add(toolTip("Close this window", jbutton("X", runnableThread(new Runnable() {
public void run() {
try {
deleteMe();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "deleteMe();";
}
}))));
icons.add(jPopDownButton_noText(flattenToList(jCheckBoxMenuItem_dyn("Always on top", () -> alwaysOnTop, alwaysOnTop -> setAlwaysOnTop(alwaysOnTop)), "---", "Restart", runnableThread(new Runnable() {
public void run() {
try {
host.restart();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "host.restart()";
}
}), "Update Gazelle", runnableThread(new Runnable() {
public void run() {
try {
host.upgradeGazelle();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "host.upgradeGazelle()";
}
}), !isMain() ? null : jCheckBoxMenuItem_dyn("Auto-Update", () -> autoUpdate, b -> cset(Stem.this, "autoUpdate", b)), "---", !isMain() ? null : ll("Screenshoot this window", runnableThread(new Runnable() {
public void run() {
try {
shootWindow();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "shootWindow();";
}
}), "Dump threads", runnableThread(new Runnable() {
public void run() {
try {
showText("User threads", renderUserThreadsWithStackTraces());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "showText(\"User threads\", renderUserThreadsWithStackTraces());";
}
}), !isMain() ? null : "Log", !isMain() ? null : new Runnable() {
public void run() {
try {
host.showPrintLog();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "host.showPrintLog()";
}
}, !isMain() ? null : "Copy log to clipboard", !isMain() ? null : runnableThread(new Runnable() {
public void run() {
try {
copyToClipboard(printLog());
infoBox("Copied log to clipboard");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyToClipboard(printLog());\r\n infoBox(\"Copied log to clipboard\");";
}
})), ccallOpt(module, "popDownItems"))));
JComponent actualTitle = titleComponent = fontSizePlus(7, jCenteredLabel(title));
installWindowDragger(actualTitle);
if (haveMuricaPassword())
actualTitle = centerAndEastWithMargin(actualTitle, jline(compileButton = makeCompileButton(), jLiveValueLabel(host.lvComputerCount())));
var spacer = gazelle_wavySpacer();
var titleBarMain = setOpaqueBackground(host.color1, jtransparent_recursive(westCenterAndEastWithMargin(jImage_scaledToHeight(24, host.trayIconImageID), actualTitle, setOpaqueBackground(host.color2, spacer))));
installWindowDragger(spacer);
var titleBar = setBackground(host.color2, centerAndEast(titleBarMain, icons));
var border = BorderFactory.createLineBorder(host.color1, host.borderSize);
var outerPanel = withBorder(border, northAndCenter(titleBar, contents));
installWindowResizeDraggerOnBorder(outerPanel);
return outerPanel;
}
public JButton makeCompileButton() {
var gears = resizeImageIcon(imageIcon("#1103061"), 16);
var btn = jimageButtonScaledToWidth(16, "#1101268", "Compile & update", runnableThread(new Runnable() {
public void run() {
try {
host.compile();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "host.compile()";
}
}));
return btn;
}
public void startAndShow() {
module._host = this;
setOpt_raw(module, "threadPool", threadPool);
setOpt_raw(module, "concepts", host.concepts);
setOpt_raw(module, "g22utils", host.g22utils);
copyLocalLog(module, mc());
var __33 = makeVisAndTitle();
var vis = __33.a;
var title = __33.b;
printWithMS("Show frame");
JFrame frame = makeUndecoratedFrame(title, vis);
setFrameIcon(frame, host.trayIconImageID);
setWindow(frame);
frame.addPropertyChangeListener("title", evt -> setText(titleComponent, frame.getTitle()));
if (minimized)
minimize();
onWindowDeiconified(frame, () -> cset(this, "minimized", false));
showWindow(window);
if (maximized && host.allowFrameMaximization)
maximizeFrame(window);
}
public Pair makeVisAndTitle() {
JComponent vis;
{
printWithMS("Starting " + module);
AutoCloseable __27 = module.enter();
try {
module.start();
printWithMS("Visualize");
vis = swing(() -> {
AutoCloseable __28 = module.enter();
try {
return module.visualize();
} finally {
_close(__28);
}
});
} finally {
_close(__27);
}
}
String title = host.windowTitle;
if (!isMain())
title = unnull(module.moduleName());
vis = makeWindowBorderAndTitle(vis, title);
return pair(vis, title);
}
public void revisualize() {
if (window == null)
return;
try {
module.unvisualize();
} catch (Throwable __e) {
printStackTrace(__e);
}
var __34 = makeVisAndTitle();
var vis = __34.a;
var title = __34.b;
setFrameContents(window, vis);
}
public void shootWindow() {
var img = renderComponentToImage(window);
copyImageToClipboard(img);
saveInImageDirectoryWithCounter(gazelle22_imagesSubDirName() + "/Gazelle", img);
}
}
static public class GazelleHost implements G22MasterStuff {
public boolean _isTransient() {
return true;
}
public Stem stem;
public DynModule gazelle;
transient public String windowTitle = "November Gazelle v1";
transient public String trayIconImageID = "#1103047";
transient public int borderSize = 5;
transient public Color color1 = awtColor("ADD8E6");
transient public Color color2 = awtColor("EEEEEE");
transient public Color color3 = awtColor("A3C0AA");
transient public IF0 moduleMaker;
transient public ThreadPool threadPool;
transient public TrayIcon trayIcon;
transient public TrayIconLastPosition trayIconLastPosition;
transient public Set argsSet;
transient public boolean incrementalDownloads = true;
transient public Concepts concepts;
transient public boolean allowFrameMaximization = false;
transient public StefansOS_ConnectToServer serverConnector;
transient public ComputerCountListener computerCount;
transient public Q systemQ = startQ("System Q");
transient public G22Utils g22utils = new G22Utils();
transient public Map importedFieldsForMainStem;
public GazelleHost(ThreadPool threadPool, IF0 moduleMaker) {
this.moduleMaker = moduleMaker;
this.threadPool = threadPool;
}
public void trayIconLeftClick() {
activateFrame_v3(mainWindow());
}
public void makeTrayIcon() {
try {
trayIcon_imageAutoSize = false;
trayIcon = installTrayIcon(trayIconImageID, windowTitle, new Runnable() {
public void run() {
try {
trayIconLeftClick();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "trayIconLeftClick();";
}
}, "Show Gazelle", new Runnable() {
public void run() {
try {
trayIconLeftClick();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "trayIconLeftClick();";
}
}, "Exit Gazelle", new Runnable() {
public void run() {
try {
cleanExit();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cleanExit();";
}
});
trayIconLastPosition = new TrayIconLastPosition(trayIcon);
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
public void run(String[] args) {
try {
run2(args);
} catch (Throwable e) {
printStackTrace(e);
hideTrayIcon(trayIcon);
onWindowClosing(() -> systemExit(1), getWindow(showText_fast_noWrap("Gazelle Error", renderStackTrace(e))));
}
}
public void run2(String[] args) {
argsSet = asSet(args);
if (!argsSet.contains("noflatlaf"))
com.formdev.flatlaf.FlatLightLaf.setup();
if (contains(args, "profile"))
profileToConsole(() -> actualMain(args));
else
actualMain(args);
if (argsSet.contains("brexit"))
System.exit(0);
}
public void actualMain(String... args) {
vm_generalMap_put("stefansOS", this);
System.out.println(hmsWithColonsAndMS() + ": Init");
printJavaVersion();
if (containsOneOf(argsSet, "upgrade", "update")) {
upgradeGazelle();
return;
}
g22utils.masterStuff = this;
makeTrayIcon();
initAutoUpdate();
assertEquals(callF(_defaultClassFinder(), "main$Stem"), Stem.class);
String dbName = g22utils.dbToOpen();
concepts = newConceptsWithClassFinder(newFile(newFile(g22utils.databasesMotherDir(), dbName), conceptsFileName()));
startDBAndModules();
}
public void startDBAndModules() {
concepts.makeStructureData = () -> {
structure_Data data = concepts.makeStructureData_base();
data.mcDollar = mcDollar();
return data;
};
try {
concepts.fileLock().lockOrFail();
} catch (Throwable e) {
printStackTrace(e);
if (cic(str(e), "Couldn't aquire lock")) {
infoBox("Gazelle is still running, please exit it first!", 10.0);
sleepSeconds(10);
System.exit(1);
}
}
concepts.fileLock().deleteOnExit();
concepts.persist();
db_setMainConcepts(concepts);
var stems = findConcepts(concepts, Stem.class);
print("Stems in DB: " + l(stems));
stem = first(stems);
if (stem == null) {
print("Starting new module");
makeModule();
stem = registerConcept(concepts, new Stem(this, gazelle));
}
gazelle = stem.module;
print("importedFieldsForMainStem", importedFieldsForMainStem);
csetAll(stem, importedFieldsForMainStem);
importedFieldsForMainStem = null;
for (var stem : list(Stem.class, concepts)) {
stem.host = this;
stem.startAndShow();
}
printWithMS("Dudadoneski");
}
public void showPrintLog() {
systemQ.add(() -> {
var logModule = firstThat(list(concepts, Stem.class), stem -> stem.module instanceof PrintLogModule);
if (logModule != null)
logModule.activateWindow();
else
registerConcept(concepts, new Stem(this, new PrintLogModule())).startAndShow();
});
}
public JFrame mainWindow() {
return stem == null ? null : stem.window;
}
public Object dm_getStem(Object moduleOrID) {
return stem;
}
public Object resolveModule(Object moduleOrID) {
return moduleOrID == stem ? gazelle : moduleOrID;
}
public void cleanExit() {
{
startThread(new Runnable() {
public void run() {
try {
print("Saving DB for exit");
{
cleanUp(concepts);
concepts = null;
}
System.exit(0);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "print(\"Saving DB for exit\");\r\n { cleanUp(concepts); concepts = null; }\r\n...";
}
});
}
}
public File myJar() {
return getBytecodePathForClass(this);
}
public AutoCloseable tempDisableCompileButtons() {
return tempDisableButtons(compileButtons());
}
public void upgradeGazelle() {
try {
printAlsoToSystemOut = true;
AutoCloseable __29 = tempDisableCompileButtons();
try {
for (var f : allJFrames()) setFrameTitle(f, "Updating...");
File myJar = myJar();
print("myJar", myJar);
String existingFilesComp = !incrementalDownloads ? null : existingFilesInfo();
String date = ymdMinusHMS();
File f = javaxCodeDir("Downloaded Updates/" + "gazelle-" + date + ".jar");
var progress = tempProgressBar_addToWindowIfPossible(mainWindow(), "Updating Gazelle");
try {
progress.setText("Downloading Update...");
long _startTime_25 = sysNow();
postBinaryPageToFile(downloadURL(), f, "existingFilesComp", existingFilesComp);
done2_always("Downloading zip", _startTime_25);
printFileInfo(f);
if (!isNonEmptySingleZip_byMagicHeader(f)) {
infoBox("Bad file downloaded... :(");
return;
}
boolean replaced = false;
if (isFile(myJar)) {
progress.setText("Replacing with new version: " + renderFileInfo(myJar));
File myJarSaved = fileInSubDir("old-code", appendToBaseName(myJar, ".bak." + date));
File myJarNew = appendToFileName(myJar, ".new");
Set toKeep = asSet(tlft(loadTextFileFromZip(f, "to-keep")));
if (nempty(toKeep)) {
progress.setText("Keeping " + nFiles(toKeep));
int have = countFilesInZip(myJar);
if (l(toKeep) == have && countFilesInZip(f) == 1) {
infoBox("Nothing to update - will just restart");
sleepSeconds(1);
restart();
}
Zip4j_MergeZipFilesWithFilter merger = new Zip4j_MergeZipFilesWithFilter(myJarNew);
try {
merger.addZipFile(myJar, name -> contains(toKeep, name));
merger.addZipFile(f, name -> !eq(name, "to-keep"));
merger.finish();
renameFileVerbose(myJar, myJarSaved);
renameFileVerbose(myJarNew, myJar);
} finally {
_close(merger);
}
} else {
renameFileVerbose(myJar, myJarSaved);
renameFileVerbose(f, myJar);
}
printFileInfo(myJar);
replaced = true;
}
progress.setText("Done");
if (replaced)
infoBox("Installed update, replaced " + f2s(myJar) + " - now starting");
else
infoBox("Updated but could not replace originally downloaded jar");
restart(replaced ? myJar : f);
} finally {
_close(progress);
}
} finally {
_close(__29);
}
} catch (Throwable e) {
printStackTrace(e);
throw rethrow(e);
}
}
public void restart() {
restart(myJar());
}
public void restart(File jar) {
String javaCmd = or2(currentProcessCommand(), "java");
String cmd = pqO(javaCmd) + " -jar " + pqO(jar);
print(cmd);
nohup(cmd);
cleanExit();
}
public void makeModule() {
if (gazelle == null)
gazelle = callF(moduleMaker);
}
public void reloadModuleInBackground(Stem mod) {
restart();
}
public void initAutoUpdate() {
print("Making server connection for updates.");
serverConnector = snippetUpdateConnector();
vmBus_onMessage("snippetUpdate", new VF1() {
public void get(List l) {
try {
String uri = getString(l, 1);
Matches m = new Matches();
if (swic(uri, "/transpileOK/", m))
if (sameSnippetID(programID(), firstIntAsString(m.rest()))) {
if (stem.autoUpdate)
upgradeGazelle();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S uri = getString(l, 1);\r\n new Matches m;\r\n if (swic(uri, \"/transpi...";
}
});
try {
computerCount = new ComputerCountListener(serverConnector);
computerCount.init();
} catch (Throwable __e) {
printStackTrace(__e);
}
}
public String downloadURL() {
return "https://botcompany.de/jar/" + psI(programID()) + "?withLibs=1&withX30=1" + (!downloadJarWithSrc() ? "&noSrc=1" : "") + (downloadUncompressedJAR() ? "&uncompressed=1" : "");
}
public boolean downloadJarWithSrc() {
return false;
}
public boolean downloadUncompressedJAR() {
return false;
}
public void revisualizeModule(Stem stem) {
stem.revisualize();
}
public Integer computerCount() {
return computerCount == null ? (Integer) 0 : computerCount.get();
}
public LiveValue lvComputerCount() {
return computerCount.liveValue();
}
public List compileButtons() {
return mapNonNulls(list(Stem.class), s -> s.compileButton());
}
public void compile() {
print("Compiling");
var gears = resizeImageIcon(imageIcon("#1103061"), 16);
print("compileButtons", compileButtons());
AutoCloseable __30 = tempDisableCompileButtons();
try {
AutoCloseable __31 = tempSetButtonImages(compileButtons(), gears);
try {
{
startThread(new Runnable() {
public void run() {
try {
existingFilesInfo();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "existingFilesInfo();";
}
});
}
transpileOnServerWithErrorWindow(programID, true, null);
print("Done transpilation");
} finally {
_close(__31);
}
} finally {
_close(__30);
}
}
public void switchDatabase(File conceptsDir) {
printAlsoToSystemOut = true;
AutoCloseable __32 = tempInfoBoxNoHide("Switching database...");
try {
importedFieldsForMainStem = cgetAll(stem, stem.fieldsToShareBetweenDatabases());
print("importedFieldsForMainStem", importedFieldsForMainStem);
File newConceptsFile = newFile(conceptsDir, conceptsFileName());
if (!fileExists(newConceptsFile))
throw fail(infoBox("Database not found: " + newConceptsFile));
print("Cleaning up concepts");
for (Concept c : allConcepts(concepts)) cleanUp(c);
print("Releasing DB");
{
cleanUp(concepts);
concepts = null;
}
print("Loading new DB: " + f2s(newConceptsFile));
concepts = newConceptsWithClassFinder(newConceptsFile);
startDBAndModules();
g22utils.openedDB(conceptsDir);
print("Database switch complete, stopping System.out");
printAlsoToSystemOut = false;
} finally {
_close(__32);
}
}
transient public Cache existingFilesInfo_cache = new Cache<>(() -> existingFilesInfo_load());
public String existingFilesInfo() {
return existingFilesInfo_cache.get();
}
public String existingFilesInfo_load() {
List fingerprints = zipFileToJSONFingerprint_md5(myJar());
String s = base64encode(gzipString(jsonEncode(fingerprints)));
print("existingFilesInfo", nBytes(l(s)));
return s;
}
}
static public String windowTitle = "Gazelle 22";
static public String progIDForDBAndAutoUpdate = "#1033860";
static public boolean pingSourceStrictMode = false;
static public GazelleHost host;
static public GazelleScreenCam client;
static public ThreadPool threadPool;
public static void main(final String[] args) throws Exception {
loadableUtils.utils.__setJavaX(main.class);
standaloneInit();
ping_v3_setPingSourceMaker(() -> {
if (pingSourceStrictMode)
throw fail("Strict mode - make a ping source first!!");
return new PingSource(threadPool, "legacy");
});
threadPool = new ThreadPool(findIntArg("cores", args, numberOfCores()));
print(threadPool);
PingSource ps = new PingSource(threadPool, print("Starting Gazelle"));
ps.dO(() -> {
System.out.println("Pinging");
ping();
print("Pinged");
programID = progIDForDBAndAutoUpdate;
preferredScreen = () -> {
if (host == null)
return 0;
var stem = host.stem;
if (stem == null)
return 0;
int screen = max(0, screenNrOfWindow(mainWindow()));
return screen;
};
showForm_makeFrame = (title, panel) -> {
var dialog = new JDialog(mainWindow(), title);
setDialogContents(dialog, withMargin(panel));
packWindow(dialog);
minWindowWidth(dialog, 400);
centerDialogOverOwner(dialog);
dialog.setVisible(true);
};
if (cic(args, "delete-session")) {
print("Deleting session (" + programDir(programID) + ")");
clearConceptsOf(programID);
}
F1 baseClassFinder = (F1) (_defaultClassFinder());
setDefaultClassFinder(new F1() {
public Class get(String name) {
try {
name = replacePrefix("loadableUtils.utils$", "main$", name);
if (eq(name, "main$Challenge")) {
print("Legacy Challenge converted!");
return G22Challenge.class;
}
return baseClassFinder.get(name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "name = replacePrefix(\"loadableUtils.utils$\", \"main$\", name);\r\n //print(\"...";
}
});
host = new GazelleHost(threadPool, () -> {
return client = new GazelleScreenCam();
});
if (sameSnippetID(programID, "#1033860"))
windowTitle += " dev";
host.windowTitle = windowTitle;
host.run(args);
if (!cic(args, "console")) {
print("Stopping System.out");
printAlsoToSystemOut = false;
}
});
print("aha.");
}
static public Window mainWindow() {
return host.stem.window;
}
static public Map generalMap = syncMap();
static public Rect leftScreenBounds() {
return first(allScreenBounds());
}
static public Rect rightScreenBounds() {
return second(allScreenBounds());
}
static public Rect mergeRects(List l) {
Rect r = first(l);
for (int i = 1; i < l(l); i++) r = rectUnion(r, l.get(i));
return r;
}
static public Rect mergeRects(Rect a, Rect b) {
return rectUnion(a, b);
}
static public double g22_squareness(Rect r) {
return doubleRatio(min(r.w, r.h), max(r.w, r.h));
}
static public double g22_regionFilledness(IImageRegion region) {
return doubleRatio(region.numberOfPixels(), area(region.bounds()));
}
static public BigInteger mul(BigInteger a, BigInteger b) {
return a.multiply(b);
}
static public BigInteger mul(BigInteger a, long b) {
return a.multiply(bigint(b));
}
static public int mul(int a, int b) {
return a * b;
}
static public BufferedImage newImage(int w, int h) {
return whiteImage(w, h);
}
static public BufferedImage newImage(int w, int h, Color color) {
return bufferedImage(w, h, color);
}
static public BufferedImage newImage(int size) {
return whiteImage(size);
}
static public BufferedImage newImage(Pt size) {
return whiteImage(size.x, size.y);
}
static public BufferedImage newImage(Dimension size) {
return whiteImage(size.width, size.height);
}
static public Rect randomRect(Rect outer) {
var w = random_incl(outer.w);
var h = random_incl(outer.h);
return randomRect(w, h, outer);
}
static public Rect randomRect(int w, int h, Rect outer) {
return translateRect(outer.x, outer.y, randomRect(outer.w, outer.h, 0, w, h));
}
static public Rect randomRect(Rect outer, int w, int h) {
return randomRect(w, h, outer);
}
static public Rect randomRect(int w, int h, int rw, int rh) {
return randomRect(w, h, 0, rw, rh);
}
static public Rect randomRect(int w, int h, int border, int rw, int rh) {
if (rw > w - border * 2 || rh > h - border * 2)
return null;
int ww = random(border, w - border - rw);
int hh = random(border, h - border - rh);
return new Rect(ww, hh, rw, rh);
}
static public Rect randomRect(int w, int h) {
int rw = random(w);
int rh = random(h);
return randomRect(w, h, 0, rw, rh);
}
static public Rect randomRect(RGBImage img, int rw, int rh) {
return randomRect(img.w(), img.h(), 0, rw, rh);
}
static public Rect randomRect(RGBImage img) {
return randomRect(img.w(), img.h());
}
static public Rect randomRect() {
return randomRect(currentImage().getWidth(), currentImage().getHeight());
}
static public Rect randomRect(BufferedImage img, int rw, int rh) {
return randomRect(img.getWidth(), img.getHeight(), 0, rw, rh);
}
static public boolean lessThan(int a, int b) {
return a < b;
}
static public boolean lessThan(double a, double b) {
return a < b;
}
static public boolean greaterThan(Object a, Object b) {
return cmp(a, b) > 0;
}
static public boolean greaterThan(int a, int b) {
return a > b;
}
static public boolean greaterThan(double a, double b) {
return a > b;
}
static public IImageRegion g22_darkestRegion(IImageRegions regions) {
return regions == null ? null : lowest(regions.regions(), r -> r.brightness());
}
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 JMenuItem jMenuItem(final String text) {
return jmenuItem(text);
}
static public JMenuItem jMenuItem(String text, Object r) {
return jmenuItem(text, r);
}
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 void assertSame(Object a, Object b) {
assertSame("", a, b);
}
static public void assertSame(String msg, Object a, Object b) {
if (a != b)
throw fail(joinNemptiesWithColon(msg, a + " != " + b + " (" + identityHash(a) + "/" + identityHash(b) + ")"));
}
static public void indexConceptField(Class extends Concept> c, String field) {
indexConceptField(db_mainConcepts(), c, field);
}
static public void indexConceptField(Concepts concepts, Class extends Concept> c, String field) {
if (!isConceptFieldIndexed(concepts, c, field))
new ConceptFieldIndex(concepts, c, field);
}
static public void onConceptChanges(Runnable r) {
onConceptsChange(r);
}
static public void onConceptChanges(Concepts cc, Runnable r) {
onConceptsChange(cc, r);
}
static public void updateEnclosingTabTitleWithCount(JComponent c, int n) {
Pair p = enclosingTab(c);
if (p == null)
return;
setTabTitle(p.a, p.b, appendBracketedCount(dropTrailingBracketedCount(getTabTitle(p.a, p.b)), n));
}
static public int countConcepts(Concepts concepts, Class c, Object... params) {
return concepts.countConcepts(c, params);
}
static public int countConcepts(Class c, Object... params) {
return db_mainConcepts().countConcepts(c, params);
}
static public int countConcepts() {
return db_mainConcepts().countConcepts();
}
static public int countConcepts(String className) {
return db_mainConcepts().countConcepts(className);
}
static public int countConcepts(Concepts concepts, String className) {
return concepts.countConcepts(className);
}
static public int countConcepts(Concepts concepts) {
return concepts.countConcepts();
}
static public void dm_watchFieldAndNow(String field, Runnable onChange) {
dm_watchField(field, onChange);
dm_q(onChange);
}
static public int iround(double d) {
return (int) Math.round(d);
}
static public int iround(Number n) {
return iround(toDouble(n));
}
static public Object getMetaSrc(Object o) {
return metaGet("src", o);
}
static public void g22_runPostAnalysisLeftArrowScript(Gazelle22_ImageToRegions itr, GazelleV_LeftArrowScript.Script script) {
if (script == null)
return;
var fScore = script.getFunction("score");
if (fScore != null) {
List> regions = itr.regions.regions();
int n = l(regions);
Map, Double> scores = new HashMap();
for (var region : regions) scores.put(region, toDouble(fScore.call(null, region)));
itr.scoredRegions = mapSortedByValue(scores);
}
}
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 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 void g22_renderPosterizedHighlightedImage(ImageSurface isPosterized, Gazelle22_ImageToRegions itr, boolean showRegionsAsOutline) {
if (isPosterized == null)
return;
var mouse = mouseLocationPt();
if (!isScreenCoordinateInWindow(mouse, isPosterized)) {
var mouse2 = itr.coordinatesFromScreen(mouse);
mouse = mouse2;
} else
mouse = isPosterized.mousePosition;
var pixels = itr.posterized.getRGBPixels();
g22_highlightRegion(pixels, isPosterized, itr, mouse, showRegionsAsOutline);
if (itr.scoredRegions != null)
for (Map.Entry extends IImageRegion, ? extends Double> __0 : _entrySet(itr.scoredRegions)) {
IImageRegion region = __0.getKey();
double score = __0.getValue();
if (score >= .5) {
int color = colorToIntOpaque(blendColors(lightBlue(), Color.blue, (score - .5) * 2));
g22_highlightRegion(pixels, isPosterized, itr, region.indexInCreator(), color, false);
}
}
isPosterized.setImage(bufferedImage(pixels, itr.posterized));
}
static public void ownResource(AutoCloseable c) {
_registerAutoCloseable(c);
}
static public Timestamp tsNowPlusMS(long ms) {
return tsNow().plus(msToSeconds(ms));
}
static public Timestamp tsNowPlusMS(double ms) {
return tsNow().plus(msToSeconds(ms));
}
static public Window getWindow(Object o) {
if (!(o instanceof Component))
return null;
return swing(() -> {
Component c = (Component) o;
while (c != null) {
if (c instanceof Window)
return ((Window) c);
c = c.getParent();
}
return null;
});
}
static public 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 List allImageFiles(File dir) {
return filter(__55 -> isImageFile(__55), findAllFiles_noDirs(dir));
}
static public File picturesDir() {
return imagesDir();
}
static public File picturesDir(String sub) {
return newFile(picturesDir(), sub);
}
static public boolean isImageFile(File f) {
return isImageFileName(fileName(f)) && isFile(f);
}
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 List list(Class type) {
return list(type, db_mainConcepts());
}
static public List list(Class type, Concepts cc) {
return cc.list(type);
}
static public List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static public List list(String type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, String type) {
return concepts.list(type);
}
static public LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return 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 String fileName(File f) {
return f == null ? null : f.getName();
}
static public String dirPath(File f) {
return f == null ? null : f.getParent();
}
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 JPanel withSideMargins(Component c) {
return withLeftAndRightMargin(c);
}
static public JPanel withSideMargins(int w, Component c) {
return withLeftAndRightMargin(w, c);
}
static public JPanel withSideMargins(int w1, int w2, Component c) {
return withLeftAndRightMargin(w1, w2, c);
}
static public A dm_transientCalculatedToolTip(IF0 calc, A component) {
return toolTipFromLiveValue(dm_transientCalculatedLiveValue(Object.class, calc), component);
}
static public A rightAlignLabel(final A a) {
return setHorizontalAlignment(JLabel.RIGHT, a);
}
static public JLabel dm_transientCalculatedLabel(IF0 calc) {
return jLiveValueLabel(dm_transientCalculatedLiveValue(Object.class, calc));
}
static public JTabbedPane scrollingTabs(JTabbedPane pane) {
if (pane != null) {
swing(() -> {
pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
});
}
return pane;
}
static public JTabbedPane jTopOrLeftTabs(boolean horizontal, Object... x) {
return jLeftOrTopTabs(horizontal, x);
}
static public JTabbedPane jTopOrLeftTabs(boolean horizontal, Collection c) {
return jLeftOrTopTabs(horizontal, c);
}
static public SingleComponentPanel jOnDemand(IF0 makeComponent) {
SingleComponentPanel scp = singleComponentPanel();
bindToComponent(scp, () -> {
try {
scp.setComponent(makeComponent == null ? null : makeComponent.get());
} catch (Throwable e) {
printStackTrace(e);
scp.setComponent(jscroll(jFastLogView_noWrap(renderStackTrace(e))));
}
}, null);
return scp;
}
static public int withTopAndBottomMargin_defaultWidth = 6;
static public JPanel withTopAndBottomMargin(Component c) {
return withTopAndBottomMargin(withTopAndBottomMargin_defaultWidth, withTopAndBottomMargin_defaultWidth, c);
}
static public JPanel withTopAndBottomMargin(int topMargin, int bottomMargin, Component c) {
return swing(() -> {
JPanel p = new JPanel(new BorderLayout());
int w = withTopAndBottomMargin_defaultWidth;
p.setBorder(BorderFactory.createEmptyBorder(topMargin, 0, bottomMargin, 0));
p.add(c);
return p;
});
}
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 void addTabs(JTabbedPane tabs, Object... x) {
if (tabs == null)
return;
x = flattenToArray(x);
for (int i = 0; i < l(x); i++) {
Object o = x[i];
if (isComponentOrSwingable(o))
addTab(tabs, "Tab " + (tabCount(tabs) + 1), wrap(o));
else {
String toolTip = "";
if (o instanceof WithToolTip) {
toolTip = ((WithToolTip) o).toolTip();
o = ((WithToolTip) o).get();
}
String name = str(or(o, "Tab " + tabCount(tabs) + 1));
Component c;
if (isComponentOrSwingable(get(x, i + 1)))
c = wrap(get(x, ++i));
else
c = new JPanel();
addTabWithToolTip(tabs, name, toolTip, wrap(c));
}
}
}
static public List tabNames(JTabbedPane tabs) {
return tabs == null ? null : swing(() -> countIteratorToList(tabs.getTabCount(), i -> tabs.getTitleAt(i)));
}
static public String dropTrailingBracketedCount(String s) {
return replaceAll(s, "\\s?\\([0-9,]+\\)$", "");
}
static public int indexOfTabNameWithoutTrailingCount(JTabbedPane tabs, String name) {
if (tabs == null)
return 1;
return swing(() -> {
var _name_1 = dropTrailingBracketedCount(name);
int n = tabs.getTabCount();
for (int i = 0; i < n; i++) if (eqic(_name_1, dropTrailingBracketedCount(tabs.getTitleAt(i))))
return i;
return -1;
});
}
static public JLabel jcenteredlabel(String text) {
return jcenteredLabel(text);
}
static public JLabel jcenteredlabel() {
return jcenteredLabel();
}
static public void selectTab(final JTabbedPane tabs, final int idx) {
if (tabs != null) {
swing(() -> {
tabs.setSelectedIndex(idx);
});
}
}
static public void onTabSelected(final JTabbedPane tabs, final Runnable r) {
if (tabs != null) {
swing(() -> {
tabs.getModel().addChangeListener(changeListener(r));
});
}
}
static public boolean isShowing(Component c) {
return isComponentShowing(c);
}
static public String selectedTabName(JTabbedPane tabs) {
return tabs == null ? null : swing(() -> getTabTitle(tabs, tabs.getSelectedIndex()));
}
static public boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x))
return true;
return false;
}
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 void tabComponentClickFixer(JComponent c) {
onMouseDown(c, e -> {
JTabbedPane tabs = parentOfType(c, JTabbedPane.class);
if (tabs == null)
return;
var tabComponents = tabComponents(tabs);
for (int i = 0; i < l(tabComponents); i++) if (isGrandChildOf(c, tabComponents.get(i))) {
{
selectTab(tabs, i);
return;
}
}
});
}
static public int hstackWithSpacing_spacing = 10;
static public JPanel hstackWithSpacing(Object... parts) {
parts = flattenArray2(parts);
int spacing = hstackWithSpacing_spacing;
int i = 0;
if (first(parts) instanceof Integer) {
spacing = toInt(first(parts));
++i;
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.gridheight = GridBagConstraints.REMAINDER;
for (; i < l(parts); i++) {
if (i != 0)
panel.add(javax.swing.Box.createRigidArea(new Dimension(spacing, 0)), gbc);
panel.add(wrapForSmartAdd(parts[i]), gbc);
}
gbc.weightx = 1;
panel.add(jrigid(), gbc);
return panel;
}
static public boolean replaceTabTitleComponent(JTabbedPane tabs, String name, Component c) {
if (tabs == null)
return false;
return swing(new F0() {
public Boolean get() {
try {
int idx = tabs.indexOfTab(name);
if (idx < 0)
return false;
tabs.setTabComponentAt(idx, c);
return true;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "int idx = tabs.indexOfTab(name);\r\n if (idx < 0) false;\r\n tabs.setTabCom...";
}
});
}
static public void persistSelectedTabAsLiveValue(JTabbedPane tabs, SimpleLiveValue lv) {
String value = lv.get();
if (value != null) {
int idx = indexOfTabName(tabs, value);
if (idx >= 0)
selectTab(tabs, idx);
}
onChangeAndNow(tabs, () -> {
String name = getTabTitle(tabs, selectedTabIndex(tabs));
lv.set(name);
});
}
static public A focusOnFirstShow(A a) {
return focusOnShow(a);
}
static public String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static public String f2s(String s) {
return f2s(newFile(s));
}
static public String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static public JLabel jSimpleLabel() {
return jSimpleLabel("");
}
static public JLabel jSimpleLabel(String text) {
return swing(() -> new JLabel(text));
}
static public String conceptsDirName() {
return conceptsDirName(db_mainConcepts());
}
static public String conceptsDirName(Concepts cc) {
return fileName(cc.conceptsDir());
}
static public A componentPopupMenuItems(A c, final Object... params) {
componentPopupMenu(c, new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItems(menu, params);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItems(menu, params)";
}
});
return c;
}
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 boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return c.getText();";
}
});
}
static public String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return c.getText();";
}
});
}
static public String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return l.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return l.getText();";
}
});
}
static public String getText(final JComboBox cb) {
if (cb == null)
return null;
if (isEditableComboBox(cb))
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
static public JScrollPane jscroll_centered_borderless(Component c) {
return borderlessScrollPane(jscroll_centered(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 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 double nsToMicroseconds(double ns) {
return nanosToMicroseconds(ns);
}
static public String microSymbol() {
return "\u00B5";
}
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 JButton jimageButtonScaledToWidth(int w, String imageID, Runnable action) {
return jimageButtonScaledToWidth(w, imageID, "", action);
}
static public JButton jimageButtonScaledToWidth(int w, String imageID, String toolTip, Runnable action) {
return jimageButton(scaleImageToWidth(w, imageID), toolTip, action);
}
static public JComboBox jComboBox(final String... items) {
return jcombobox(items);
}
static public JComboBox jComboBox(Collection items) {
return jcombobox(items);
}
static public JComboBox jComboBox(Collection items, String selectedItem) {
return jcombobox(items, selectedItem);
}
static public JComboBox selectItem(A item, JComboBox cb) {
if (cb != null) {
swing(() -> {
cb.setSelectedItem(item);
});
}
return cb;
}
static public JComboBox selectItem(JComboBox cb, A item) {
return selectItem(item, cb);
}
static public JList selectItem(JList list, A item) {
{
swing(() -> {
selectRow(list, jlist_indexOf(list, item));
});
}
return list;
}
static public int screenCount() {
return l(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices());
}
static public Object swing(Object f) {
return swingAndWait(f);
}
static public void swing(Runnable f) {
swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public void setComboBoxItems(JComboBox cb, Collection items) {
if (cb != null) {
swing(() -> {
cb.setModel(new DefaultComboBoxModel(new Vector(items)));
});
}
}
static public List flattenToList(Object... l) {
Flattener f = new Flattener();
f.add(l);
return f.toList();
}
static public List countIteratorAsList_incl(int b) {
return countIteratorAsList_incl(0, b);
}
static public List countIteratorAsList_incl(int a, int b) {
return countIteratorToList_inclusive(a, b);
}
static public List countIteratorAsList_incl(int b, IF1 f) {
return countIteratorAsList_incl(0, b, f);
}
static public List countIteratorAsList_incl(int a, int b, IF1 f) {
return countIteratorToList_inclusive(a, b, f);
}
static public List countIteratorAsList_incl(int a, int b, int step) {
return countIteratorToList_inclusive(a, b, step);
}
static public List countIteratorAsList_incl(double a, double b, double step, IF1 f) {
return countIteratorToList_inclusive(a, b, step, f);
}
static public List countIteratorAsList_incl(double a, double b, double step) {
return countIteratorToList_inclusive(a, b, step);
}
static public List countIteratorAsList_incl(IF1 f, double a, double b, double step) {
return countIteratorToList_inclusive(f, a, b, step);
}
static public List countIteratorAsList_incl(IF1 f, int a, int b) {
return countIteratorAsList_incl(f, a, b, 1);
}
static public List countIteratorAsList_incl(IF1 f, int a, int b, int step) {
return countIteratorToList_inclusive(f, a, b, step);
}
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 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 JSpinner jspinner(int value) {
return jSpinner(value);
}
static public JSpinner jspinner(int value, int min, int max) {
return jSpinner(value, min, max);
}
static public int intFromSpinner(JSpinner s) {
return toInt(s.getValue());
}
static public JSpinner jPowersOfTwoSpinner(int max, int defaultValue) {
return jPowersOfTwoSpinner(1, max, defaultValue);
}
static public JSpinner jPowersOfTwoSpinner(int min, int max, int defaultValue) {
var powers = powersOfTwoUpTo(max);
if (min > 1)
powers = filter(powers, x -> x >= min);
return rightAlignSpinner(jListSpinner(powers, defaultValue));
}
static public JPanel jRaisedSection(Component c) {
return jRaisedSection("", c);
}
static public JPanel jRaisedSection(final String title, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
Border border = BorderFactory.createBevelBorder(BevelBorder.RAISED);
border = BorderFactory.createTitledBorder(border, title);
JPanel panel = new SingleComponentPanel(c);
panel.setBorder(border);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Border border = BorderFactory.createBevelBorder(BevelBorder.RAISED);\r\n bor...";
}
});
}
static public JPanel jRaisedSection(String title) {
return jRaisedSection(title, new JPanel());
}
static public String gazelle22_imagesSubDirName() {
return "Gazelle";
}
static public File saveImageWithCounter(File dir, String baseName, BufferedImage img) {
if (img == null || dir == null)
return null;
if (!isImageFileName(baseName))
baseName += ".png";
File f = makeFileNameUnique_beforeExtension_startWith1_noDot(newFile(dir, baseName));
saveImage(f, img);
infoBox("Saved image " + appendBracketed(img.getWidth(null) + "*" + img.getHeight(null)) + ": " + fileInfo(f));
return f;
}
static public A uniq(Class c, Object... params) {
return uniqueConcept(c, params);
}
static public A uniq(Concepts cc, Class c, Object... params) {
return uniqueConcept(cc, c, params);
}
static public List sortedByComparator(Collection l, Comparator c) {
List l2 = cloneList(l);
sort(l2, c);
return l2;
}
static public List sortedByComparator(Comparator c, Collection l) {
return sortedByComparator(l, c);
}
static public int cmpAlphanumIC(String a, String b) {
return cmpAlphaNum(a, b);
}
static public void onChangeAndNow(JComponent c, Object r) {
onUpdateAndNow(c, r);
}
static public void onChangeAndNow(List extends JComponent> l, Object r) {
onUpdateAndNow(l, r);
}
static public JComboBox onChangeAndNow(JComboBox cb, IVF1 f) {
onChange(cb, f);
{
if (f != null)
f.get(getSelectedItem_typed(cb));
}
return cb;
}
static public A onChangeAndNow(A tabs, Runnable r) {
if (r != null) {
onChange(tabs, r);
r.run();
}
return tabs;
}
static public Runnable r_dm_q(final Runnable r) {
DynModule mod = dm_current_mandatory();
return r_dm_q(mod, r);
}
static public Runnable r_dm_q(DynModule mod, Runnable r) {
return new Runnable() {
public void run() {
try {
dm_q(mod, r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_q(mod, r)";
}
};
}
static public void imageSurfaceOnLeftMouseDown(ImageSurface is, IVF1 action) {
if (is == null || action == null)
return;
{
swing(() -> {
MouseAdapter ma = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.getButton() == 1)
pcallF(action, is.pointFromEvent(e));
}
};
is.addMouseListener(ma);
});
}
}
static public A uniq_returnIfNew(Class c, Object... params) {
return uniq_returnIfNew(db_mainConcepts(), c, params);
}
static public A uniq_returnIfNew(Concepts cc, Class c, Object... params) {
Pair p = uniq2(cc, c, params);
return p.b ? p.a : null;
}
static public ScanlineBitMatrix toScanlineBitMatrix(Matrix m) {
if (m == null)
return null;
if (m instanceof ScanlineBitMatrix)
return ((ScanlineBitMatrix) m);
return new ScanlineBitMatrix(m);
}
static public BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static public BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
static public Collection conceptsWhere(Class c, Object... params) {
return findConceptsWhere(c, params);
}
static public Collection conceptsWhere(String c, Object... params) {
return findConceptsWhere(c, params);
}
static public Collection conceptsWhere(Concepts concepts, Class c, Object... params) {
return findConceptsWhere(concepts, c, params);
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(Object... c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public JTabbedPane jtabs(Object... x) {
return fillJTabs(swingNu(JTabbedPane.class), x);
}
static public void g22_highlightRegion(int[] pixels, ImageSurface is, Gazelle22_ImageToRegions itr, boolean showRegionsAsOutline) {
g22_highlightRegion(pixels, is, itr, is.mousePosition, showRegionsAsOutline);
}
static public void g22_highlightRegion(int[] pixels, ImageSurface is, Gazelle22_ImageToRegions itr, Pt mouse, boolean showRegionsAsOutline) {
if (mouse != null && itr != null && itr.regions != null) {
int iHighlightedRegion = itr.regions.regionAt(mouse);
int color = 0xFF00C000;
g22_highlightRegion(pixels, is, itr, iHighlightedRegion, color, showRegionsAsOutline);
}
}
static public void g22_highlightRegion(int[] pixels, ImageSurface is, Gazelle22_ImageToRegions itr, int iRegion, int color, boolean showRegionsAsOutline) {
if (iRegion == 0)
return;
if (showRegionsAsOutline) {
RegionBorder_innerPoints x = new RegionBorder_innerPoints(itr.regions, iRegion);
gazelle22_highlightRegionOutline(pixels, itr, x);
} else
itr.regions.markRegionInPixelArray(pixels, iRegion, color);
}
static public void waitUntil(int interval, IF0 condition) {
if (condition == null)
return;
while (!condition.get()) sleep(interval);
}
static public boolean waitUntil(int interval, double timeout, IF0 condition) {
if (condition == null)
return false;
long start = sysNow();
while (sysNow() < start + toMS(timeout)) if (condition.get())
return true;
else
sleep(interval);
return false;
}
static public boolean comboBoxContainsItem(JComboBox cb, A item) {
return contains(getComboBoxItems(cb), item);
}
static public JComboBox setSelectedItem(A item, JComboBox cb) {
return selectItem(item, cb);
}
static public JComboBox setSelectedItem(JComboBox cb, A item) {
return selectItem(cb, item);
}
static public JList setSelectedItem(JList list, A item) {
return selectItem(list, item);
}
static public JPanel northAndCenterWithMargins(Component n, Component c) {
return applyDefaultMargin(northAndCenter(withBottomMargin(n), c));
}
static public JPanel northAndCenterWithMargins(int margin, Component n, Component c) {
return applyMargin(margin, northAndCenter(withBottomMargin(margin, n), c));
}
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 Component horizontalStrut(int height) {
return Box.createHorizontalStrut(height);
}
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 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 JLabel jCenteredLabel(String text) {
return jcenteredLabel(text);
}
static public JLabel jCenteredLabel() {
return jcenteredLabel();
}
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 Object dm_callStem(Object moduleOrID, String method, Object... args) {
return call_withVarargs(dm_getStem(moduleOrID), method, args);
}
static public JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return new JScrollPane(c);";
}
});
}
static public JPanel makeForm3(Object... parts) {
return withRightMargin(makeForm2(parts));
}
static public String javaVersion() {
return System.getProperty("java.version");
}
static public String str_toMB_oneDigit(long l) {
return formatDouble1(toM(l)) + " MB";
}
static public long fileSize(String path) {
return getFileSize(path);
}
static public long fileSize(File f) {
return getFileSize(f);
}
static public String or2(String a, String b) {
return nempty(a) ? a : b;
}
static public String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
static public ClassLoader classLoader(Object o) {
return classLoaderForObject(o);
}
static public String str_toKB(long l) {
return n2(toK(l)) + " KB";
}
static public Class mc() {
return main.class;
}
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 boolean contains(Rect r, Pt p) {
return rectContains(r, p);
}
static public List _stickyLibs_1013490 = ll("#1400553", "#1400552", "#1004016", "#1004015");
static public List listWebCams() {
return Webcam.getWebcams();
}
static public JComboBox jTypedComboBox(Collection items) {
return swing(() -> new JComboBox (toVector(items)));
}
static public JComboBox jTypedComboBox(Collection items, A selectedItem) {
return selectItem(selectedItem, jTypedComboBox(items));
}
static public Webcam findWebCamByName(List cams, String name) {
if (empty(name))
return null;
for (Webcam cam : unnull(cams)) if (eqic(cam.getName(), name))
return cam;
return null;
}
static public AutoCloseable tempInfoBox(String msg) {
return tempDisposeWindow(infoBox(msg));
}
static public A getSelectedItem_typed(JList l) {
return swing(() -> l.getSelectedValue());
}
static public A getSelectedItem_typed(JComboBox cb) {
return swing(() -> (A) cb.getSelectedItem());
}
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 int l(LongBuffer b) {
return b == null ? 0 : b.size();
}
static public int l(AppendableChain a) {
return a == null ? 0 : a.size;
}
static public void deleteConcepts(Collection conceptsOrIDs) {
db_mainConcepts().deleteConcepts(asList(conceptsOrIDs));
}
static public List deleteConcepts(Class c, Object... params) {
return deleteConcepts(db_mainConcepts(), c, params);
}
static public List deleteConcepts(Concepts cc, Class c, Object... params) {
List l = asList(findConceptsWhere(cc, c, params));
deleteConcepts(l);
return l;
}
static public List deleteConcepts(Class c, IF1 pred) {
return deleteConcepts(db_mainConcepts(), c, pred);
}
static public List deleteConcepts(Concepts cc, Class c, IF1 pred) {
var l = filter(list(cc, c), pred);
deleteConcepts(l);
return l;
}
static public List deleteConcepts(Concepts cc) {
return deleteConcepts(cc, Concept.class);
}
static public String nImages(long n) {
return n2(n, "image");
}
static public String nImages(Collection l) {
return nImages(l(l));
}
static public boolean containsTabNameWithoutTrailingCount(JTabbedPane tabs, String name) {
return indexOfTabNameWithoutTrailingCount(tabs, name) >= 0;
}
static public void addTab(JTabbedPane tabs, String title, Component c) {
if (tabs != null) {
swing(() -> {
tabs.add(title, wrap(c));
});
}
}
static public void addTab(JTabbedPane tabs, String title, Swingable c) {
if (tabs != null) {
swing(() -> {
tabs.add(title, wrap(c));
});
}
}
static public boolean fileExists(String path) {
return path != null && new File(path).exists();
}
static public boolean fileExists(File f) {
return f != null && f.exists();
}
static public int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
static public int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static public Rect mouseArea(int w) {
return mouseArea(w, w);
}
static public Rect mouseArea(int w, int h) {
Point p = mouseLocation();
return new Rect(p.x - w / 2, p.y - h / 2, w, h);
}
static public int screenNrContaining(Pt p) {
if (p == null)
return -1;
return indexOfFirst(allScreenBounds(), screen -> contains(screen, p));
}
static public Pt mouseLocationPt() {
return mousePointer();
}
static public int screenNrOfWindow(Window w) {
if (w == null)
return -1;
Rect bounds = boundsAsRect(w);
return indexOfMax(allScreenBounds(), screen -> area(intersectRects(bounds, screen)));
}
static public int numberOfScreens() {
return screenCount();
}
static public String printLog() {
return getPrintLog();
}
static public List identifiers(String s) {
return tok_identifiersInOrder(s);
}
static public List identifiers(List tok) {
return tok_identifiersInOrder(tok);
}
static public A setBounds(final int x, final int y, final int w, final int h, final A a) {
if (a != null) {
swing(() -> {
a.setBounds(x, y, w, h);
});
}
return a;
}
static public A setBounds(A a, Rect r) {
if (a != null && r != null) {
swing(() -> {
a.setBounds(toRectangle(r));
});
}
return a;
}
static public A setBounds(A a, Rectangle r) {
if (a != null && r != null) {
swing(() -> {
a.setBounds(r);
});
}
return a;
}
static public A setBounds(Rect r, A a) {
return setBounds(a, r);
}
static public A setBounds(A a, int x, int y, int w, int h) {
return setBounds(x, y, w, h, a);
}
static public A onBoundsChange(A c, final Object r) {
if (c != null && r != null) {
swing(() -> {
c.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
pcallF(r);
}
public void componentMoved(ComponentEvent e) {
pcallF(r);
}
});
});
}
return c;
}
static public A onBoundsChange(Object r, A c) {
return onBoundsChange(c, r);
}
static public boolean isMain() {
return isMainProgram();
}
static public List cdelete(Class c, Object... params) {
return deleteConcepts(c, params);
}
static public void cdelete(Concept c) {
deleteConcept(c);
}
static public void cdelete(Collection c) {
for (A a : cloneList(c)) cdelete(a);
}
static public boolean isExtendedStateNormal(JFrame f) {
return f != null && swing(() -> f.getExtendedState() == JFrame.NORMAL);
}
static public void maximizeOrRestoreFrame(JFrame f) {
if (f == null)
return;
if (!isExtendedStateNormal(f)) {
swing(() -> {
f.setExtendedState(JFrame.NORMAL);
});
} else
maximizeFrame(f);
}
static public A onFirstShowing(A component, Runnable onShow) {
return onFirstComponentShow(component, onShow);
}
static public boolean swingConfirm(Component owner, String msg) {
return confirmOKCancel(owner, msg);
}
static public boolean swingConfirm(String msg) {
return confirmOKCancel(msg);
}
static public A setAlwaysOnTop(A c) {
return alwaysOnTop(c);
}
static public BufferedImage shootWindow(Window w) {
w.toFront();
sleep(50);
return shootScreen2(w.getBounds());
}
static public String copyToClipboard(String text) {
return copyTextToClipboard(text);
}
static public A copyToClipboard(A image) {
copyImageToClipboard(image);
return image;
}
static public File copyToClipboard(File f) {
return copyFileToClipboard(f);
}
static public Object ccallOpt(Concept.Ref ref, String method, Object... args) {
return callOptWithEnter(cDeref(ref), method, args);
}
static public Object ccallOpt(Object object, String method, Object... args) {
return callOptWithEnter(object, method, args);
}
static public A fontSizePlus(final int delta, final A c) {
if (c != null) {
swing(() -> {
Font font = c.getFont();
c.setFont(font.deriveFont(font.getSize2D() + delta));
});
}
return c;
}
static public boolean haveMuricaPassword() {
return nempty(muricaPassword());
}
static public A setOpaqueBackground(final Color color, final A a) {
if (a != null) {
swing(() -> {
a.setBackground(color);
a.setOpaque(true);
a.putClientProperty("substancelaf.colorizationFactor", 1.0);
});
}
return a;
}
static public A jtransparent_recursive(A a) {
if (a instanceof JPanel) {
((JPanel) a).setOpaque(false);
for (Component c : getSwingChildren(a)) jtransparent_recursive(c);
}
return a;
}
static public JLabel jImage_scaledToHeight(String imageID, int height) {
return jImage_scaledToHeight(imageID, height, null);
}
static public JLabel jImage_scaledToHeight(String imageID, int height, String toolTip) {
return setToolTip(toolTip, jImage(resizeImageToHeight_bilinear(loadImage2(imageID), height)));
}
static public JLabel jImage_scaledToHeight(int height, String imageID) {
return jImage_scaledToHeight(height, imageID, null);
}
static public JLabel jImage_scaledToHeight(int height, String imageID, String toolTip) {
return jImage_scaledToHeight(imageID, height, toolTip);
}
static public ImageIcon resizeImageIcon(ImageIcon icon, int newW) {
var img = icon.getImage();
int newH = iround(img.getHeight(null) * (double) newW / img.getWidth(null));
return imageIcon(resizeImage_raw(img, newW, newH, Image.SCALE_DEFAULT));
}
static public int imageIcon_cacheSize = 10;
static public boolean imageIcon_verbose = false;
static public Map imageIcon_cache;
static public Lock imageIcon_lock = lock();
static public ThreadLocal imageIcon_fixGIF = new ThreadLocal();
static public ImageIcon imageIcon(String imageID) {
try {
if (imageID == null)
return null;
Lock __0 = imageIcon_lock;
lock(__0);
try {
if (imageIcon_cache == null)
imageIcon_cache = new MRUCache(imageIcon_cacheSize);
imageID = fsI(imageID);
ImageIcon ii = imageIcon_cache.get(imageID);
if (ii == null) {
if (imageIcon_verbose)
print("Loading image icon: " + imageID);
File f = loadBinarySnippet(imageID);
Boolean b = imageIcon_fixGIF.get();
if (!isFalse(b))
ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
else
ii = new ImageIcon(f.toURI().toURL());
} else
imageIcon_cache.remove(imageID);
imageIcon_cache.put(imageID, ii);
return ii;
} finally {
unlock(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ImageIcon imageIcon(File f) {
try {
return new ImageIcon(f.toURI().toURL());
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ImageIcon imageIcon(Image img) {
return new ImageIcon(img);
}
static public ImageIcon imageIcon(RGBImage img) {
return imageIcon(img.getBufferedImage());
}
static public A onWindowDeiconified(A w, Runnable r) {
if (w != null && r != null) {
swing(() -> {
w.addWindowListener(new WindowAdapter() {
public void windowDeiconified(WindowEvent e) {
try {
r.run();
} catch (Throwable __e) {
printStackTrace(__e);
}
}
});
});
}
return w;
}
static public A maximizeFrame(A c) {
JFrame f = swing(new F0() {
public JFrame get() {
try {
JFrame f = getFrame(c);
if (f != null)
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JFrame f = getFrame(c);\r\n if (f != null)\r\n f.setExtendedState(JFrame....";
}
});
if (f != null && !isAWTThread()) {
Dimension d = maximumWindowBounds().getSize();
long start = sysNow();
while (licensed()) {
try {
if (f.getWidth() >= d.getWidth() - 100 && f.getHeight() >= d.getHeight() - 100)
break;
if (sysNow() >= start + 100) {
warn("maximizeFrame timeout");
break;
}
} catch (Throwable __e) {
printStackTrace(__e);
}
sleep(1);
}
}
return c;
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public int[] unnull(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnull(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnull(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public int unnull(Integer i) {
return i == null ? 0 : i;
}
static public long unnull(Long l) {
return l == null ? 0L : l;
}
static public double unnull(Double l) {
return l == null ? 0.0 : l;
}
static public Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
static public void setFrameContents(final Component c, final Object contents) {
swing(() -> {
JFrame frame = getFrame(c);
if (frame == null)
return;
frame.getContentPane().removeAll();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrap(contents));
revalidate(frame);
});
}
static public BufferedImage renderComponentToImage(final Component c) {
if (c == null)
return null;
return swing(new F0() {
public BufferedImage get() {
try {
int w = getWidth(c), h = getHeight(c);
BufferedImage img = newBufferedImage(w, h);
c.paint(createGraphics(img));
return img;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "int w = getWidth(c), h = getHeight(c);\r\n BufferedImage img = newBufferedIm...";
}
});
}
static public A copyImageToClipboard(A img) {
TransferableImage trans = new TransferableImage(img);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
vmBus_send("newClipboardContents", img);
print("Copied image to clipboard (" + img.getWidth(null) + "*" + img.getHeight(null) + " px)");
return img;
}
static public File saveInImageDirectoryWithCounter(String subPath, BufferedImage img) {
if (img == null)
return null;
assertNempty(subPath);
File dir = imagesDir();
if (!isImageFileName(subPath))
subPath += ".png";
File f = makeFileNameUnique_beforeExtension_startWith1_noDot(newFile(dir, subPath));
saveImage(f, img);
infoBox("Saved image " + appendBracketed(img.getWidth(null) + "*" + img.getHeight(null)) + ": " + fileInfo(f));
return f;
}
static public java.awt.Color awtColor(String hex) {
byte[] b = bytesFromHex(dropPrefix("#", hex));
return new Color(ubyteToInt(b[0]), ubyteToInt(b[1]), ubyteToInt(b[2]));
}
static public Q startQ() {
return new Q();
}
static public Q startQ(String name) {
return new Q(name);
}
static public CleanExit cleanExit(String msg) {
throw new CleanExit(msg);
}
static public CleanExit cleanExit() {
throw new CleanExit();
}
static public String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
static public void hideTrayIcon(TrayIcon t) {
removeTrayIcon(t);
}
static public void systemExit(int code) {
System.exit(code);
}
static public JFastLogView_noWrap showText_fast_noWrap(String title, Object text) {
return showText_fast_noWrap(null, title, text);
}
static public JFastLogView_noWrap showText_fast_noWrap(JFastLogView_noWrap view, String title, Object text) {
if (view != null) {
view.setText(str(text));
return view;
}
view = jFastLogView_noWrap(str(text));
makeFrame(title, jscroll_copyBackground(view));
return view;
}
static public JFastLogView_noWrap showText_fast_noWrap(Object text) {
return showText_fast_noWrap(autoFrameTitle(), text);
}
static public String renderStackTrace(StackTraceElement[] st) {
return stackTraceToString(st);
}
static public String renderStackTrace(Throwable e) {
return stackTraceToString(e);
}
static public String renderStackTrace(String msg) {
return renderStackTrace(new Throwable(msg));
}
static public Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static public void printJavaVersion() {
print("Java version: " + javaVersion());
}
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 String conceptsFileName() {
return "concepts.structure.gz";
}
static public String mcDollar() {
return mcName() + "$";
}
static public boolean cic(Collection l, String s) {
return containsIgnoreCase(l, s);
}
static public boolean cic(String[] l, String s) {
return containsIgnoreCase(l, s);
}
static public boolean cic(String s, char c) {
return containsIgnoreCase(s, c);
}
static public boolean cic(String a, String b) {
return containsIgnoreCase(a, b);
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public void sleepSeconds(double s) {
if (s > 0)
sleep(round(s * 1000));
}
static public Collection findConcepts(Class c, Object... params) {
return findConceptsWhere(c, params);
}
static public Collection findConcepts(String c, Object... params) {
return findConceptsWhere(c, params);
}
static public Collection findConcepts(Concepts concepts, Class c, Object... params) {
return findConceptsWhere(concepts, c, params);
}
static public Collection findConcepts(Concepts concepts, String c, Object... params) {
return findConceptsWhere(concepts, c, params);
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public Pair first(Map map) {
return mapEntryToPair(first(entrySet(map)));
}
static public Pair first(MultiMap mm) {
if (mm == null)
return null;
var e = first(mm.data.entrySet());
if (e == null)
return null;
return pair(e.getKey(), first(e.getValue()));
}
static public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public Character first(CharSequence s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public A first(T3 t) {
return t == null ? null : t.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public int first(IntBuffer buf) {
return buf.get(0);
}
static public byte first(ByteBuffer buf) {
return buf.get(0);
}
static public A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static public A first(AppendableChain a) {
return a == null ? null : a.element;
}
static public A registerConcept(A c) {
return registerConcept(db_mainConcepts(), c);
}
static public A registerConcept(Concepts cc, A c) {
{
if (cc != null)
cc.register(c);
}
return c;
}
static public int csetAll(Concept c, Object... values) {
return cset(c, values);
}
static public int csetAll(Iterable extends Concept> l, Object... values) {
int n = 0;
for (Concept c : unnullForIteration(l)) n += cset(c, values);
return n;
}
static public int csetAll(Concept c, Map values) {
int n = 0;
for (Map.Entry extends String, ? extends Object> __0 : _entrySet(values)) {
String field = __0.getKey();
Object value = __0.getValue();
n += cset(c, field, value);
}
return n;
}
static public A firstThat(Iterable l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(A[] l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public A firstThat(IF1 pred, A[] l) {
return firstThat(l, pred);
}
static public Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static public Thread startThread(String name, Runnable runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(runnable, name));
}
static public Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static public Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static public File myJar() {
return first(myLibraryFiles());
}
static public AutoCloseable tempDisableButtons(Collection buttons) {
return combineAutoCloseables(map(__56 -> tempDisableButton(__56), buttons));
}
static public List allJFrames() {
return allFrames();
}
static public IProgressShower tempProgressBar_addToWindowIfPossible(JWindow window, String text) {
return tempProgressBar_addToWindowIfPossible(window, text, 1);
}
static public IProgressShower tempProgressBar_addToWindowIfPossible(JWindow window, String text, double total) {
if (!isVisibleWindow(window))
return tempProgressBar(text, total);
JProgressBar bar = jProgressBarWithText(iround(total), text);
var closeable = tempAddToWindow(window, withMargin(jCenteredRaisedSection(text, bar)));
return new IProgressShower() {
public void setValue(double value) {
setProgressBarValue(bar, iround(value));
}
public void setTotal(double total) {
setProgressBarTotal(bar, iround(total));
}
public void setText(String text) {
setProgressBarText(bar, print(text));
}
public void close() {
_close(closeable);
}
};
}
static public IProgressShower tempProgressBar_addToWindowIfPossible(JFrame window, String text) {
return tempProgressBar_addToWindowIfPossible(window, text, 1);
}
static public IProgressShower tempProgressBar_addToWindowIfPossible(JFrame window, String text, double total) {
if (!isVisibleWindow(window))
return tempProgressBar(text, total);
JProgressBar bar = jProgressBarWithText(iround(total), text);
var closeable = tempAddToWindow(window, withMargin(jCenteredRaisedSection(text, bar)));
return new IProgressShower() {
public void setValue(double value) {
setProgressBarValue(bar, iround(value));
}
public void setTotal(double total) {
setProgressBarTotal(bar, iround(total));
}
public void setText(String text) {
setProgressBarText(bar, print(text));
}
public void close() {
_close(closeable);
}
};
}
static public void postBinaryPageToFile(File file, String url, Object... params) {
doPostBinaryToFile(litmap(params), url, file);
}
static public void postBinaryPageToFile(String url, File file, Object... params) {
doPostBinaryToFile(litmap(params), url, file);
}
static public long done2_always(long startTime, String desc) {
long time = sysNow() - startTime;
saveTiming_noPrint(time);
print(desc + " [" + time + " ms]");
return time;
}
static public long done2_always(String desc, long startTime) {
return done2_always(startTime, desc);
}
static public long done2_always(long startTime) {
return done2_always(startTime, "");
}
static public boolean isFile(File f) {
return f != null && f.isFile();
}
static public boolean isFile(String path) {
return isFile(newFile(path));
}
static public File fileInSubDir(File f, String subDir) {
if (f == null)
return null;
File dir = dirOfFile(f);
return newFile(dir, subDir, f.getName());
}
static public File fileInSubDir(String subDir, File f) {
return fileInSubDir(f, subDir);
}
static public File appendToFileName(File f, String suffix) {
return fileAppendToName(f, suffix);
}
static public File appendToFileName(String suffix, File f) {
return appendToFileName(f, suffix);
}
static public List tlft(String s) {
return toLinesFullTrim(s);
}
static public List tlft(File f) {
return toLinesFullTrim(f);
}
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(LongBuffer 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 String nFiles(long n) {
return n2(n, "file");
}
static public String nFiles(Collection l) {
return nFiles(l(l));
}
static public int countFilesInZip(File inZip) {
try {
ZipFile zipFile = new ZipFile(inZip);
try {
return countFilesInZip(zipFile);
} finally {
_close(zipFile);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public int countFilesInZip(ZipFile zipFile) {
try {
int n = 0;
Enumeration entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) (entries.nextElement());
if (!entry.isDirectory())
++n;
}
return n;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean renameFileVerbose(File a, File b) {
if (a == null || b == null)
return false;
boolean result = a.renameTo(b);
print("Renaming " + f2s(a) + " to " + f2s(b) + "? " + yesNo2(result));
return result;
}
static public boolean renameFileVerbose(File a, String newName) {
return renameFileVerbose(a, fileInSameDir(a, newName));
}
static public String currentProcessCommand() {
ProcessHandle processHandle = ProcessHandle.current();
return getVar(processHandle.info().command());
}
static public StefansOS_ConnectToServer snippetUpdateConnector(Object... __) {
boolean verbose = boolPar("verbose", __);
StefansOS_ConnectToServer connector = new StefansOS_ConnectToServer();
connector.onLine = new VF1() {
public void get(String line) {
try {
Matches m = new Matches();
if (startsWith(line, "snippetUpdates:", m)) {
if (verbose)
print(line);
String msg = m.rest();
vmBus_send("snippetUpdate", safeUnstruct(msg));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new Matches m;\r\n if (startsWith(line, \"snippetUpdates:\", m)) {\r\n if (...";
}
};
connector.startWithSubs("snippetUpdates");
return connector;
}
static public AutoCloseable vmBus_onMessage(String msg, IVF1 onMessage) {
return vmBus_onMessage(msg, ivf1ToVF1(onMessage));
}
static public AutoCloseable vmBus_onMessage(final String msg, final VF1 onMessage) {
Map map = vm_busListenersByMessage_live();
synchronized (map) {
Set listeners = map.get(msg);
if (listeners == null)
map.put(msg, listeners = syncIdentityHashSet());
return tempAdd(listeners, new VF2() {
public void get(String _msg, Object arg) {
try {
callF(onMessage, arg);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, arg)";
}
});
}
}
static public AutoCloseable vmBus_onMessage(String msg, final VF2 onMessage) {
return vmBus_onMessage(msg, new VF1() {
public void get(Object[] o) {
try {
callF(onMessage, first(o), second(o));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, first(o), second(o));";
}
});
}
static public AutoCloseable vmBus_onMessage(String msg, final IVF2 onMessage) {
return vmBus_onMessage(msg, new VF1() {
public void get(Object[] o) {
try {
callF(onMessage, first(o), second(o));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, first(o), second(o));";
}
});
}
static public AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) {
return vmBus_onMessage(msg, runnableToVF1(onMessage));
}
static public String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
static public String getString(List l, int idx) {
return (String) get(l, idx);
}
static public String getString(Object o, Object key) {
if (o instanceof Map)
return getString((Map) o, key);
if (key instanceof String)
return (String) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
static public String getString(String key, Object o) {
return getString(o, (Object) key);
}
static public boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static public boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
static public boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b))
return false;
return parseSnippetID(a) == parseSnippetID(b);
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public String firstIntAsString(String s) {
return jextract("", s);
}
static public long psI(String snippetID) {
return parseSnippetID(snippetID);
}
static public List mapNonNulls(Iterable l, Object f) {
return mapNonNulls(f, l);
}
static public List mapNonNulls(Object f, Iterable l) {
List x = new ArrayList();
if (l != null)
for (Object o : l) addIfNotNull(x, callF(f, o));
return x;
}
static public List mapNonNulls(Object f, Object[] l) {
List x = new ArrayList();
if (l != null)
for (Object o : l) addIfNotNull(x, callF(f, o));
return x;
}
static public List mapNonNulls(Iterable l, F1 f) {
return mapNonNulls(f, l);
}
static public List mapNonNulls(F1 f, Iterable l) {
List x = new ArrayList();
if (l != null)
for (Object o : l) addIfNotNull(x, callF(f, o));
return x;
}
static public List mapNonNulls(A[] l, IF1 f) {
return mapNonNulls(f, l);
}
static public List mapNonNulls(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) addIfNotNull(x, f.get(o));
return x;
}
static public List mapNonNulls(IF1 f, Iterable l) {
return mapNonNulls(l, f);
}
static public AutoCloseable tempSetButtonImages(Collection buttons, ImageIcon img) {
return combineAutoCloseables(map(buttons, b -> tempSetButtonImage(b, img)));
}
static public class transpileOnServerWithErrorWindow_DaClass {
public String snippetID;
public JFastLogView_noWrap transpilationErrorBox;
public Runnable onSuccess;
public Object onError;
public void go(boolean medium) {
infoBox("Transpiling " + snippetID);
final Pair p = transpileOnBestServer(snippetID, medium ? "medium" : "quick");
swingLater(new Runnable() {
public void run() {
try {
if (p.a) {
infoBox("Transpiled OK!");
hideWindow(transpilationErrorBox);
transpilationErrorBox = null;
callFInNewThread(onSuccess);
} else {
infoBox("Transpilation error. " + p.b);
boolean first = transpilationErrorBox == null;
transpilationErrorBox = maximizeFrame(scrollAllTheWayDown(showText_fast_noWrap(transpilationErrorBox, "Transpilation Error", p.b)));
if (first) {
setFrameIcon("#1101268", transpilationErrorBox);
addButtonsToWindow(transpilationErrorBox, "Medium transpile", runnableThread(new Runnable() {
public void run() {
try {
go(true);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "go(true)";
}
}));
}
callFInNewThread(onError, p.b);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (p.a) {\r\n infoBox(\"Transpiled OK!\");\r\n hideWindow(transpilat...";
}
});
}
}
static public void transpileOnServerWithErrorWindow(String snippetID, boolean medium, final Runnable onSuccess, Object... __) {
nu(transpileOnServerWithErrorWindow_DaClass.class, paramsPlus(__, "snippetID", snippetID, "onSuccess", onSuccess)).go(medium);
}
static public AutoCloseable tempInfoBoxNoHide(String msg) {
return tempInfoBox_noHide(msg);
}
static public Map cgetAll(Concept c, Collection fields) {
return mapToValues(fields, f -> cget(c, f));
}
static public Collection allConcepts() {
return db_mainConcepts().allConcepts();
}
static public Collection allConcepts(Concepts concepts) {
return concepts.allConcepts();
}
static public List zipFileToJSONFingerprint_md5(File zip) {
var zipFile = zipFile(zip);
try {
return zipFileToJSONFingerprint_md5(zipFile);
} finally {
_close(zipFile);
}
}
static public List zipFileToJSONFingerprint_md5(ZipFile zip) {
return map(listZipEntries(zip), e -> {
try {
return litorderedmap("name", e.getName(), "md5", md5OfStream(zip.getInputStream(e)));
} catch (Exception __e) {
throw rethrow(__e);
}
});
}
static public String base64encode(byte[] a) {
int aLen = a.length;
int numFullGroups = aLen / 3;
int numBytesInPartialGroup = aLen - 3 * numFullGroups;
int resultLen = 4 * ((aLen + 2) / 3);
StringBuffer result = new StringBuffer(resultLen);
char[] intToAlpha = intToBase64;
int inCursor = 0;
for (int i = 0; i < numFullGroups; i++) {
int byte0 = a[inCursor++] & 0xff;
int byte1 = a[inCursor++] & 0xff;
int byte2 = a[inCursor++] & 0xff;
result.append(intToAlpha[byte0 >> 2]);
result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]);
result.append(intToAlpha[(byte1 << 2) & 0x3f | (byte2 >> 6)]);
result.append(intToAlpha[byte2 & 0x3f]);
}
if (numBytesInPartialGroup != 0) {
int byte0 = a[inCursor++] & 0xff;
result.append(intToAlpha[byte0 >> 2]);
if (numBytesInPartialGroup == 1) {
result.append(intToAlpha[(byte0 << 4) & 0x3f]);
result.append("==");
} else {
int byte1 = a[inCursor++] & 0xff;
result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]);
result.append(intToAlpha[(byte1 << 2) & 0x3f]);
result.append('=');
}
}
return result.toString();
}
static final public char[] intToBase64 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
static public byte[] gzipString(String s) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gos = new GZIPOutputStream(baos);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gos, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(s);
printWriter.close();
gos.close();
return baos.toByteArray();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String jsonEncode(Object o) {
StringBuilder buf = new StringBuilder();
jsonEncode(o, buf);
return str(buf);
}
static public void jsonEncode(Object o, StringBuilder buf) {
if (o == null)
buf.append("null");
else if (o instanceof String)
buf.append(quote((String) o));
else if (o instanceof Number || o instanceof Boolean)
buf.append(o);
else if (o instanceof Map) {
Map map = (Map) o;
buf.append("{");
boolean first = true;
for (Object key : keys(map)) {
if (first)
first = false;
else
buf.append(",");
buf.append(quote((String) key));
buf.append(":");
jsonEncode(map.get(key), buf);
}
buf.append("}");
} else if (o instanceof Collection) {
Collection l = (Collection) o;
buf.append("[");
boolean first = true;
for (Object element : l) {
if (first)
first = false;
else
buf.append(",");
jsonEncode(element, buf);
}
buf.append("]");
} else
throw fail("Unknown object for JSON encoding: " + className(o));
}
static public void ping_v3_setPingSourceMaker(IF0 pingMaker) {
vm_generalMap_set("ping_v3_pingSourceMaker", pingMaker);
}
static public int findIntArg(String name, String[] args, int defaultValue) {
int i = indexOfIC(args, name);
return i >= 0 && i + 1 < l(args) ? parseInt(args[i + 1]) : defaultValue;
}
static public int cores() {
return numberOfCores();
}
static public boolean ping() {
return ping(pingSource());
}
static public boolean ping(PingSource source) {
ping_v3(source);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
return ping();
}
static volatile public boolean ping_pauseAll = false;
static public 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 setDialogContents(JDialog dialog, JComponent contents) {
if (dialog == null)
return;
{
swing(() -> {
dialog.getContentPane().removeAll();
dialog.getContentPane().setLayout(new BorderLayout());
dialog.getContentPane().add(wrap(contents));
revalidate(dialog);
});
}
}
static public A packWindow(final A c) {
{
swing(() -> {
Window w = getWindow(c);
if (w != null)
w.pack();
});
}
return c;
}
static public void minWindowWidth(Window window, int w) {
if (window != null) {
swing(() -> {
if (window.getWidth() < w)
window.setSize(w, window.getHeight());
});
}
}
static public void centerDialogOverOwner(JDialog dialog) {
if (dialog != null) {
swing(() -> {
var owner = dialog.getOwner();
if (owner != null)
setLocation(dialog, center(boundsRect(owner)));
});
}
}
static public File programDir_mine;
static public File programDir() {
return programDir(getProgramID());
}
static public File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
if (me) {
String c = caseID();
if (nempty(c))
dir = newFile(dir, c);
}
return dir;
}
static public File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
static public void clearConceptsOf(String progID) {
getProgramFile(progID, "concepts.structure").delete();
getProgramFile(progID, "concepts.structure.gz").delete();
getProgramFile(progID, "idCounter.structure").delete();
}
static public List syncMap(Object f, Map map) {
return syncMap(map, f);
}
static public List syncMap(Map map, Object f) {
return map(cloneLinkedHashMap(map), f);
}
static public Map syncMap() {
return synchroHashMap();
}
static public Map syncMap(Map map) {
return synchronizedMap(map);
}
static public A second(List l) {
return get(l, 1);
}
static public A second(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
if (!it.hasNext())
return null;
it.next();
return it.hasNext() ? it.next() : null;
}
static public A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static public B second(Pair p) {
return p == null ? null : p.b;
}
static public B second(T3 t) {
return t == null ? null : t.b;
}
static public A second(Producer p) {
if (p == null)
return null;
if (p.next() == null)
return null;
return p.next();
}
static public char second(String s) {
return charAt(s, 1);
}
static public B second(Either e) {
return e == null ? null : e.bOpt();
}
static public Rect rectUnion(Rect a, Rect b) {
if (a == null)
return b;
if (b == null)
return a;
int x = min(a.x, b.x), y = min(a.y, b.y);
int x2 = max(a.x + a.w, b.x + b.w), y2 = max(a.y + a.h, b.y + b.h);
return new Rect(x, y, x2 - x, y2 - y);
}
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 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 BufferedImage whiteImage(int w, int h) {
return newBufferedImage(w, h, Color.white);
}
static public BufferedImage whiteImage(int size) {
return whiteImage(size, size);
}
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 Rect translateRect(int x, int y, Rect r) {
return translateRect(r, x, y);
}
static public Rect translateRect(Rect r, int x, int y) {
return r == null ? null : new Rect(r.x + x, r.y + y, r.w, r.h);
}
static public int random(int n) {
return random(n, defaultRandomGenerator());
}
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 defaultRandomGenerator().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 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 A lowest(Map map) {
A best = null;
Number bestScore = null;
for (A key : keys(map)) {
Number score = map.get(key);
if (best == null || cmp(score, bestScore) < 0) {
best = key;
bestScore = score;
}
}
return best;
}
static public A lowest(Iterable l, IF1 f) {
return lowestByScoreFunction(l, f);
}
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 boolean jmenuItem_newThreads = false;
static public JMenuItem jmenuItem(final String text) {
return jMenuItem(text, null);
}
static public JMenuItem jmenuItem(final String text, final Object r) {
return swing(new F0() {
public JMenuItem get() {
try {
Pair p = jmenu_autoMnemonic(dropPrefix("[disabled] ", text));
JMenuItem mi = new JMenuItem(p.a);
if (startsWith(text, "[disabled] "))
disableMenuItem(mi);
if (p.b != 0)
mi.setMnemonic(p.b);
mi.addActionListener(jmenuItem_newThreads ? actionListenerInNewThread(r) : actionListener(r));
return mi;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Pair p = jmenu_autoMnemonic(dropPrefix(\"[disabled] \", text));\r\n JM...";
}
});
}
static public void dm_watchFields(Collection fields, Runnable onChange) {
for (String field : unnullForIteration(fields)) dm_watchField(field, onChange);
}
static public String joinNemptiesWithColon(String... strings) {
return joinNempties(": ", strings);
}
static public String joinNemptiesWithColon(Collection strings) {
return joinNempties(": ", strings);
}
static public int identityHash(Object o) {
return identityHashCode(o);
}
static public boolean isConceptFieldIndexed(Class extends Concept> c, String field) {
return isConceptFieldIndexed(db_mainConcepts(), c, field);
}
static public boolean isConceptFieldIndexed(Concepts concepts, Class extends Concept> c, String field) {
return concepts.getFieldIndex(c, field) != null;
}
static public void onConceptsChange(Runnable r) {
onConceptsChange(db_mainConcepts(), r);
}
static public void onConceptsChange(Concepts cc, Runnable r) {
cc.addConceptIndex(simpleConceptIndex(r));
cc.onAllChanged.add(r);
}
static public Pair enclosingTab(Component _c) {
return swing(() -> {
Component c = _c;
while (c != null) {
Container p = c.getParent();
if (p instanceof JTabbedPane)
return pair(((JTabbedPane) p), ((JTabbedPane) p).indexOfComponent(c));
c = c.getParent();
}
return null;
});
}
static public void setTabTitle(JTabbedPane tabs, int idx, String title) {
if (tabs != null && idx >= 0) {
swing(() -> {
if (idx < tabs.getTabCount())
tabs.setTitleAt(idx, title);
});
}
}
static public String appendBracketedCount(int n, String a) {
return appendBracketed(a, n2(n));
}
static public String appendBracketedCount(String a, int n) {
return appendBracketedCount(n, a);
}
static public String getTabTitle(JTabbedPane tabs, int idx) {
return tabs == null || idx < 0 ? null : swing(() -> idx < tabs.getTabCount() ? tabs.getTitleAt(idx) : null);
}
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 LinkedHashMap mapSortedByValue(Map map) {
return orderMapByValue(map);
}
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 boolean isScreenCoordinateInWindow(Pt p, Component c) {
Window w = getWindow(c);
return w != null && w.isShowing() && toRect(boundsOnScreen(w)).contains(p);
}
static public Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
static public int colorToIntOpaque(Color c) {
return c.getRGB() | 0xFF000000;
}
static public Color blendColors(double bish, Color a, Color b) {
return blendColors(a, b, bish);
}
static public Color blendColors(Color a, Color b, double bish) {
bish = normalizeTo0to1(bish);
return new Color((float) blend(a.getRed() / 255.0, b.getRed() / 255.0, bish), (float) blend(a.getGreen() / 255.0, b.getGreen() / 255.0, bish), (float) blend(a.getBlue() / 255.0, b.getBlue() / 255.0, bish));
}
static public Color lightBlue_cache;
static public Color lightBlue() {
if (lightBlue_cache == null)
lightBlue_cache = lightBlue_load();
return lightBlue_cache;
}
static public Color lightBlue_load() {
return colorFromHex("4169e1");
}
static public Set _registerAutoCloseable_set = synchroHashSet();
static public void _registerAutoCloseable(AutoCloseable c) {
addIfNotNull(_registerAutoCloseable_set, c);
}
static public void cleanMeUp__registerAutoCloseable() {
closeAutoCloseables(getAndClearList(_registerAutoCloseable_set));
}
static public double msToSeconds(long ms) {
return toSeconds(ms);
}
static public double msToSeconds(double ms) {
return toSeconds(ms);
}
static public File imagesDir() {
return userDir_oneOf_createIfNone("Pictures", "OneDrive/Pictures", "OneDrive/Bilder", "Pictures", "Bilder");
}
static public File imagesDir(String sub) {
return newFile(imagesDir(), sub);
}
static public boolean isImageFileName(String s) {
return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif");
}
static public ArrayList emptyList() {
return new ArrayList();
}
static public ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
static public ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static public ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
static public ArrayList emptyList(Class c) {
return new ArrayList();
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(long[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(double[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static public ArrayList asList(short[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (short i : a) l.add(i);
return l;
}
static public ArrayList asList(Iterator it) {
ArrayList l = new ArrayList();
if (it != null)
while (it.hasNext()) l.add(it.next());
return l;
}
static public ArrayList asList(IterableIterator s) {
return asList((Iterator) s);
}
static public ArrayList asList(Iterable s) {
if (s instanceof ArrayList)
return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s) l.add(a);
return l;
}
static public ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null)
while ((a = p.next()) != null) l.add(a);
return l;
}
static public ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static public HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static public void litmap_impl(Map map, Object... x) {
if (x != null)
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
static public 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(LongBuffer b) {
return b == null || b.isEmpty();
}
static public boolean empty(Rect r) {
return !(r != null && r.w != 0 && r.h != 0);
}
static public boolean empty(AppendableChain c) {
return c == null;
}
static public 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 A setBorder(Border border, A c) {
if (c != null) {
swing(() -> {
c.setBorder(border);
});
}
return c;
}
static public A setBorder(A c, Border border) {
return setBorder(border, c);
}
static public JScrollPane withoutViewportBorder(JScrollPane sp) {
if (sp != null) {
swing(() -> {
sp.setViewportBorder(null);
});
}
return sp;
}
static public JPanel vstack2(final Object... parts) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
smartAddWithLayout(panel, gbc, parts);
gbc.weighty = 1;
panel.add(jrigid(), gbc);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new GridBagLayout);\r\n new GridBagConstraints gbc...";
}
});
}
static public JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
for (Object o : parts) panel.add(wrapForSmartAdd(o), layout);
return panel;
}
static public JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
return smartAddWithLayout(panel, layout, asList(flattenArray2(parts)));
}
static public Component jrigid() {
return javax.swing.Box.createRigidArea(new Dimension(0, 0));
}
static public JSpinner liveValueSpinner(SimpleLiveValue lv, int min, int max) {
JSpinner spinner = jSpinner(lv.get(), min, max);
return bindLiveValueToSpinner(lv, spinner);
}
static public JSpinner bindLiveValueToSpinner(SimpleLiveValue lv, JSpinner spinner) {
onChange(spinner, new Runnable() {
public void run() {
try {
lv.set(intFromSpinner(spinner));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "lv.set(intFromSpinner(spinner))";
}
});
lv.onChange(new Runnable() {
public void run() {
try {
setSpinnerValue(spinner, lv.get());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "setSpinnerValue(spinner, lv!)";
}
});
return spinner;
}
static public A toolTipFromLiveValue(LiveValue lv, A c) {
return bindToolTipToLiveValue(lv, c);
}
static public LiveValue dm_transientCalculatedLiveValue(Class type, IF0 calc) {
return dm_transientCalculatedLiveValue(dm_current_mandatory(), type, calc);
}
static public LiveValue dm_transientCalculatedLiveValue(DynModule mod, Class type, IF0 calc) {
Lock __0 = mod.lock;
lock(__0);
try {
SimpleLiveValue value = new SimpleLiveValue(type, calc.get());
mod.onFieldChange(new VF1() {
public void get(String field) {
try {
value.set(calc.get());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "value.set(calc!)";
}
});
return value;
} finally {
unlock(__0);
}
}
static public LiveValue dm_transientCalculatedLiveValue(IF0 calc) {
return dm_transientCalculatedLiveValue(Object.class, calc);
}
static public A setHorizontalAlignment(final int pos, final A a) {
swingCall(a, "setHorizontalAlignment", pos);
return a;
}
static public A setHorizontalAlignment(final int pos, final A a) {
swingCall(a, "setHorizontalAlignment", pos);
return a;
}
static public A setHorizontalAlignment(final int pos, final A a) {
swingCall(a, "setHorizontalAlignment", pos);
return a;
}
static public JTabbedPane jLeftOrTopTabs(boolean horizontal, Object... x) {
return horizontal ? jLeftTabs(x) : jtabs(x);
}
static public JTabbedPane jLeftOrTopTabs(boolean horizontal, Collection c) {
return horizontal ? jLeftTabs(c) : jtabs(c);
}
static public JFastLogView_noWrap jFastLogView_noWrap() {
return jFastLogView_noWrap("");
}
static public JFastLogView_noWrap jFastLogView_noWrap(String text) {
return withTypeWriterFont(swingNu(JFastLogView_noWrap.class, text));
}
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 Object[] flattenToArray(Object... a) {
return flattenArray2(a);
}
static public boolean isComponentOrSwingable(Object o) {
if (o instanceof Swingable)
return true;
return o instanceof Component;
}
static public int tabCount(final JTabbedPane tabs) {
return tabs == null ? 0 : swing(new F0() {
public Integer get() {
try {
return tabs.getTabCount();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return tabs.getTabCount();";
}
});
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static public void addTabWithToolTip(JTabbedPane tabs, String title, String toolTip, Component c) {
if (tabs == null)
return;
{
swing(() -> {
addTab(tabs, title, c);
if (nempty(toolTip))
tabs.setToolTipTextAt(tabCount(tabs) - 1, toolTip);
});
}
}
static public void addTabWithToolTip(JTabbedPane tabs, String title, String toolTip, Swingable c) {
addTabWithToolTip(tabs, title, toolTip, wrap(c));
}
static public List replaceAll(List l, final A a, final A b) {
return map(l, new F1 () {
public A get(A x) {
try {
return eq(x, a) ? b : x;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "eq(x, a) ? b : x";
}
});
}
static public String replaceAll(String s, String a, String b) {
return s == null ? null : s.replaceAll(a, b);
}
static public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public JLabel jcenteredLabel(String text) {
return setHorizontalAlignment(JLabel.CENTER, jLabel(text));
}
static public JLabel jcenteredLabel() {
return jcenteredLabel(" ");
}
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 "return c.isShowing();";
}
});
}
static public A setToolTipText(final A c, final Object toolTip) {
if (c == null)
return null;
{
swing(() -> {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
});
}
return c;
}
static public A setToolTipText(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
static public void setTrayIconToolTip(TrayIcon trayIcon, String toolTip) {
if (trayIcon != null)
trayIcon.setToolTip(toolTip);
}
static public A parentOfType(Component _c, Class theClass) {
return swing(() -> {
Component c = _c;
while (c != null) {
if (isInstance(theClass, c))
return (A) c;
c = c.getParent();
}
return null;
});
}
static public List tabComponents(final JTabbedPane tabs) {
final List l = new ArrayList();
if (tabs != null) {
swing(() -> {
for (int i = 0; i < tabs.getTabCount(); i++) l.add(tabs.getTabComponentAt(i));
});
}
return l;
}
static public boolean isGrandChildOf(Component a, Component b) {
if (a == b)
return true;
while ((a = getParent(a)) != null) if (a == b)
return true;
return false;
}
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 int indexOfTabName(JTabbedPane tabs, String name) {
return tabs == null ? -1 : swing(() -> tabs.indexOfTab(name));
}
static public int selectedTabIndex(final JTabbedPane tabs) {
return tabs == null ? -1 : swing(new F0() {
public Integer get() {
try {
return tabs.getSelectedIndex();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return tabs.getSelectedIndex();";
}
});
}
static public A focusOnShow(final A a) {
onFirstComponentShow(a, new Runnable() {
public void run() {
try {
focus(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "focus(a)";
}
});
return a;
}
static public void addMenuItems(JMenu m, Object... x) {
fillJMenu(m, x);
}
static public void addMenuItems(JPopupMenu m, Object... x) {
fillJPopupMenu(m, x);
}
static public JPanel marginPanel() {
return jtransparent(borderLayoutPanel());
}
static public void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
static public String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
static public String fromLines(String... lines) {
return fromLines(asList(lines));
}
static public IterableIterator toLines(File f) {
return linesFromFile(f);
}
static public List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
static public int toLines_nextLineBreak(String s, int start) {
int n = s.length();
for (int i = start; i < n; i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static public List mapToLines(Map map) {
List l = new ArrayList();
for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
return l;
}
static public String mapToLines(Map map, Object f) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Map map) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Iterable l) {
return lines(map(f, l));
}
static public String mapToLines(Iterable l, IF1 f) {
return mapToLines((Object) f, l);
}
static public String mapToLines(IF1 f, Iterable l) {
return mapToLines((Object) f, l);
}
static public String mapToLines(Map map, IF2 f) {
return lines(map(map, f));
}
static public String mapToLines(IF1 f, A data1, A... moreData) {
return lines(map(f, data1, moreData));
}
static public List sortedIgnoreCase(Collection c) {
List l = cloneList(c);
Collections.sort(l, caseInsensitiveComparator());
return l;
}
static public double nanosToMicroseconds(double ns) {
return ns / 1000;
}
static public JButton jimageButton(String imageID, Object action) {
JButton btn = jbutton("", action);
btn.setIcon(imageIcon(imageID));
return btn;
}
static public JButton jimageButton(String imageID) {
return jimageButton(imageID, null);
}
static public JButton jimageButton(Image img) {
return jimageButton(img, null, null);
}
static public JButton jimageButton(Image img, String toolTip, Runnable action) {
var btn = jbutton("", action);
setButtonImage(btn, img);
return setToolTip(toolTip, btn);
}
static public JButton jimageButton(ImageIcon img, String toolTip, Runnable action) {
var btn = jbutton("", action);
setButtonImage(btn, img);
return setToolTip(toolTip, btn);
}
static public BufferedImage scaleImageToWidth(BufferedImage img, int newW) {
return resizeImage(img, newW);
}
static public BufferedImage scaleImageToWidth(int newW, BufferedImage img) {
return scaleImageToWidth(img, newW);
}
static public BufferedImage scaleImageToWidth(int newW, String imageID) {
return scaleImageToWidth(newW, loadImage2(imageID));
}
static public JComboBox jcombobox(final String... items) {
return swing(new F0() {
public JComboBox get() {
try {
return new JComboBox(items);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return new JComboBox(items);";
}
});
}
static public JComboBox jcombobox(Collection items) {
return jcombobox(toStringArray(items));
}
static public JComboBox jcombobox(Collection items, String selectedItem) {
return selectItem(selectedItem, jcombobox(items));
}
static public void selectRow(final JTable table, final int i) {
if (table != null) {
swing(() -> {
if (i >= 0 && i < table.getRowCount()) {
table.setRowSelectionInterval(i, i);
scrollRowToVisible(table, i);
} else
table.clearSelection();
});
}
}
static public void selectRow(final JList list, final int i) {
if (list != null) {
swing(() -> {
if (i >= 0 && i < listRowCount(list))
list.setSelectedIndex(i);
else
list.clearSelection();
});
}
}
static public int jlist_indexOf(JList list, A item) {
return swing(new F0() {
public Integer get() {
try {
ListModel model = list.getModel();
int n = model.getSize();
for (int i = 0; i < n; i++) if (eq(model.getElementAt(i), item))
return i;
return -1;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ListModel model = list.getModel();\r\n int n = model.getSize();\r\n for ...";
}
});
}
static public List countIteratorToList_inclusive(int b) {
return countIteratorToList_inclusive(0, b);
}
static public List countIteratorToList_inclusive(int a, int b) {
return asList(countIterator_inclusive(a, b));
}
static public List countIteratorToList_inclusive(int b, IF1 f) {
return countIteratorToList_inclusive(0, b, f);
}
static public List countIteratorToList_inclusive(int a, int b, IF1 f) {
return asList(countIterator_inclusive(a, b, f));
}
static public List countIteratorToList_inclusive(int a, int b, int step) {
return asList(countIterator_inclusive_step(a, b, step));
}
static public List countIteratorToList_inclusive(double a, double b, double step, IF1 f) {
return asList(countIterator_inclusive(a, b, step, f));
}
static public List countIteratorToList_inclusive(double a, double b, double step) {
return asList(countIterator_inclusive_step(a, b, step));
}
static public List countIteratorToList_inclusive(IF1 f, double a, double b, double step) {
return asList(countIterator_inclusive_step(a, b, step, f));
}
static public List countIteratorToList_inclusive(IF1 f, int a, int b) {
return countIteratorToList_inclusive(f, a, b, 1);
}
static public List countIteratorToList_inclusive(IF1 f, int a, int b, int step) {
return asList(countIterator_inclusive(a, b, step, f));
}
static public ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static public ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
static public Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
printStackTrace(__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();
}
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
static public A pcallF(IF0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
static public B pcallF(IF1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
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 "return jSpinnerCommitOnValidEdit(new JSpinner(new SpinnerNumberModel(value, m...";
}
});
}
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 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 File makeFileNameUnique_beforeExtension_startWith1_noDot(File f) {
File orig = f;
int n = 1;
do {
f = appendToFileBaseName(orig, str(n++));
} while (f.exists());
return f;
}
static public void saveImage(File f, BufferedImage img) {
if (hasJPEGExtension(f))
saveJPG(f, img);
else
savePNG(f, img);
}
static public String appendBracketed(Object o) {
String b = strOrNull(o);
return empty(b) ? "" : "" + " (" + b + ")";
}
static public String appendBracketed(String a, String b) {
return a + appendBracketed(b);
}
static public String fileInfo(File f) {
return renderFileInfo(f);
}
static public String fileInfo(String f) {
return renderFileInfo(newFile(f));
}
static public A uniqueConcept(Class c, Object... params) {
return uniqueConcept(db_mainConcepts(), c, params);
}
static public A uniqueConcept(Concepts cc, Class c, Object... params) {
AutoCloseable __1 = tempDBLock(cc);
try {
params = expandParams(c, params);
A x = findConceptWhere(cc, c, params);
if (x == null) {
x = unlisted(c);
csetAll(x, params);
cc.register(x);
} else {
}
return x;
} finally {
_close(__1);
}
}
static public